The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
docs(langchain): runnable `langchain.mcp` examples (#39976)
Sydney Runkle8330dfe98798
diff --git a/libs/langchain_v1/examples/mcp/README.md b/libs/langchain_v1/examples/mcp/README.mdnew file mode 100644index 0000000000..2c3340436e--- /dev/null+++ b/libs/langchain_v1/examples/mcp/README.md@@ -0,0 +1,31 @@+# `langchain.mcp` examples++Runnable, self-contained scripts. Each starts whatever MCP server it needs, so+there is nothing to launch separately.++```bash+uv sync --extra mcp --extra anthropic+export ANTHROPIC_API_KEY=... # needed by the examples that run an agent+uv run examples/mcp/transports.py+```++| Example | Shows | Model | Network |+|---|---|:-:|:-:|+| `transports.py` | one adapter over in-memory, stdio, and HTTP | | |+| `remote_server.py` | pointing the adapter at a public MCP server | ✅ | ✅ |+| `multi_server.py` | several servers behind one adapter, tools prefixed per server | ✅ | |+| `graph_factory.py` | one long-lived adapter shared by every run of a `langgraph dev` graph | | |+| `protocol_eras.py` | one agent holding tools from both MCP protocol eras | ✅ | |+| `tool_errors.py` | a failing tool reaching the model so it can retry | ✅ | |+| `elicitation.py` | a server asking a human mid-call, via `interrupt()` | ✅ | |+| `destructive_interrupt.py` | gating destructive tools behind approval, from tool metadata | ✅ | |+| `auth_bearer.py` | a server behind a static bearer token | | |+| `auth_oauth.py` | a full OAuth 2.1 flow with dynamic client registration | | |++`remote_server.py` calls DeepWiki, a public MCP server, so it needs internet+access. `auth_oauth.py` opens a browser tab; the demo authorization server+auto-approves, so it redirects straight back.++`_servers.py` holds the small MCP servers the examples share, and+`_stdio_server.py` is the entry point launched as a subprocess over stdio.+Neither is part of the API being demonstrated.diff --git a/libs/langchain_v1/examples/mcp/_fleet_servers.py b/libs/langchain_v1/examples/mcp/_fleet_servers.pynew file mode 100644index 0000000000..6e29a99cb9--- /dev/null+++ b/libs/langchain_v1/examples/mcp/_fleet_servers.py@@ -0,0 +1,36 @@+"""Run the two guarded MCP servers the graph factory talks to.++`graph_factory.py` points `SERVERS` at fixed ports; this starts a server on+each. Both verify tokens against the shared keypair (`MCP_DEMO_KEYFILE`), the+same one `langgraph dev` mints with, so a token minted in the factory process+validates here.++ MCP_DEMO_KEYFILE=/path/to/keys.json uv run examples/mcp/_fleet_servers.py+"""++from __future__ import annotations++import multiprocessing++from _servers import PUBLIC_KEY, run_guarded_server++PORTS = {"calendar": 8001, "docs": 8002}+++def main() -> None:+ procs = [+ multiprocessing.Process(+ target=run_guarded_server,+ args=("127.0.0.1", port, name, PUBLIC_KEY),+ daemon=True,+ )+ for name, port in PORTS.items()+ ]+ for proc in procs:+ proc.start()+ for proc in procs:+ proc.join()+++if __name__ == "__main__":+ main()diff --git a/libs/langchain_v1/examples/mcp/_servers.py b/libs/langchain_v1/examples/mcp/_servers.pynew file mode 100644index 0000000000..2b5d41786b--- /dev/null+++ b/libs/langchain_v1/examples/mcp/_servers.py@@ -0,0 +1,211 @@+"""Tiny MCP servers the examples share, so each example stays about one idea.++Nothing here is specific to LangChain — these are plain FastMCP servers. The+`run_*` functions exist because a server reached over stdio or HTTP has to be+started as its own process, and that entry point cannot be a lambda.+"""++from __future__ import annotations++import json+import os+from pathlib import Path++from fastmcp import Context, FastMCP+from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPair+from fastmcp.server.dependencies import get_access_token+from mcp.types import (+ ElicitRequest,+ ElicitRequestFormParams,+ ElicitResult,+ InputRequiredResult,+ TextContent,+ ToolAnnotations,+)+from pydantic import SecretStr+++def weather_server() -> FastMCP[None]:+ """A server with one tool that always succeeds."""+ mcp: FastMCP[None] = FastMCP("weather")++ @mcp.tool+ def get_forecast(city: str) -> str:+ """Report the forecast for a city."""+ return f"{city}: 18C and clear."++ return mcp+++def calculator_server() -> FastMCP[None]:+ """A server whose tool reports failure for input it cannot handle."""+ mcp: FastMCP[None] = FastMCP("calculator")++ @mcp.tool+ def divide(numerator: float, denominator: float) -> str:+ """Divide two numbers."""+ if denominator == 0:+ # Raising inside a tool becomes an MCP error result (`isError=True`)+ # rather than a transport failure, which is what lets the agent see+ # it and retry. See `tool_errors.py`.+ msg = "Cannot divide by zero. Choose a non-zero denominator."+ raise ValueError(msg)+ return str(numerator / denominator)++ return mcp+++def files_server() -> FastMCP[None]:+ """A server with a read-only tool and a destructive one.++ `delete_file` sets `destructiveHint=True`; the adapter surfaces that as+ `metadata["mcp"]["tool"]["annotations"]["destructive_hint"]`, which+ `destructive_interrupt.py` uses to gate the tool behind human approval.+ """+ mcp: FastMCP[None] = FastMCP("files")++ @mcp.tool+ def list_files() -> list[str]:+ """List the files in the workspace."""+ return ["report.md", "notes.txt"]++ @mcp.tool(annotations=ToolAnnotations(destructiveHint=True))+ def delete_file(path: str) -> str:+ """Delete a file from the workspace."""+ return f"Deleted {path}."++ return mcp+++def booking_server() -> FastMCP[None]:+ """A server whose tool cannot finish without an answer from a human.++ Uses the guard pattern: the tool checks whether the answer it needs has+ arrived and, if not, returns an `InputRequiredResult` describing the+ question instead of doing any work. Returning early is what makes the call+ safe to replay when the run resumes.+ """+ mcp: FastMCP[None] = FastMCP("booking")++ @mcp.tool+ async def book_table(party_size: int, ctx: Context) -> list[TextContent] | InputRequiredResult:+ """Book a restaurant table. Asks the user which date to book."""+ answers = ctx.input_responses+ if not answers or "date" not in answers:+ return InputRequiredResult(+ input_requests={+ "date": ElicitRequest(+ method="elicitation/create",+ params=ElicitRequestFormParams(+ mode="form",+ message="What date would you like to book?",+ requested_schema={+ "type": "object",+ "properties": {"date": {"type": "string", "format": "date"}},+ "required": ["date"],+ },+ ),+ )+ },+ request_state="awaiting-date",+ )++ answer = answers["date"]+ if not isinstance(answer, ElicitResult) or answer.action != "accept" or not answer.content:+ return [TextContent(type="text", text="No date given, so nothing was booked.")]+ date = answer.content["date"]+ return [TextContent(type="text", text=f"Booked a table for {party_size} on {date}.")]++ return mcp+++def run_weather_stdio() -> None:+ """Entry point for a weather server spoken to over stdio."""+ weather_server().run()+++def run_calculator_stdio() -> None:+ """Entry point for a calculator server spoken to over stdio."""+ calculator_server().run()+++def run_weather_http(host: str, port: int) -> None:+ """Entry point for a weather server served over HTTP."""+ weather_server().run(+ transport="http", host=host, port=port, show_banner=False, log_level="warning"+ )+++def run_calculator_http(host: str, port: int) -> None:+ """Entry point for a calculator server served over HTTP."""+ calculator_server().run(+ transport="http", host=host, port=port, show_banner=False, log_level="warning"+ )+++ISSUER = "https://demo.issuer"+AUDIENCE = "mcp-fleet"+++def _load_or_generate_keys() -> RSAKeyPair:+ """Return one keypair shared across processes, or a fresh one per process.++ A single process (the `run_server_in_process` examples) can generate its+ own keypair and pass its public half to the server. A multi-process demo+ cannot: the `langgraph dev` worker that mints tokens and the server process+ that verifies them are different interpreters. Point both at the same PEM+ file via `MCP_DEMO_KEYFILE` and they share one keypair; leave it unset and+ every process keeps its own, exactly as before.+ """+ keyfile = os.environ.get("MCP_DEMO_KEYFILE")+ if keyfile:+ data = json.loads(Path(keyfile).read_text())+ return RSAKeyPair(private_key=SecretStr(data["private_key"]), public_key=data["public_key"])+ return RSAKeyPair.generate()+++_KEYS = _load_or_generate_keys()+"""Stands in for an identity provider, so the examples can mint real tokens."""++PUBLIC_KEY = _KEYS.public_key+"""Pass this to `run_guarded_server`; see why in its docstring."""+++def token_for(user: str) -> str:+ """Mint an access token identifying `user`.++ The stand-in for whatever a deployment already has: an OAuth gateway that+ exchanges for a per-user token, or a provider from `fastmcp.client.auth` —+ `OAuth(mcp_url=..., token_storage=<per-user store>)` runs the full+ authorization-code flow per identity, which `auth_oauth.py` demonstrates.+ """+ return _KEYS.create_token(subject=user, issuer=ISSUER, audience=AUDIENCE)+++def run_guarded_server(host: str, port: int, name: str, public_key: str) -> None:+ """Serve a token-guarded server whose one tool reports who called it.++ The key is a parameter rather than read from this module: the server runs+ in its own process, which re-imports this file and would otherwise mint a+ second, unrelated key pair.+ """+ mcp: FastMCP[None] = FastMCP(+ name,+ auth=JWTVerifier(public_key=public_key, issuer=ISSUER, audience=AUDIENCE),+ # Opt into client-side response caching (SEP-2549): the server stamps+ # each cacheable result with this TTL and a `private` scope, so a client+ # holding a `CacheConfig` can serve a repeat `tools/list` from its own+ # store instead of the wire. Without these hints the server sends+ # `ttlMs: 0` and nothing caches, which is why arbitrary third-party+ # servers cannot be relied on for this.+ cache_ttl=60,+ cache_scope="private",+ )++ @mcp.tool+ def whoami() -> str:+ """Report the identity the server derived from the access token."""+ token = get_access_token()+ return "unauthenticated" if token is None else str(token.claims.get("sub"))++ mcp.run(transport="http", host=host, port=port, show_banner=False, log_level="warning")diff --git a/libs/langchain_v1/examples/mcp/_stdio_server.py b/libs/langchain_v1/examples/mcp/_stdio_server.pynew file mode 100644index 0000000000..e4a97cfccd--- /dev/null+++ b/libs/langchain_v1/examples/mcp/_stdio_server.py@@ -0,0 +1,13 @@+"""Run one of the shared servers over stdio, chosen by argv.++`MCPAdapter` launches this as a subprocess; it is not part of the API being+demonstrated.+"""++import sys++from _servers import run_calculator_stdio, run_weather_stdio++if __name__ == "__main__":+ which = sys.argv[1] if len(sys.argv) > 1 else "weather"+ (run_calculator_stdio if which == "calculator" else run_weather_stdio)()diff --git a/libs/langchain_v1/examples/mcp/auth.py b/libs/langchain_v1/examples/mcp/auth.pynew file mode 100644index 0000000000..b98aa404cf--- /dev/null+++ b/libs/langchain_v1/examples/mcp/auth.py@@ -0,0 +1,28 @@+"""Custom auth so `langgraph dev` knows which user a run belongs to.++The handler maps the `x-user-id` header to a user identity. That identity is+what `graph_factory.make_graph` reads off `runtime.user` and mints an MCP token+for, so each run talks to the fleet as its own user. A real deployment+validates a credential against an identity provider and returns the user it+resolves to; here the header is trusted directly, which is enough to+demonstrate per-user routing. (`x-api-key` is reserved by the LangGraph SDK for+its own auth, so the demo uses a different header.)++Wired in via `langgraph.json`.+"""++from __future__ import annotations++from langgraph_sdk import Auth++auth = Auth()+++async def authenticate(headers: dict) -> Auth.types.MinimalUserDict:+ """Resolve the caller from `x-user-id`, rejecting requests without one."""+ user_id = headers.get(b"x-user-id")+ if not user_id:+ raise Auth.exceptions.HTTPException(status_code=401, detail="Missing x-user-id")+ identity = user_id.decode() if isinstance(user_id, bytes) else str(user_id)+ return {"identity": identity}diff --git a/libs/langchain_v1/examples/mcp/auth_bearer.py b/libs/langchain_v1/examples/mcp/auth_bearer.pynew file mode 100644index 0000000000..c915e96f1c--- /dev/null+++ b/libs/langchain_v1/examples/mcp/auth_bearer.py@@ -0,0 +1,61 @@+"""A server behind a static bearer token.++The simple end of MCP auth: the server never issues credentials, it only+verifies the token arriving in `Authorization: Bearer <token>`. No discovery,+no browser, no refresh — you provisioned the token out of band and the client+presents it.++ uv run examples/mcp/auth_bearer.py+"""++from __future__ import annotations++import asyncio++from fastmcp import FastMCP+from fastmcp.client import Client+from fastmcp.server.auth.providers.jwt import StaticTokenVerifier+from fastmcp.utilities.tests import run_server_in_process++from langchain.mcp import MCPAdapter++TOKEN = "demo-weather-token" # noqa: S105+++def run_guarded_server(host: str, port: int) -> None:+ """Serve a weather server that only answers callers presenting `TOKEN`."""+ # Demo only — `StaticTokenVerifier` holds tokens in plaintext memory. A real+ # deployment uses `JWTVerifier` against an IdP's JWKS, or OAuth (see+ # `auth_oauth.py`).+ mcp: FastMCP[None] = FastMCP(+ "weather",+ auth=StaticTokenVerifier(tokens={TOKEN: {"client_id": "demo", "scopes": ["read"]}}),+ )++ @mcp.tool+ def get_forecast(city: str) -> str:+ """Report the forecast for a city."""+ return f"{city}: 18C and clear."++ mcp.run(transport="http", host=host, port=port, show_banner=False, log_level="warning")+++async def main() -> None:+ """Call the guarded server with, and without, the token."""+ with run_server_in_process(run_guarded_server) as url:+ # `auth` takes a bearer token string, the literal "oauth", or any+ # `httpx2.Auth`. A config dict takes the same key per server.+ async with MCPAdapter(Client(f"{url}/mcp", auth=TOKEN)) as adapter:+ [forecast] = await adapter.list_tools()+ [block] = await forecast.ainvoke({"city": "Oslo"})+ print("with token: ", block["text"])++ try:+ async with MCPAdapter(f"{url}/mcp") as adapter:+ await adapter.list_tools()+ except Exception as exc:+ print("without token:", type(exc).__name__)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/libs/langchain_v1/examples/mcp/auth_oauth.py b/libs/langchain_v1/examples/mcp/auth_oauth.pynew file mode 100644index 0000000000..569b3fbc09--- /dev/null+++ b/libs/langchain_v1/examples/mcp/auth_oauth.py@@ -0,0 +1,77 @@+"""A server behind a full OAuth 2.1 flow, with no client credentials up front.++This one process plays two roles that are normally separate:++- Resource Server: serves `/mcp` and rejects unauthenticated calls with a 401+ pointing at its protected-resource metadata.+- Authorization Server: serves discovery, `/register`, `/authorize`, `/token`.++In production those split — the resource server is yours, the authorization+server is Auth0 / WorkOS / Okta. FastMCP ships providers for those, and the flow+the client runs is identical, which is the point of the spec.++Dynamic Client Registration is what makes this feel plug-and-play: the client+registers itself at runtime instead of you pre-provisioning a client ID.+`InMemoryOAuthProvider` auto-approves, so the browser tab opens and redirects+straight back; a real server would show login and consent there.++ uv run examples/mcp/auth_oauth.py++Opens a browser window to complete the flow.+"""++from __future__ import annotations++import asyncio++from fastmcp import FastMCP+from fastmcp.client import Client+from fastmcp.server.auth.providers.in_memory import InMemoryOAuthProvider+from fastmcp.server.dependencies import get_access_token+from fastmcp.utilities.tests import run_server_in_process+from mcp.server.auth.settings import ClientRegistrationOptions++from langchain.mcp import MCPAdapter+++def run_oauth_server(host: str, port: int) -> None:+ """Serve a calendar server that mints its own tokens."""+ # `base_url` must match the URL clients actually reach: it is advertised in+ # discovery and used as the OAuth `resource`.+ auth = InMemoryOAuthProvider(+ base_url=f"http://127.0.0.1:{port}",+ client_registration_options=ClientRegistrationOptions(+ enabled=True,+ valid_scopes=["calendar:read"],+ default_scopes=["calendar:read"],+ ),+ required_scopes=["calendar:read"],+ )+ mcp: FastMCP[None] = FastMCP("calendar", auth=auth)++ @mcp.tool+ def whoami() -> str:+ """Report the identity the server derived from the access token."""+ token = get_access_token()+ if token is None:+ return "unauthenticated"+ return f"client_id={token.client_id} scopes={token.scopes}"++ mcp.run(transport="http", host=host, port=port, show_banner=False, log_level="warning")+++async def main() -> None:+ """Register, authorize, and call the guarded tool."""+ with run_server_in_process(run_oauth_server) as url:+ # "oauth" runs discovery, dynamic registration, the browser redirect,+ # and the token exchange. Tokens are held in memory, so each run+ # repeats the browser step; pass `OAuth(..., token_storage=...)` to+ # persist them.+ async with MCPAdapter(Client(f"{url}/mcp", auth="oauth")) as adapter:+ [whoami] = await adapter.list_tools()+ [block] = await whoami.ainvoke({})+ print("authenticated as:", block["text"])+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/libs/langchain_v1/examples/mcp/destructive_interrupt.py b/libs/langchain_v1/examples/mcp/destructive_interrupt.pynew file mode 100644index 0000000000..36e7a0716f--- /dev/null+++ b/libs/langchain_v1/examples/mcp/destructive_interrupt.py@@ -0,0 +1,80 @@+"""Gate destructive MCP tools behind human approval.++An MCP server can flag a tool as destructive (`destructiveHint=True`). The+adapter surfaces that on the LangChain tool as+`metadata["mcp"]["tool"]["annotations"]["destructive_hint"]`, so a client can+decide how to treat it without hardcoding tool names.++Here we read that hint to build the `interrupt_on` map for+`HumanInTheLoopMiddleware`: destructive tools pause for approval, everything+else runs untouched. Because the gate is derived from metadata, it covers+whatever destructive tools a server happens to expose.++ uv run examples/mcp/destructive_interrupt.py+"""++from __future__ import annotations++import asyncio+from typing import TYPE_CHECKING, Any++from _servers import files_server+from langgraph.checkpoint.memory import InMemorySaver+from langgraph.types import Command++from langchain.agents import create_agent+from langchain.agents.middleware import HumanInTheLoopMiddleware+from langchain.agents.middleware.human_in_the_loop import InterruptOnConfig+from langchain.mcp import MCPAdapter++if TYPE_CHECKING:+ from langchain_core.tools import BaseTool+++def _is_destructive(tool: BaseTool) -> bool:+ """Read the MCP destructive hint off the adapter's tool metadata."""+ annotations = (tool.metadata or {}).get("mcp", {}).get("tool", {}).get("annotations", {})+ return annotations.get("destructive_hint", False)+++def _describe(tool_call: Any, _state: Any, _runtime: Any) -> str:+ """Format the approval prompt from the pending tool call."""+ return f"Approve destructive call {tool_call['name']}({tool_call['args']})?"+++async def main() -> None:+ """Run the agent so a destructive tool pauses for approval, then approve it."""+ async with MCPAdapter(files_server()) as adapter:+ tools = await adapter.list_tools()++ # The filter: build the interrupt map from metadata, not tool names.+ interrupt_on: dict[str, bool | InterruptOnConfig] = {+ tool.name: InterruptOnConfig(allowed_decisions=["approve", "reject"], description=_describe)+ for tool in tools+ if _is_destructive(tool)+ }+ print("gated tools:", sorted(interrupt_on))++ agent = create_agent(+ "anthropic:claude-sonnet-5",+ tools,+ middleware=[HumanInTheLoopMiddleware(interrupt_on=interrupt_on)],+ checkpointer=InMemorySaver(), # resuming a paused run needs persistence+ )+ config: Any = {"configurable": {"thread_id": "files-1"}}++ paused = await agent.ainvoke(+ {"messages": [{"role": "user", "content": "Delete report.md."}]}, config+ )++ [interrupt] = paused["__interrupt__"]+ [request] = interrupt.value["action_requests"]+ print(f"paused for approval: {request['description']}")++ # Approve and let the tool run. A `reject` would skip it and tell the model.+ resumed = await agent.ainvoke(Command(resume={"decisions": [{"type": "approve"}]}), config)+ print("agent:", resumed["messages"][-1].text)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/libs/langchain_v1/examples/mcp/elicitation.py b/libs/langchain_v1/examples/mcp/elicitation.pynew file mode 100644index 0000000000..4c32c9fca5--- /dev/null+++ b/libs/langchain_v1/examples/mcp/elicitation.py@@ -0,0 +1,53 @@+"""A server that needs input mid-call, answered by a human.++Some MCP tools cannot finish without asking something. `MCPAdapter` surfaces the+question as a LangGraph `interrupt()`, so the person already reviewing the+agent's work answers it and the run resumes.++The adapter arms every client it builds to advertise the elicitation capability,+so this works without any opt-in — a server only asks a client that made the+promise on the wire, and the adapter makes it for you.++ uv run examples/mcp/elicitation.py+"""++from __future__ import annotations++import asyncio+from typing import Any++from _servers import booking_server+from langgraph.checkpoint.memory import InMemorySaver+from langgraph.types import Command++from langchain.agents import create_agent+from langchain.mcp import MCPAdapter+++async def main() -> None:+ """Book a table, answering the server's question from here."""+ async with MCPAdapter(booking_server()) as adapter:+ tools = await adapter.list_tools()++ # Resuming needs persistence, so the interrupted run has somewhere to wait.+ agent = create_agent("anthropic:claude-sonnet-5", tools, checkpointer=InMemorySaver())+ config: Any = {"configurable": {"thread_id": "booking-1"}}++ paused = await agent.ainvoke(+ {"messages": [{"role": "user", "content": "Book a table for 4."}]}, config+ )++ [interrupt] = paused["__interrupt__"]+ [question] = interrupt.value["requests"]+ print(f"server asks ({question['mode']}): {question['message']}")++ # Answers are keyed by the server's own request key, so nothing has to be+ # tracked across the pause. `decline` or `cancel` would refuse instead.+ answer = {"action": "accept", "content": {"date": "2026-09-14"}}+ resumed = await agent.ainvoke(Command(resume={"responses": {question["key"]: answer}}), config)++ print("agent:", resumed["messages"][-1].text)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/libs/langchain_v1/examples/mcp/graph_factory.py b/libs/langchain_v1/examples/mcp/graph_factory.pynew file mode 100644index 0000000000..1ab7c18768--- /dev/null+++ b/libs/langchain_v1/examples/mcp/graph_factory.py@@ -0,0 +1,59 @@+"""A per-user MCP fleet behind a `langgraph dev` graph factory."""++from __future__ import annotations++from typing import Any++import httpx2+from _servers import token_for+from fastmcp.client import Client+from fastmcp.client.auth import BearerAuth+from fastmcp.client.group import ClientGroup+from fastmcp.client.transports import StreamableHttpTransport++# Runtime imports (not TYPE_CHECKING): `langgraph dev` classifies the factory+# via `get_type_hints(make_graph)`, which must resolve every annotation.+from langgraph.graph.state import CompiledStateGraph # noqa: TC002+from langgraph_sdk.runtime import ServerRuntime # noqa: TC002+from mcp.client.caching import CacheConfig, InMemoryResponseCacheStore++from langchain.agents import create_agent+from langchain.mcp import MCPAdapter++SYSTEM_PROMPT = "You answer questions using the tools available to you."+SERVERS = {+ "calendar": "http://localhost:8001/mcp",+ "docs": "http://localhost:8002/mcp",+}++_POOL = httpx2.AsyncHTTPTransport() # one pool, shared by everyone+_CACHE = InMemoryResponseCacheStore() # one cache, partitioned by user+++class _SharedPool(httpx2.AsyncBaseTransport):+ # Lends `_POOL` out without letting a borrower close it.+ handle_async_request = _POOL.handle_async_request++ async def aclose(self) -> None: ...+++def _client_factory(**kwargs: Any) -> httpx2.AsyncClient:+ return httpx2.AsyncClient(transport=_SharedPool(), **kwargs)+++async def make_graph(runtime: ServerRuntime) -> CompiledStateGraph:+ """Build an agent over the calling user's MCP fleet (called per run)."""+ user = runtime.user.identity if runtime.user is not None else "anonymous"+ auth = BearerAuth(token_for(user))+ group = ClientGroup(+ {+ name: Client(+ StreamableHttpTransport(url, auth=auth, httpx_client_factory=_client_factory),+ cache=CacheConfig(store=_CACHE, target_id=user, partition=user),+ )+ for name, url in SERVERS.items()+ }+ )+ # `cache_mode="use"` reads the per-user cache; the group's default would refresh it.+ tools = await MCPAdapter(group).list_tools(cache_mode="use")+ return create_agent("anthropic:claude-sonnet-5", tools, system_prompt=SYSTEM_PROMPT)diff --git a/libs/langchain_v1/examples/mcp/langgraph.json b/libs/langchain_v1/examples/mcp/langgraph.jsonnew file mode 100644index 0000000000..4dd9b4061f--- /dev/null+++ b/libs/langchain_v1/examples/mcp/langgraph.json@@ -0,0 +1,10 @@+{+ "$schema": "https://langgra.ph/schema.json",+ "dependencies": ["."],+ "graphs": {+ "fleet": "./graph_factory.py:make_graph"+ },+ "auth": {+ "path": "./auth.py:auth"+ }+}diff --git a/libs/langchain_v1/examples/mcp/multi_server.py b/libs/langchain_v1/examples/mcp/multi_server.pynew file mode 100644index 0000000000..c24ecf4147--- /dev/null+++ b/libs/langchain_v1/examples/mcp/multi_server.py@@ -0,0 +1,47 @@+"""Several MCP servers behind one adapter.++An `MCPConfig` dict names each backend. FastMCP connects to all of them and+prefixes every tool with its config key, so two servers exposing the same tool+name stay distinguishable in the list handed to a model.++Each backend is addressed independently, so a fleet can mix transports — these+two are stdio, but either could be a URL.++ uv run examples/mcp/multi_server.py+"""++from __future__ import annotations++import asyncio+import sys+from pathlib import Path++from langchain.agents import create_agent+from langchain.mcp import MCPAdapter++_STDIO_SERVER = str(Path(__file__).parent / "_stdio_server.py")++CONFIG = {+ "mcpServers": {+ "weather": {"command": sys.executable, "args": [_STDIO_SERVER, "weather"]},+ "calc": {"command": sys.executable, "args": [_STDIO_SERVER, "calculator"]},+ }+}+++async def main() -> None:+ """Give one agent the tools of two servers."""+ async with MCPAdapter(CONFIG) as adapter:+ tools = await adapter.list_tools()++ print("tools:", [tool.name for tool in tools])++ agent = create_agent("anthropic:claude-sonnet-5", tools)+ result = await agent.ainvoke(+ {"messages": [{"role": "user", "content": "Forecast for Oslo? Also, what is 84 / 4?"}]}+ )+ print("\nagent:", result["messages"][-1].text)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/libs/langchain_v1/examples/mcp/protocol_eras.py b/libs/langchain_v1/examples/mcp/protocol_eras.pynew file mode 100644index 0000000000..eef0e2d2d7--- /dev/null+++ b/libs/langchain_v1/examples/mcp/protocol_eras.py@@ -0,0 +1,62 @@+"""Servers from two MCP protocol eras, in one agent.++MCP changed how a client and server agree on what each supports: the 2025-11-25+era negotiates with an `initialize` handshake, the 2026-07-28 era with+`server/discover` instead. FastMCP negotiates per connection, so tools from both+can end up in the same agent and nothing on this side has to know which is+which.++Note the shape: one adapter per server, not one `MCPConfig` fleet naming both.+A fleet is composed behind a single client, and that composite negotiates one+era for everything it holds. A fleet of modern servers does negotiate the modern+era — but add a backend that only speaks the handshake era and the whole fleet+drops to it. Separate adapters are what let each connection keep the best era+its own server supports.++ uv run examples/mcp/protocol_eras.py+"""++from __future__ import annotations++import asyncio+from typing import Any++from _servers import calculator_server, weather_server+from fastmcp.client import Client++from langchain.agents import create_agent+from langchain.mcp import MCPAdapter+++async def main() -> None:+ """Discover tools over each era, then hand them all to one agent."""+ # `mode` picks the era. "legacy" pins the handshake; "auto" negotiates the+ # newest the server understands. Each client negotiates independently.+ legacy: Client[Any] = Client(weather_server(), mode="legacy")+ modern: Client[Any] = Client(calculator_server(), mode="auto")++ async with MCPAdapter(legacy) as legacy_adapter, MCPAdapter(modern) as modern_adapter:+ tools = await legacy_adapter.list_tools() + await modern_adapter.list_tools()++ # Only the handshake era populates `initialize_result`, so it doubles as+ # proof of which negotiation actually ran.+ print(+ f"legacy server -> {legacy.protocol_version} (handshake ran: "+ f"{legacy.initialize_result is not None})"+ )+ print(+ f"modern server -> {modern.protocol_version} (handshake ran: "+ f"{modern.initialize_result is not None})"+ )++ print("tools:", [tool.name for tool in tools])++ agent = create_agent("anthropic:claude-sonnet-5", tools)+ result = await agent.ainvoke(+ {"messages": [{"role": "user", "content": "Forecast for Oslo? And what is 84 / 4?"}]}+ )+ print("\nagent:", result["messages"][-1].text)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/libs/langchain_v1/examples/mcp/remote_server.py b/libs/langchain_v1/examples/mcp/remote_server.pynew file mode 100644index 0000000000..ae00eb9d2d--- /dev/null+++ b/libs/langchain_v1/examples/mcp/remote_server.py@@ -0,0 +1,44 @@+"""Point the adapter at a real MCP server on the public internet.++DeepWiki answers questions about public GitHub repositories and serves MCP over+streamable HTTP with no auth. Nothing here is special-cased for it: the URL is+the entire configuration.++ uv run examples/mcp/remote_server.py+"""++from __future__ import annotations++import asyncio++from langchain.agents import create_agent+from langchain.mcp import MCPAdapter++DEEPWIKI = "https://mcp.deepwiki.com/mcp"+++async def main() -> None:+ """Let an agent research a repository through a remote MCP server."""+ async with MCPAdapter(DEEPWIKI) as adapter:+ tools = await adapter.list_tools()++ print("tools:", [tool.name for tool in tools])++ agent = create_agent(+ "anthropic:claude-sonnet-5",+ tools,+ system_prompt="Answer only from the deepwiki tools. Never answer from memory.",+ )+ question = "What transports does the client in the jlowin/fastmcp repo support?"+ result = await agent.ainvoke({"messages": [{"role": "user", "content": question}]})++ # Proof the remote server did the work rather than the model recalling it.+ for message in result["messages"]:+ if message.type == "tool":+ print(f"\ncalled {message.name} -> {len(message.text)} chars from DeepWiki")++ print("\nagent:", result["messages"][-1].text)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/libs/langchain_v1/examples/mcp/run_graph_factory_demo.py b/libs/langchain_v1/examples/mcp/run_graph_factory_demo.pynew file mode 100644index 0000000000..b8f5f61335--- /dev/null+++ b/libs/langchain_v1/examples/mcp/run_graph_factory_demo.py@@ -0,0 +1,151 @@+"""Drive the graph factory through a real `langgraph dev` server with auth.++This is the end-to-end check the example describes but cannot show inline: two+users hit one deployment, each authenticates with their own `x-api-key`, and+each run's agent talks to the MCP fleet as that user. It:++ 1. mints one shared keypair (so the token the factory mints validates on the+ servers) into a temp `MCP_DEMO_KEYFILE`,+ 2. starts the two guarded MCP servers on the ports `graph_factory.SERVERS`+ names,+ 3. starts `langgraph dev` over `langgraph.json` (which wires `auth.py`),+ 4. runs the `fleet` graph once per user and checks each agent reports its own+ identity from the servers' `whoami` tools.++ ANTHROPIC_API_KEY=... uv run examples/mcp/run_graph_factory_demo.py+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import os+import shutil+import subprocess+import sys+import tempfile+import time+from pathlib import Path++from fastmcp.server.auth.providers.jwt import RSAKeyPair+from langgraph_sdk import get_client++HERE = Path(__file__).parent+DEV_URL = "http://127.0.0.1:2024"+USERS = ("alice", "bob")+++def _write_keyfile() -> Path:+ """Serialize one keypair every process reads, so tokens validate across them."""+ keys = RSAKeyPair.generate()+ path = Path(tempfile.mkstemp(suffix=".json", prefix="mcp-demo-keys-")[1])+ path.write_text(+ json.dumps(+ {"private_key": keys.private_key.get_secret_value(), "public_key": keys.public_key}+ )+ )+ return path+++async def _wait_until_up(url: str, timeout: float = 60.0) -> None:+ """Poll until the dev server has registered the `fleet` graph, or time out."""+ deadline = time.monotonic() + timeout+ client = get_client(url=url, headers={"x-user-id": "healthcheck"})+ while time.monotonic() < deadline:+ with contextlib.suppress(Exception):+ assistants = await client.assistants.search(graph_id="fleet")+ if assistants:+ return+ await asyncio.sleep(1.0)+ msg = f"dev server at {url} never registered the 'fleet' graph"+ raise RuntimeError(msg)+++async def _run_as(user: str) -> str:+ """Run the fleet graph as `user` and return the agent's final text."""+ # The `x-user-id` header is what `auth.py` turns into this run's identity.+ client = get_client(url=DEV_URL, headers={"x-user-id": user})+ thread = await client.threads.create()+ result = await client.runs.wait(+ thread["thread_id"],+ "fleet",+ input={+ "messages": [+ {+ "role": "user",+ "content": (+ "Call both whoami tools. Reply with exactly: calendar=<value> docs=<value>."+ ),+ }+ ]+ },+ )+ return result["messages"][-1]["content"]+++async def _drive() -> int:+ await _wait_until_up(DEV_URL)+ failures = 0+ for user in USERS:+ reply = await _run_as(user)+ text = reply if isinstance(reply, str) else json.dumps(reply)+ ok = f"calendar={user}" in text and f"docs={user}" in text+ print(f"{user:6} -> {'PASS' if ok else 'FAIL'}: {text!r}")+ failures += not ok+ return failures+++def main() -> int:+ """Start the fleet + dev server, run every user through it, and report."""+ keyfile = _write_keyfile()+ env = {**os.environ, "MCP_DEMO_KEYFILE": str(keyfile)}+ # Use the `langgraph` next to this interpreter, not whatever is first on+ # PATH: the graph imports this venv's deps (`httpx2`, `fastmcp`, ...), so it+ # has to run under this venv, not a globally installed CLI.+ langgraph = Path(sys.executable).with_name("langgraph")+ if not langgraph.exists():+ msg = f"`langgraph` CLI not found at {langgraph}; install langgraph-cli[inmem]."+ raise RuntimeError(msg)++ # `langgraph dev` persists its graph registry under `.langgraph_api`; a+ # stale one from an earlier run would shadow this config's `fleet` graph.+ shutil.rmtree(HERE / ".langgraph_api", ignore_errors=True)++ servers = subprocess.Popen( # noqa: S603+ [sys.executable, str(HERE / "_fleet_servers.py")], env=env, cwd=HERE+ )+ devlog = Path("/tmp/lg-driver.log") # noqa: S108+ print(f"(dev log -> {devlog})")+ dev = subprocess.Popen( # noqa: S603+ [+ str(langgraph),+ "dev",+ "--no-browser",+ "--port",+ "2024",+ "--config",+ "langgraph.json",+ # A transitive dependency (`jsonschema_specifications`) scans its+ # package data synchronously the first time a tool schema is+ # validated. `langgraph dev` rejects blocking calls on the event+ # loop by default; allow them here so the demo can run.+ "--allow-blocking",+ ],+ env=env,+ cwd=HERE,+ stdout=devlog.open("w"),+ stderr=subprocess.STDOUT,+ )+ try:+ return asyncio.run(_drive())+ finally:+ for proc in (dev, servers):+ proc.terminate()+ with contextlib.suppress(Exception):+ proc.wait(timeout=10)+ keyfile.unlink(missing_ok=True)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/langchain_v1/examples/mcp/tool_errors.py b/libs/langchain_v1/examples/mcp/tool_errors.pynew file mode 100644index 0000000000..ed725bf16f--- /dev/null+++ b/libs/langchain_v1/examples/mcp/tool_errors.py@@ -0,0 +1,45 @@+"""A failing MCP tool reaches the model instead of ending the run.++When a server reports `isError=True`, the adapter turns it into a `ToolMessage`+with `status="error"` carrying the server's own message. The agent reads that+and can correct itself. Transport failures still raise, because a model cannot+act on those.++ uv run examples/mcp/tool_errors.py+"""++from __future__ import annotations++import asyncio++from _servers import calculator_server++from langchain.agents import create_agent+from langchain.mcp import MCPAdapter+++async def main() -> None:+ """Ask for a division by zero and watch the agent recover."""+ async with MCPAdapter(calculator_server()) as adapter:+ tools = await adapter.list_tools()++ agent = create_agent(+ "anthropic:claude-sonnet-5",+ tools,+ # Without this the model just answers from arithmetic it already knows,+ # and the error path never runs.+ system_prompt="Always use the `divide` tool for arithmetic. Never compute it yourself.",+ )+ result = await agent.ainvoke(+ {"messages": [{"role": "user", "content": "What is 10 divided by 0? Then try 10 / 4."}]}+ )++ for message in result["messages"]:+ if message.type == "tool":+ print(f"tool call -> status={message.status}: {message.text.strip()[:70]}")++ print("\nagent:", result["messages"][-1].text)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/libs/langchain_v1/examples/mcp/transports.py b/libs/langchain_v1/examples/mcp/transports.pynew file mode 100644index 0000000000..ebfdea9f76--- /dev/null+++ b/libs/langchain_v1/examples/mcp/transports.py@@ -0,0 +1,51 @@+"""One adapter, three transports.++`MCPAdapter` infers the transport from whatever you hand it, so the only thing+that changes between an in-process server, a local script over stdio, and a+remote URL is the target itself.++ uv run examples/mcp/transports.py+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import TYPE_CHECKING++from _servers import run_weather_http, weather_server+from fastmcp.utilities.tests import run_server_in_process++from langchain.mcp import MCPAdapter++if TYPE_CHECKING:+ from langchain.mcp.adapter import MCPAdapterTarget++_STDIO_SERVER = Path(__file__).parent / "_stdio_server.py"+++async def show(label: str, target: MCPAdapterTarget) -> None:+ """Adapt one target and call the tool it exposes."""+ async with MCPAdapter(target) as adapter:+ [forecast] = await adapter.list_tools()+ # An MCP result arrives as LangChain content blocks, not a bare string.+ [block] = await forecast.ainvoke({"city": "Oslo"})+ print(f"{label:12} {forecast.name} -> {block['text']}")+++async def main() -> None:+ """Reach the same server over each transport in turn."""+ # In-process: no subprocess, no socket. Ideal for tests.+ await show("in-memory", weather_server())++ # A script path is launched over stdio, one subprocess per adapter.+ await show("stdio", _STDIO_SERVER)++ # A URL is reached over streamable HTTP. FastMCP's own test helper runs the+ # server in a subprocess and hands back its URL.+ with run_server_in_process(run_weather_http) as url:+ await show("http", f"{url}/mcp")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/libs/langchain_v1/pyproject.toml b/libs/langchain_v1/pyproject.tomlindex 1138b1077c..7f32ecac86 100644--- a/libs/langchain_v1/pyproject.toml+++ b/libs/langchain_v1/pyproject.toml@@ -169,6 +169,11 @@ ignore-var-parameters = true # ignore missing documentation for *args and **kwa"T201", # Scripts can print to the console]+"examples/*" = [+ "INP", # Examples are not in a package+ "T201", # Examples print their output, which is the point+]+[tool.coverage.run]omit = ["tests/*"]