Skip to content

langchain-mcp-adapters

PyPI - Version PyPI - License PyPI - Downloads

Reference documentation for the langchain-mcp-adapters package.

client

Client for connecting to multiple MCP servers and loading LC tools/resources.

This module provides the MultiServerMCPClient class for managing connections to multiple MCP servers and loading tools, prompts, and resources from them.

MultiServerMCPClient

Client for connecting to multiple MCP servers.

Loads LangChain-compatible tools, prompts and resources from MCP servers.

METHOD DESCRIPTION
__init__

Initialize a MultiServerMCPClient with MCP servers connections.

session

Connect to an MCP server and initialize a session.

get_tools

Get a list of all tools from all connected servers.

get_prompt

Get a prompt from a given MCP server.

get_resources

Get resources from MCP server(s).

__aenter__

Async context manager entry point.

__aexit__

Async context manager exit point.

__init__

__init__(
    connections: dict[str, Connection] | None = None,
    *,
    callbacks: Callbacks | None = None,
    tool_interceptors: list[ToolCallInterceptor] | None = None,
    tool_name_prefix: bool = False,
) -> None

Initialize a MultiServerMCPClient with MCP servers connections.

PARAMETER DESCRIPTION
connections

A dict mapping server names to connection configurations. If None, no initial connections are established.

TYPE: dict[str, Connection] | None DEFAULT: None

callbacks

Optional callbacks for handling notifications and events.

TYPE: Callbacks | None DEFAULT: None

tool_interceptors

Optional list of tool call interceptors for modifying requests and responses.

TYPE: list[ToolCallInterceptor] | None DEFAULT: None

tool_name_prefix

If True, tool names are prefixed with the server name using an underscore separator (e.g., "weather_search" instead of "search"). This helps avoid conflicts when multiple servers have tools with the same name. Defaults to False.

TYPE: bool DEFAULT: False

Basic usage (starting a new session on each tool call)

from langchain_mcp_adapters.client import MultiServerMCPClient

client = MultiServerMCPClient(
    {
        "math": {
            "command": "python",
            # Make sure to update to the full absolute path to your
            # math_server.py file
            "args": ["/path/to/math_server.py"],
            "transport": "stdio",
        },
        "weather": {
            # Make sure you start your weather server on port 8000
            "url": "http://localhost:8000/mcp",
            "transport": "http",
        }
    }
)
all_tools = await client.get_tools()

Explicitly starting a session

from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain_mcp_adapters.tools import load_mcp_tools

client = MultiServerMCPClient({...})
async with client.session("math") as session:
    tools = await load_mcp_tools(session)

session async

session(
    server_name: str, *, auto_initialize: bool = True
) -> AsyncIterator[ClientSession]

Connect to an MCP server and initialize a session.

PARAMETER DESCRIPTION
server_name

Name to identify this server connection

TYPE: str

auto_initialize

Whether to automatically initialize the session

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
ValueError

If the server name is not found in the connections

YIELDS DESCRIPTION
AsyncIterator[ClientSession]

An initialized ClientSession

get_tools async

get_tools(*, server_name: str | None = None) -> list[BaseTool]

Get a list of all tools from all connected servers.

PARAMETER DESCRIPTION
server_name

Optional name of the server to get tools from. If None, all tools from all servers will be returned.

TYPE: str | None DEFAULT: None

Note

A new session will be created for each tool call

RETURNS DESCRIPTION
list[BaseTool]

A list of LangChain tools

get_prompt async

get_prompt(
    server_name: str, prompt_name: str, *, arguments: dict[str, Any] | None = None
) -> list[HumanMessage | AIMessage]

Get a prompt from a given MCP server.

get_resources async

get_resources(
    server_name: str | None = None, *, uris: str | list[str] | None = None
) -> list[Blob]

Get resources from MCP server(s).

PARAMETER DESCRIPTION
server_name

Optional name of the server to get resources from. If None, all resources from all servers will be returned.

TYPE: str | None DEFAULT: None

uris

Optional resource URI or list of URIs to load. If not provided, all resources will be loaded.

TYPE: str | list[str] | None DEFAULT: None

RETURNS DESCRIPTION
list[Blob]

A list of LangChain Blob objects.

__aenter__ async

__aenter__() -> MultiServerMCPClient

Async context manager entry point.

RAISES DESCRIPTION
NotImplementedError

Context manager support has been removed.

__aexit__

__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Async context manager exit point.

PARAMETER DESCRIPTION
exc_type

Exception type if an exception occurred.

TYPE: type[BaseException] | None

exc_val

Exception value if an exception occurred.

TYPE: BaseException | None

exc_tb

Exception traceback if an exception occurred.

TYPE: TracebackType | None

RAISES DESCRIPTION
NotImplementedError

Context manager support has been removed.

tools

Tools adapter for converting MCP tools to LangChain tools.

This module provides functionality to convert MCP tools into LangChain-compatible tools, handle tool execution, and manage tool conversion between the two formats.

FUNCTION DESCRIPTION
load_mcp_tools

Load all available MCP tools and convert them to LangChain tools.

MCPToolArtifact

Bases: TypedDict

Artifact returned from MCP tool calls.

This TypedDict wraps the structured content from MCP tool calls, allowing for future extension if MCP adds more fields to tool results.

ATTRIBUTE DESCRIPTION
structured_content

The structured content returned by the MCP tool, corresponding to the structuredContent field in CallToolResult.

TYPE: dict[str, Any]

load_mcp_tools async

load_mcp_tools(
    session: ClientSession | None,
    *,
    connection: Connection | None = None,
    callbacks: Callbacks | None = None,
    tool_interceptors: list[ToolCallInterceptor] | None = None,
    server_name: str | None = None,
    tool_name_prefix: bool = False,
) -> list[BaseTool]

Load all available MCP tools and convert them to LangChain tools.

PARAMETER DESCRIPTION
session

The MCP client session. If None, connection must be provided.

TYPE: ClientSession | None

connection

Connection config to create a new session if session is None.

TYPE: Connection | None DEFAULT: None

callbacks

Optional Callbacks for handling notifications and events.

TYPE: Callbacks | None DEFAULT: None

tool_interceptors

Optional list of interceptors for tool call processing.

TYPE: list[ToolCallInterceptor] | None DEFAULT: None

server_name

Name of the server these tools belong to.

TYPE: str | None DEFAULT: None

tool_name_prefix

If True and server_name is provided, tool names will be prefixed w/ server name (e.g., "weather_search" instead of "search").

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
list[BaseTool]

List of LangChain tools. Tool annotations are returned as part of the tool metadata object.

RAISES DESCRIPTION
ValueError

If neither session nor connection is provided.

prompts

Prompts adapter for converting MCP prompts to LangChain messages.

This module provides functionality to convert MCP prompt messages into LangChain message objects, handling both user and assistant message types.

FUNCTION DESCRIPTION
load_mcp_prompt

Load MCP prompt and convert to LangChain messages.

load_mcp_prompt async

load_mcp_prompt(
    session: ClientSession, name: str, *, arguments: dict[str, Any] | None = None
) -> list[HumanMessage | AIMessage]

Load MCP prompt and convert to LangChain messages.

PARAMETER DESCRIPTION
session

The MCP client session.

TYPE: ClientSession

name

Name of the prompt to load.

TYPE: str

arguments

Optional arguments to pass to the prompt.

TYPE: dict[str, Any] | None DEFAULT: None

RETURNS DESCRIPTION
list[HumanMessage | AIMessage]

A list of LangChain messages converted from the MCP prompt.

resources

Resources adapter for converting MCP resources to LangChain Blob objects.

This module provides functionality to convert MCP resources into LangChain Blob objects, handling both text and binary resource content types.

FUNCTION DESCRIPTION
load_mcp_resources

Load MCP resources and convert them to LangChain Blob objects.

load_mcp_resources async

load_mcp_resources(
    session: ClientSession, *, uris: str | list[str] | None = None
) -> list[Blob]

Load MCP resources and convert them to LangChain Blob objects.

PARAMETER DESCRIPTION
session

MCP client session.

TYPE: ClientSession

uris

List of URIs to load. If None, all resources will be loaded.

Note

Dynamic resources will NOT be loaded when None is specified, as they require parameters and are ignored by the MCP SDK's session.list_resources() method.

TYPE: str | list[str] | None DEFAULT: None

RETURNS DESCRIPTION
list[Blob]

A list of LangChain Blob objects.

RAISES DESCRIPTION
RuntimeError

If an error occurs while fetching a resource.

interceptors

Interceptor interfaces and types for MCP client tool call lifecycle management.

This module provides an interceptor interface for wrapping and controlling MCP tool call execution with a handler callback pattern.

In the future, we might add more interceptors for other parts of the request / result lifecycle, for example to support elicitation.

ToolCallInterceptor

Bases: Protocol

Protocol for tool call interceptors using handler callback pattern.

Interceptors wrap tool execution to enable request/response modification, retry logic, caching, rate limiting, and other cross-cutting concerns. Multiple interceptors compose in "onion" pattern (first is outermost).

The handler can be called multiple times (retry), skipped (caching/short-circuit), or wrapped with error handling. Each handler call is independent.

Similar to LangChain's middleware pattern but adapted for MCP remote tools.

METHOD DESCRIPTION
__call__

Intercept tool execution with control over handler invocation.

__call__ async

__call__(
    request: MCPToolCallRequest,
    handler: Callable[[MCPToolCallRequest], Awaitable[MCPToolCallResult]],
) -> MCPToolCallResult

Intercept tool execution with control over handler invocation.

PARAMETER DESCRIPTION
request

Tool call request containing name, args, headers, and context (server_name, runtime). Access context fields like request.server_name.

TYPE: MCPToolCallRequest

handler

Async callable executing the tool. Can be called multiple times, skipped, or wrapped for error handling.

TYPE: Callable[[MCPToolCallRequest], Awaitable[MCPToolCallResult]]

RETURNS DESCRIPTION
MCPToolCallResult

Final MCPToolCallResult from tool execution or interceptor logic.

callbacks

Types for callbacks.

CallbackContext dataclass

LangChain MCP client callback context.

Callbacks dataclass

Callbacks for the LangChain MCP client.

METHOD DESCRIPTION
to_mcp_format

Convert the LangChain MCP client callbacks to MCP SDK callbacks.

to_mcp_format

to_mcp_format(*, context: CallbackContext) -> _MCPCallbacks

Convert the LangChain MCP client callbacks to MCP SDK callbacks.

Injects the LangChain CallbackContext as the last argument.

sessions

Session management for different MCP transport types.

This module provides connection configurations and session management for various MCP transport types including stdio, SSE, WebSocket, and streamable HTTP.

Connection module-attribute

SSEConnection

Bases: TypedDict

Configuration for Server-Sent Events (SSE) transport connections to MCP.

url instance-attribute

url: str

The URL of the SSE endpoint to connect to.

headers instance-attribute

headers: NotRequired[dict[str, Any] | None]

HTTP headers to send to the SSE endpoint.

timeout instance-attribute

timeout: NotRequired[float]

HTTP timeout.

Default is 5 seconds. If the server takes longer to respond, you can increase this value.

sse_read_timeout instance-attribute

sse_read_timeout: NotRequired[float]

SSE read timeout.

Default is 300 seconds (5 minutes). This is how long the client will wait for a new event before disconnecting.

session_kwargs instance-attribute

session_kwargs: NotRequired[dict[str, Any] | None]

Additional keyword arguments to pass to the ClientSession.

httpx_client_factory instance-attribute

httpx_client_factory: NotRequired[McpHttpClientFactory | None]

Custom factory for httpx.AsyncClient (optional).

auth instance-attribute

auth: NotRequired[Auth]

Optional authentication for the HTTP client.

StdioConnection

Bases: TypedDict

Configuration for stdio transport connections to MCP servers.

command instance-attribute

command: str

The executable to run to start the server.

args instance-attribute

args: list[str]

Command line arguments to pass to the executable.

env instance-attribute

env: NotRequired[dict[str, str] | None]

The environment to use when spawning the process.

If not specified or set to None, a subset of the default environment variables from the current process will be used.

Please refer to the MCP SDK documentation for details on which environment variables are included by default. The behavior varies by operating system.

https://github.com/modelcontextprotocol/python-sdk/blob/c47c767ff437ee88a19e6b9001e2472cb6f7d5ed/src/mcp/client/stdio/__init__.py#L51

cwd instance-attribute

cwd: NotRequired[str | Path | None]

The working directory to use when spawning the process.

encoding instance-attribute

encoding: NotRequired[str]

The text encoding used when sending/receiving messages to the server.

Default is 'utf-8'.

encoding_error_handler instance-attribute

encoding_error_handler: NotRequired[EncodingErrorHandler]

The text encoding error handler.

See https://docs.python.org/3/library/codecs.html#codec-base-classes for explanations of possible values.

Default is 'strict', which raises an error on encoding/decoding errors.

session_kwargs instance-attribute

session_kwargs: NotRequired[dict[str, Any] | None]

Additional keyword arguments to pass to the ClientSession.

StreamableHttpConnection

Bases: TypedDict

Connection configuration for Streamable HTTP transport.

url instance-attribute

url: str

The URL of the endpoint to connect to.

headers instance-attribute

headers: NotRequired[dict[str, Any] | None]

HTTP headers to send to the endpoint.

timeout instance-attribute

HTTP timeout.

sse_read_timeout instance-attribute

sse_read_timeout: NotRequired[timedelta]

How long (in seconds) the client will wait for a new event before disconnecting. All other HTTP operations are controlled by timeout.

terminate_on_close instance-attribute

terminate_on_close: NotRequired[bool]

Whether to terminate the session on close.

session_kwargs instance-attribute

session_kwargs: NotRequired[dict[str, Any] | None]

Additional keyword arguments to pass to the ClientSession.

httpx_client_factory instance-attribute

httpx_client_factory: NotRequired[McpHttpClientFactory | None]

Custom factory for httpx.AsyncClient (optional).

auth instance-attribute

auth: NotRequired[Auth]

Optional authentication for the HTTP client.

WebsocketConnection

Bases: TypedDict

Configuration for WebSocket transport connections to MCP servers.

url instance-attribute

url: str

The URL of the Websocket endpoint to connect to.

session_kwargs instance-attribute

session_kwargs: NotRequired[dict[str, Any] | None]

Additional keyword arguments to pass to the ClientSession