Skip to content

Commit 280442b

Browse files
sydney-runklehntrlSydney Runkle
authored
feat(langchain): langchain.mcp namespace, MCPAdapter (#39939)
Adds `langchain.mcp`: adapt an MCP server into LangChain tools ready for `create_agent`. ```python from langchain.agents import create_agent from langchain.mcp import MCPAdapter adapter = MCPAdapter("https://example.com/mcp") agent = create_agent("anthropic:claude-sonnet-5", await adapter.list_tools()) ``` `langchain-mcp-adapters` stays the place for the full surface (interceptors, callbacks, prompts, resources). This is the short path for the common case. ## Public API `MCPAdapter(target, *, elicitation=None)`, with a `client` property, `list_tools(*, cache_mode="use")`, and async context management. `as_langchain_tool(tool, client, *, elicitation=None)` converts a single tool for callers managing their own client. `MCPAdapter` accepts anything `fastmcp.Client` accepts — a URL, `Path`, in-process server, `ClientTransport`, `MCPConfig` (or its dict form), or a pre-built `Client` — plus a FastMCP `ClientGroup` for a fleet of servers behind one client. Inference is FastMCP's, so new target types work without changes here. The target union is `MCPAdapterTarget`; it is not part of the package's public surface (it is only useful for annotating a `target`), but it stays importable from `langchain.mcp.adapter` for that purpose. An `MCPConfig` naming several servers yields one prefixed toolset from one adapter: ```python MCPAdapter({"mcpServers": {"notes": {"command": "python", "args": ["notes.py"]}, "web": {"url": "https://example.com/mcp"}}}) # -> ["notes_read_note", "web_get_weather", ...] ``` ## Tool conversion Tool results are ported from `langchain-mcp-adapters`, so a call reaches a model in the same shape either way. Results become LangChain content blocks (audio raises `NotImplementedError`); structured content becomes an `MCPToolArtifact`; `args_schema` is the tool's `input_schema`. Tool *metadata* is grouped under a single `mcp` namespace so a consumer can tell an MCP tool's provenance apart and keep tool-level fields distinct from the serving server's identity: ```python tool.metadata == { "mcp": { "tool": { "annotations": {"destructive_hint": True, ...}, # snake_case, from tool.annotations "_meta": {...}, # verbatim MCP `_meta` }, "server": {"name": "files", "version": "2.1.0", ...}, # from the live client connection }, } ``` Server identity comes off the connection (a `Tool` carries no server field) and is read at conversion time while the client is connected. This metadata rides onto the LangChain tool's `metadata`, so it also lands on the tool's traced run — `mcp.server.name` becomes filterable in traces. The examples PR uses the destructive hint to gate a tool behind human approval. An `isError=True` result becomes a `ToolMessage` with `status="error"` carrying the server's own error content, so the agent can correct itself instead of the run ending. Transport failures and unconvertible content still raise. FastMCP clients are reentrant and reference-counted, so the adapter adds no second layer — tools hold the client and stay callable after the adapter's context exits. ## Discovery caching `list_tools(cache_mode=...)` selects how discovery interacts with the client-side response cache (SEP-2549): `use` (default) serves a cached tool list within the server's TTL hint, `refresh` calls the server and repopulates it, `bypass` skips the cache. The cache and its per-principal isolation are configured on the client itself (`Client(cache=...)`); this only selects how discovery reads it. The default is `use` so a configured cache is honored — note this differs from a bare `ClientGroup.list_tools()`, whose own default is `refresh`. ## Elicitation Some MCP tools need input before they can finish. `elicitation="interrupt"` surfaces the question as a LangGraph interrupt: ```python adapter = MCPAdapter(server, elicitation="interrupt") paused = await agent.ainvoke({"messages": [...]}, config) [question] = paused["__interrupt__"][0].value["requests"] # {'key': 'date', 'message': 'What date would you like to book?', 'mode': 'form', # 'requested_schema': {...}} await agent.ainvoke( Command(resume={"responses": {question["key"]: {"action": "accept", "content": {"date": "2026-08-26"}}}}), config, ) ``` Answers correlate by the server's own request keys, so nothing extra is needed on resume. Several requests in one round share one interrupt; successive rounds each get their own. The payload types live in `langchain.mcp.elicitation`, split so the type system carries the protocol's rules: `mode` discriminates form from URL requests, and only an accept can carry content, narrowed to the scalar shapes the wire accepts. It is opt-in because a declared capability is a promise on the wire — servers only build flows that depend on it once a client says yes — so left unset, a server whose tool *requires* an answer refuses the call rather than running without one. The loop is driven through `session.call_tool(..., allow_input_required=True)` rather than a FastMCP handler, which would convert the `GraphInterrupt` into an MCP error. Resuming re-issues the call from its first round, since the interrupt unwound it; a server that asks before doing work repeats nothing, which the tests assert by counting tool-body executions. Scope is elicitation only. Embedded sampling and roots requests raise, since driving the loop by hand bypasses the FastMCP callbacks that answer them, as does a continuation round carrying only `request_state` — that is the protocol's long-running-work channel, and serving it would mean polling a remote server from inside a tool call. ## Building on FastMCP Handing the client to FastMCP is what keeps this small. Most of the protocol surface is inherited rather than written: - **Negotiation, per server.** FastMCP speaks both the 2025-11-25 `initialize` handshake and the 2026-07-28 `server/discover` revision, and picks per connection — so one agent can hold tools from servers on different revisions at once, with no protocol mode to choose. There is a test that builds exactly that agent. - **Transports and auth.** Inference covers URLs, script paths, in-process servers, and config dicts, while `auth="oauth"`, bearer tokens, custom `httpx` auth, and TLS via `verify` all arrive without code here. - **Fleets.** A `ClientGroup` target lets one adapter serve a fleet of servers, prefixing each server's tools and routing every call back to the client that serves it. - **Connection lifecycle.** Clients are reentrant and reference-counted, so tools outlive the adapter's context without a second layer of bookkeeping, and requests race the background session task so a dead HTTP session raises instead of hanging a tool call. - **The input-required flow (SEP-2322).** Elicitation intercepts a round at the session layer instead of reimplementing the multi-round protocol. - **In-process servers.** The whole unit suite drives real MCP servers with no subprocess and no socket. This requires `fastmcp>=4.0.0` — the GA line whose multi-server config routes to modern-protocol servers, which the `MCPConfig` and `ClientGroup` support rely on. ## Release note New `langchain.mcp` namespace. `MCPAdapter` adapts any target `fastmcp.Client` accepts — a URL, a local script, an in-process server, an `MCPConfig` naming several servers, or a pre-built client — as well as a FastMCP `ClientGroup`, into LangChain tools ready for `create_agent`. `MCPAdapter.list_tools(cache_mode=...)` discovers tools with optional client-side response caching. `as_langchain_tool` converts a single MCP tool for callers managing their own client. Tool metadata (annotations, `_meta`, and the serving server's identity) is grouped under an `mcp` namespace on each tool. `elicitation="interrupt"` surfaces a server's mid-call questions as LangGraph interrupts. Requires the `mcp` extra: `pip install "langchain[mcp]"`. ## Notes for review - A `Path` or script-path target launches a local subprocess with no opt-in keyword. Intended, and the target comes from application code rather than a model, but it loosens the previous default and is awkward to walk back once released. - Tool metadata is traced. Whatever a server puts in `_meta` reaches the tool's LangSmith run verbatim; keeping it nested under `mcp.tool._meta` (rather than flattened) keeps that clearly demarcated. - Two FastMCP internals are load-bearing, and both now fail loudly rather than silently. `elicitation="interrupt"` installs a sentinel handler purely to trip the SDK's identity comparison against its default callback, which is the only way the SDK lets a client declare the capability; a test asserts the negotiated capability so a change upstream cannot quietly stop servers asking. `_await_monitored` reaches for FastMCP's private `_await_with_session_monitoring`, without which a session dying mid-elicitation hangs the tool call; the fallback now warns. - `tests/unit_tests/mcp/conftest.py` grants `blockbuster` two narrow allowances, both caused upstream in FastMCP: entering a server `Context` resolves an optional dependency through `importlib.metadata` on every in-process request, and `mcp.client.session` imports `jsonschema` lazily on first tool call. --- *Prepared with the assistance of an AI agent.* --------- Signed-off-by: Hunter Lovell <[email protected]> Co-authored-by: Hunter Lovell <[email protected]> Co-authored-by: Hunter Lovell <[email protected]> Co-authored-by: Sydney Runkle <[email protected]>
1 parent f5ee2b6 commit 280442b

15 files changed

Lines changed: 3855 additions & 22 deletions

File tree

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
"""Main entrypoint into LangChain."""
22

3-
__version__ = "1.3.18"
3+
__version__ = "1.4.0"
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""LangChain MCP adapters for connecting MCP servers with LangChain applications.
2+
3+
Interrupt-driven elicitation has its own types — the interrupt payload, the
4+
answers a run resumes with, and the discriminator to recognize them by. Import
5+
those from `langchain.mcp.elicitation`.
6+
7+
!!! warning "This namespace is in beta"
8+
9+
`langchain.mcp` is actively being worked on and its API may change. Importing
10+
from it raises a `LangChainBetaWarning` once per process. Silence it with
11+
`warnings.filterwarnings("ignore", category=LangChainBetaWarning)`, or scope
12+
the suppression with `langchain_core._api.suppress_langchain_beta_warning()`.
13+
"""
14+
15+
import warnings
16+
17+
from langchain_core._api import LangChainBetaWarning
18+
19+
from langchain.mcp.adapter import MCPAdapter
20+
from langchain.mcp.tools import MCPToolArtifact, as_langchain_tool
21+
22+
# Warned on import rather than through `@beta`, which annotates a function or
23+
# class and so only fires once something is called. The status belongs to the
24+
# whole namespace, and a caller should learn it when they reach for it —
25+
# including when they import a submodule directly, which runs this module first.
26+
warnings.warn(
27+
"`langchain.mcp` is in beta. It is actively being worked on, so the API may change.",
28+
LangChainBetaWarning,
29+
stacklevel=2,
30+
)
31+
32+
__all__ = [
33+
"MCPAdapter",
34+
"MCPToolArtifact",
35+
"as_langchain_tool",
36+
]
Lines changed: 245 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
"""Adapt MCP tools into LangChain tools suitable for `create_agent`."""
2+
3+
from __future__ import annotations
4+
5+
from pathlib import Path
6+
from typing import TYPE_CHECKING, Any, Final, TypeAlias
7+
8+
from pydantic import AnyUrl, TypeAdapter, ValidationError
9+
from typing_extensions import Self
10+
11+
from langchain.mcp.elicitation import _arm_for_interrupts
12+
from langchain.mcp.tools import as_langchain_tool
13+
14+
try:
15+
from fastmcp.client import Client as FastMCPClient
16+
from fastmcp.client.group import ClientGroup
17+
from fastmcp.client.transports import ClientTransport
18+
from fastmcp.mcp_config import MCPConfig
19+
from mcp.server.mcpserver import MCPServer
20+
except ImportError as _import_error:
21+
msg = "Please install FastMCP to use `MCPAdapter` — `pip install fastmcp`."
22+
raise ImportError(msg) from _import_error
23+
24+
25+
if TYPE_CHECKING:
26+
from types import TracebackType
27+
28+
from fastmcp import FastMCP
29+
from langchain_core.tools import BaseTool
30+
31+
# `CacheMode` is the MCP SDK's own type (SEP-2549); FastMCP re-imports it
32+
# rather than defining its own, so this is the canonical source.
33+
from mcp.client.caching import CacheMode
34+
else:
35+
try:
36+
from fastmcp import FastMCP
37+
except ImportError:
38+
# In-process FastMCP servers, and multi-server `MCPConfig` targets, live
39+
# in the server half of FastMCP. The `mcp` extra installs it, but a
40+
# caller who reached this module through a client-only install
41+
# (`fastmcp-slim[client]`) can still use every other target type — so
42+
# the annotation degrades rather than the import failing, the same way
43+
# FastMCP degrades it in `fastmcp.client.transports.inference`.
44+
FastMCP = Any
45+
46+
47+
MCPAdapterTarget: TypeAlias = (
48+
FastMCPClient[Any]
49+
| ClientGroup
50+
| ClientTransport
51+
| FastMCP
52+
| MCPServer
53+
| AnyUrl
54+
| Path
55+
| MCPConfig
56+
| dict[str, Any]
57+
| str
58+
)
59+
"""Anything `MCPAdapter` accepts as its `target`.
60+
61+
Every transport `fastmcp.Client` accepts, plus a pre-built `fastmcp.Client`.
62+
63+
A `str` target is the one member narrowed relative to `fastmcp.Client`: it must
64+
be an `http`/`https` URL. Local servers are reached through `Path`, an explicit
65+
transport, or `MCPConfig` — see `MCPAdapter`.
66+
67+
`ClientGroup` is the one member `fastmcp.Client` does not accept at all, since a
68+
group is a peer of `Client` rather than a transport it could wrap.
69+
"""
70+
71+
72+
_URL_SCHEMES: Final = frozenset({"http", "https"})
73+
"""Schemes a `str` target may carry.
74+
75+
The only schemes `fastmcp.Client` can reach a server over from a string, so
76+
nothing that would have connected is forbidden here. It selects that branch on
77+
a bare `str.startswith("http")` though, which also admits strings that are not
78+
URLs at all — those fail on connect there, and on construction here.
79+
"""
80+
81+
_ANY_URL: Final = TypeAdapter(AnyUrl)
82+
83+
84+
def _validate_url_target(target: str) -> None:
85+
"""Reject a `str` target that is not an `http`/`https` URL.
86+
87+
`fastmcp.Client` infers a transport from a string by testing it as a
88+
filesystem path *before* testing it as a URL, so a string naming an
89+
existing `.py` or `.js` file launches that file as a subprocess. A string
90+
that reaches an application from configuration, a request body, or a model
91+
is expected to address a server over the network; letting it silently
92+
select local execution instead makes the dangerous reading the implicit
93+
one.
94+
95+
Args:
96+
target: The string passed as the adapter's target.
97+
98+
Raises:
99+
ValueError: If `target` is not an `http` or `https` URL.
100+
"""
101+
hint = (
102+
"To run a local MCP server over stdio, ask for it explicitly with "
103+
"`Path('server.py')`, a `fastmcp` transport, or an `MCPConfig` — a bare "
104+
"string is read as a URL so that it cannot silently become a subprocess."
105+
)
106+
try:
107+
url = _ANY_URL.validate_python(target)
108+
except ValidationError as validation_error:
109+
msg = f"MCP target {target!r} is not a valid URL. {hint}"
110+
raise ValueError(msg) from validation_error
111+
112+
# `AnyUrl` alone is not the boundary. It reads a Windows path such as
113+
# `C:\server.py` as the scheme `c` and accepts it — and on Windows that
114+
# path *does* resolve, so FastMCP would launch it. Schemes FastMCP cannot
115+
# infer a transport from at all (`file:`, `ws:`) are refused here too, for
116+
# an error that names the problem rather than "could not infer a transport".
117+
if url.scheme not in _URL_SCHEMES:
118+
msg = (
119+
f"MCP target {target!r} has scheme {url.scheme!r}, but a string target must "
120+
f"be an http or https URL. {hint}"
121+
)
122+
raise ValueError(msg)
123+
124+
125+
class MCPAdapter:
126+
"""Adapt an MCP target into LangChain tools.
127+
128+
`MCPAdapter` uses FastMCP for protocol negotiation and connection management,
129+
then converts discovered MCP tools into asynchronous LangChain tools. The
130+
resulting tools can be passed directly to `create_agent`.
131+
132+
Transport inference is delegated to `fastmcp.Client`, so a target may be a URL,
133+
a local script path (launched over stdio), an in-process server, or an already
134+
constructed client.
135+
136+
!!! warning "A string target must be an http(s) URL"
137+
138+
`fastmcp.Client` resolves a string by testing it as a filesystem path
139+
before testing it as a URL, so a string naming an existing `.py` or `.js`
140+
file launches that file as a subprocess. Because strings are the form a
141+
target most often arrives in from configuration or from a model,
142+
`MCPAdapter` rejects one that is not an `http` or `https` URL rather than
143+
let it select local execution. Reach a local server through `Path`, a
144+
`fastmcp` transport, or an `MCPConfig`, all of which say so explicitly.
145+
146+
A server that needs input mid-call is answered with a LangGraph
147+
`interrupt()`, so a human answers and the run resumes — see
148+
`langchain.mcp.elicitation`. This is the default: the adapter arms every
149+
client it builds to advertise the elicitation capability and drives the
150+
interrupt loop on each call. A server that never asks for input is
151+
unaffected, since the loop only runs when the server returns a request.
152+
153+
A pre-built client (or `ClientGroup`) that already carries its own
154+
elicitation handler is honored rather than overridden: its handler keeps
155+
answering, and the adapter leaves the client as the caller built it. Only a
156+
client with no handler is armed, and it is cloned first so the caller's own
157+
object is never mutated.
158+
159+
Args:
160+
target: MCP target accepted by `fastmcp.Client`, including an existing
161+
FastMCP client. A `str` must be an `http`/`https` URL.
162+
163+
Example:
164+
```python
165+
from langchain.agents import create_agent
166+
from langchain.mcp import MCPAdapter
167+
168+
async with MCPAdapter("https://example.com/mcp") as adapter:
169+
agent = create_agent("anthropic:claude-sonnet-5", await adapter.list_tools())
170+
result = await agent.ainvoke({"messages": [{"role": "user", "content": "..."}]})
171+
```
172+
"""
173+
174+
def __init__(self, target: MCPAdapterTarget) -> None:
175+
"""Initialize the adapter around a FastMCP target, client, or group.
176+
177+
Each underlying client is armed to answer elicitation with an interrupt,
178+
unless it already carries the caller's own handler, which is honored
179+
instead. A caller's client is cloned rather than mutated. See the class
180+
docstring.
181+
"""
182+
183+
def armed(client: FastMCPClient[Any]) -> FastMCPClient[Any]:
184+
if getattr(client, "_elicitation_callback", None) is not None:
185+
return client
186+
clone = client.new()
187+
_arm_for_interrupts(clone)
188+
return clone
189+
190+
if isinstance(target, ClientGroup):
191+
members = {name: armed(client) for name, client in target.clients.items()}
192+
self._client: FastMCPClient[Any] | ClientGroup = ClientGroup(members)
193+
elif isinstance(target, FastMCPClient):
194+
self._client = armed(target)
195+
else:
196+
if isinstance(target, str):
197+
_validate_url_target(target)
198+
client = FastMCPClient(target)
199+
_arm_for_interrupts(client)
200+
self._client = client
201+
202+
@property
203+
def client(self) -> FastMCPClient[Any] | ClientGroup:
204+
"""Return the underlying FastMCP client or group for advanced MCP operations."""
205+
return self._client
206+
207+
async def __aenter__(self) -> Self:
208+
"""Connect the underlying client or group for the duration of the context."""
209+
await self._client.__aenter__()
210+
return self
211+
212+
async def __aexit__(
213+
self,
214+
exc_type: type[BaseException] | None,
215+
exc_value: BaseException | None,
216+
traceback: TracebackType | None,
217+
) -> None:
218+
"""Release this context's hold on the underlying client or group."""
219+
await self._client.__aexit__(exc_type, exc_value, traceback)
220+
221+
async def list_tools(self, *, cache_mode: CacheMode = "use") -> list[BaseTool]:
222+
"""Discover and adapt MCP tools for use with LangChain.
223+
224+
Args:
225+
cache_mode: How discovery interacts with the client-side response
226+
cache (SEP-2549). `use` serves a cached tool list when one is
227+
present and still within the server's TTL hint, `refresh` calls
228+
the server and repopulates the cache, and `bypass` skips the
229+
cache entirely. The cache and its per-principal isolation are
230+
configured on the client itself (`Client(cache=...)`); this only
231+
selects how discovery reads it. Defaults to `use` so a
232+
configured cache is honored — note this differs from a bare
233+
`ClientGroup.list_tools()`, whose own default is `refresh`.
234+
235+
Returns:
236+
LangChain tools that invoke the corresponding MCP tools
237+
asynchronously. Each holds the adapter's client, so the tools
238+
stay callable after this adapter's context exits.
239+
"""
240+
async with self:
241+
remote_tools = await self._client.list_tools(cache_mode=cache_mode)
242+
return [await as_langchain_tool(tool, self._client) for tool in remote_tools]
243+
244+
245+
__all__ = ["MCPAdapter", "MCPAdapterTarget"]

0 commit comments

Comments
 (0)