langchain-mcp-adapters¶
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 |
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
TYPE:
|
callbacks
|
Optional callbacks for handling notifications and events.
TYPE:
|
tool_interceptors
|
Optional list of tool call interceptors for modifying requests and responses.
TYPE:
|
tool_name_prefix
|
If
TYPE:
|
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()
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:
|
auto_initialize
|
Whether to automatically initialize the session
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the server name is not found in the connections |
| YIELDS | DESCRIPTION |
|---|---|
AsyncIterator[ClientSession]
|
An initialized |
get_tools
async
¶
Get a list of all tools from all connected servers.
| PARAMETER | DESCRIPTION |
|---|---|
server_name
|
Optional name of the server to get tools from.
If
TYPE:
|
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
TYPE:
|
uris
|
Optional resource URI or list of URIs to load. If not provided, all resources will be loaded. |
| 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:
|
exc_val
|
Exception value if an exception occurred.
TYPE:
|
exc_tb
|
Exception traceback if an exception occurred.
TYPE:
|
| 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. |
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
TYPE:
|
connection
|
Connection config to create a new session if session is
TYPE:
|
callbacks
|
Optional
TYPE:
|
tool_interceptors
|
Optional list of interceptors for tool call processing.
TYPE:
|
server_name
|
Name of the server these tools belong to.
TYPE:
|
tool_name_prefix
|
If
TYPE:
|
| 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:
|
name
|
Name of the prompt to load.
TYPE:
|
arguments
|
Optional arguments to pass to the prompt. |
| 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 and convert them to LangChain Blob objects.
| PARAMETER | DESCRIPTION |
|---|---|
session
|
MCP client session.
TYPE:
|
uris
|
List of URIs to load. If Note Dynamic resources will NOT be loaded when |
| 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:
|
handler
|
Async callable executing the tool. Can be called multiple times, skipped, or wrapped for error handling.
TYPE:
|
| 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
¶
Connection = (
StdioConnection | SSEConnection | StreamableHttpConnection | WebsocketConnection
)
SSEConnection
¶
Bases: TypedDict
Configuration for Server-Sent Events (SSE) transport connections to MCP.
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).
StdioConnection
¶
Bases: TypedDict
Configuration for stdio transport connections to MCP servers.
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.
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.
headers
instance-attribute
¶
headers: NotRequired[dict[str, Any] | None]
HTTP headers to send to the endpoint.
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).