AI14 min read
LangChain MCP Connections: MCPConfig, ClientGroup, Caching
MCPAdapter tools open a session per call; combine servers with MCPConfig or ClientGroup, scale with a shared pool and cache, and mix legacy and modern MCP eras.
Connecting to a single MCP server from a small script is pretty easy. Things start getting complicated in real projects. Our agent might be pulling tools from five different servers, one of them might still be on the old protocol, or our application might be answering hundreds of requests at the same time. In this article we'll talk about these situations, and we'll see that connection management in MCPAdapter really comes down to two questions: how do we combine servers, and how long do we keep the connection open?
In the first article of the series we covered transports, and in the second tool outputs, metadata and elicitation. In this article we focus on the connection layer: lifecycle, multiple servers, scaling, caching and protocol eras.
Scope of this article: The connection itself belongs to FastMCP; here we describe the LangChain-side patterns and touch on FastMCP details where needed. We mention
langgraph devand LangSmith Agent Server only in relation to MCP; we'll cover deployment separately in upcoming articles.
Choosing the right pattern
The documentation's suggested approach is very practical: pick one row from each of the two tables below. Server shape and connection lifetime are independent; any shape works with any lifetime.
Server shape
| Need | Use |
|---|---|
| One server | A URL, Path or in-process target |
| Several servers behind one connection | An MCPConfig dict |
| Several servers with separate auth, protocol eras or pools | A ClientGroup |
Connection lifetime
| Situation | Pattern |
|---|---|
| Script, notebook and most agents | Discover inside async with, then exit |
| Hold one session across several tool calls in a run | Keep the adapter open around the agent call |
| Many concurrent runs in a deployment | Discover per run; use a shared pool and cache |
Unless we have a specific reason, starting with the default lifecycle is the right call. The other patterns come into play with multiple servers or high concurrency.
Connection lifecycle
MCPAdapter is an async context manager. Entering the context connects the underlying client; exiting releases the connection. Discovery happens inside the context, but the returned tools hold the client, so they stay callable after the context exits.
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter
async def build_agent(target):
async with MCPAdapter(target) as adapter:
tools = await adapter.list_tools()
return create_agent("openai:gpt-6.1-sol", tools)
This is the default pattern. We don't need to keep the adapter open for the agent's whole lifetime; we can return the agent and use it as much as we like.
One session per tool call
This works because the tools the adapter produces are reentrant. Each time a tool is invoked it opens the client, runs the MCP call and releases the client, regardless of whether a connection is held elsewhere. As a result, a single agent run opens one session per tool call and closes it when the call returns, instead of holding a session open for the whole run.
Default (outside the context):
agent.ainvoke ─┬─ tool A ─ [open ─ call ─ close]
├─ model thinking... (no open connection)
└─ tool B ─ [open ─ call ─ close]
With the context open:
async with adapter ───────────────────────────── [open session]
agent.ainvoke ─┬─ tool A ─ [reuse existing session]
└─ tool B ─ [reuse existing session]
This design has two benefits:
- A long-running agent doesn't pin an idle connection between tool calls (while the model is thinking).
- Tools stay callable after the discovery context closes.
If we want the session held open for a whole run, for example to avoid restarting a stdio server on every call, calling the agent inside the adapter's context is enough. The reentrant client reuses the existing connection rather than opening a second one:
async def run_with_held_session(target, question: str) -> dict:
async with MCPAdapter(target) as adapter:
tools = await adapter.list_tools()
agent = create_agent("openai:gpt-6.1-sol", tools)
# The agent runs inside the context, so every tool call reuses one session
return await agent.ainvoke(
{"messages": [{"role": "user", "content": question}]}
)
This choice is felt most with stdio servers: with stdio, every new session means starting a subprocess. For HTTP servers the difference is smaller, but it still saves connection setup cost.
Multiple servers
To give an agent tools from several servers, there are two options: MCPConfig when one aggregate connection is enough, and ClientGroup when each server needs its own connection.
One aggregate connection: MCPConfig
MCPConfig is a dict in the standard mcpServers shape, also used by tools like Claude Desktop and Cursor. Passing it to the adapter connects us to several servers behind one aggregate endpoint:
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter
CONFIG = {
"mcpServers": {
"weather": {"command": "python", "args": ["/path/to/weather_server.py"]},
"calc": {"command": "python", "args": ["/path/to/calc_server.py"]},
}
}
async def fleet_agent(config):
async with MCPAdapter(config) as adapter:
# weather_get_forecast, calc_divide ...
tools = await adapter.list_tools()
return create_agent("openai:gpt-6.1-sol", tools)
FastMCP prefixes every tool name with its config key (weather_..., calc_...). So even if two servers expose a tool with the same name, they don't get mixed up in the list handed to the model. This automatic prefixing replaces the old package's tool_name_prefix option.
Each entry sets its own transport, so a fleet can mix transports. The main fields we can use in an entry:
| Field | For which server? | What it does |
|---|---|---|
command |
Local (stdio) | Executable that starts the server |
args |
Local (stdio) | Arguments passed to the command, in order |
env |
Local (stdio) | Environment variables for the subprocess (values must be strings) |
url |
Remote (HTTP) | The server's MCP endpoint |
transport |
Remote (HTTP) | Optional; inferred from the URL (ending in /sse uses SSE, otherwise Streamable HTTP) |
headers |
Remote (HTTP) | Headers sent with every request |
auth |
Remote (HTTP) | Server-specific credential (see the auth article) |
CONFIG = {
"mcpServers": {
"files": {
"command": "python",
"args": ["/path/to/files_server.py"],
"env": {"ROOT_DIR": "/workspace"},
},
"weather": {
"url": "https://weather.example.com/mcp",
"headers": {"X-Api-Key": "..."},
},
}
}
MCPConfig comes at a price: the fleet shares a single negotiated protocol era across every backend. Add a legacy-only server and the whole fleet drops to the legacy era. Handlers and client-level policies (such as caching) are also shared from the outer client.
Independent connections: ClientGroup
When we want each server on its own connection, we use FastMCP's ClientGroup. Each member keeps its own protocol era, authentication and handlers, and the group routes each call back to the client that advertised the tool:
from fastmcp.client import Client
from fastmcp.client.group import ClientGroup
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter
async def agent_from_group(legacy_url: str, modern_url: str):
group = ClientGroup(
{
"weather": Client(legacy_url, mode="legacy"),
"calc": Client(modern_url, mode="auto"),
}
)
async with MCPAdapter(group) as adapter:
tools = await adapter.list_tools() # weather_..., calc_...
return create_agent("openai:gpt-6.1-sol", tools)
In this example:
- The keys of the dict we give to
ClientGroup(weather,calc) become tool name prefixes:{server}_{tool}. Tools with the same name still don't collide. - Each member is an independent
fastmcp.Client; settings likemode,auth,cacheand handlers can be set per member. - When a tool in the group is called, the adapter resolves the prefixed name back to the right member and the tool name its server knows.
The two approaches side by side:
| Feature | MCPConfig |
ClientGroup |
|---|---|---|
| Connection | One aggregate connection | One connection per server |
| Protocol era | Shared by the fleet (drops to the oldest) | Each server keeps its best era |
| Authentication | auth per entry |
auth per client |
| Handlers, cache | Shared from the outer client | Per member |
| Tool names | {key}_{tool} |
{key}_{tool} |
| When? | Simple fleets, quick start | Mixed eras, different auth, shared pool |
Scaling a deployment
In a deployment serving many runs, the goal is: discover tools per run, but reuse the underlying connections. That way when a server adds a new tool, the agent sees it on the next run, but we don't set up connections from scratch on every request.
To do this we build the agent inside a langgraph dev graph factory. The factory is called once per run:
# agent.py
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter
SERVERS = {
"weather": "http://localhost:8001/mcp",
"calc": "http://localhost:8002/mcp",
}
async def make_graph():
"""Called once per run by langgraph dev."""
config = {"mcpServers": {name: {"url": url} for name, url in SERVERS.items()}}
async with MCPAdapter(config) as adapter:
tools = await adapter.list_tools(cache_mode="use")
return create_agent("openai:gpt-6.1-sol", tools)
On LangSmith Agent Server we register this factory in langgraph.json instead of exporting a static compiled graph:
{
"dependencies": ["."],
"graphs": {
"agent": "./agent.py:make_graph"
}
}
Two important details in this section:
- Type hints on the factory must be importable at runtime.
langgraph-apiclassifies the factory withtyping.get_type_hints(). If parameter or return types are only imported under aTYPE_CHECKINGblock, they can't be resolved, and a config dict is injected instead of the runtime. - Since tools from
list_tools()stay callable after the context closes, returning the agent after discovery is enough for most MCP setups. If we need teardown around the run, or want to skip expensive MCP work on schema and state reads, we can use LangSmith's context manager factory form and theexecution_runtimecontrol. We'll talk about these in the deployment article.
Shared connection pool
By default each FastMCP client manages its own HTTP connections. Across a fleet of servers or many concurrent runs, that means many independent pools. To share one pool, we give the transport an httpx_client_factory that draws from a single transport:
import httpx2
from fastmcp.client import Client
from fastmcp.client.group import ClientGroup
from fastmcp.client.transports import StreamableHttpTransport
from langchain.mcp import MCPAdapter
# One pool shared by every server the deployment talks to
_POOL = httpx2.AsyncHTTPTransport()
class _SharedPool(httpx2.AsyncBaseTransport):
"""Lend _POOL to each client without letting any client close it."""
handle_async_request = _POOL.handle_async_request
async def aclose(self) -> None: ...
def _client_factory(**kwargs: object) -> httpx2.AsyncClient:
return httpx2.AsyncClient(transport=_SharedPool(), **kwargs)
async def load_over_shared_pool(servers: dict[str, str]) -> list:
group = ClientGroup(
{
name: Client(
StreamableHttpTransport(url, httpx_client_factory=_client_factory)
)
for name, url in servers.items()
}
)
async with MCPAdapter(group) as adapter:
return await adapter.list_tools()
In this example:
_POOLis the single transport holding the real connections. It's created once at module level._SharedPoolis a thin wrapper that forwards requests to_POOL. The most important line here is the emptyaclose(). We left it empty so that a client can't close the shared pool when it shuts down; otherwise the first client to close would drop everyone's connections.httpx_client_factoryis the factory FastMCP calls when creating its HTTP client. Each client gets its ownAsyncClient, but all of them draw from the same pool.- As a result the deployment opens one set of HTTP connections for the whole fleet rather than one pool per server.
We see httpx2 instead of httpx in the example because recent FastMCP releases use httpx2 in their HTTP layer. On an older FastMCP release we'd need to build the same pattern with httpx.
Caching
FastMCP can cache the result of list_tools so repeated discovery avoids a network round trip. This is opt-in and honors the server's own cache hints (ttlMs, cacheScope). So it only takes effect against modern-era servers that advertise these hints; on a legacy connection the cache does nothing.
The cache itself is configured on the client:
from fastmcp.client import Client
from mcp.client.caching import CacheConfig
from langchain.mcp import MCPAdapter
# Simplest form: the default in-memory cache
client = Client("https://example.com/mcp", cache=True)
# More control: identity and default TTL
config = CacheConfig(target_id="weather-api", default_ttl_ms=60_000)
client = Client("https://example.com/mcp", cache=config)
async with MCPAdapter(client) as adapter:
tools = await adapter.list_tools() # cache_mode="use"
The cache_mode parameter of list_tools() selects how discovery reads that cache:
cache_mode |
Behavior | When? |
|---|---|---|
"use" (default) |
Serves from the cache within TTL; otherwise fetches and stores | Normal operation |
"refresh" |
Fetches a fresh list from the server and repopulates the cache | When we know the server added new tools |
"bypass" |
Skips the cache entirely | Debugging, cases that shouldn't write to the cache |
tools = await adapter.list_tools(cache_mode="refresh")
A small but potentially confusing difference: MCPAdapter.list_tools() defaults to "use", while a bare ClientGroup.list_tools() defaults to "refresh". The adapter deliberately chooses "use" so that a configured cache is honored.
When multiple replicas need to share the same cache (for example backed by Redis), we can use FastMCP's KeyValueResponseCacheStore. Here a partition is mandatory: since a shared store could mix up different users' responses, each user or tenant needs its own partition, derived from a verified identity, not from request data. This topic comes back in the auth article together with per-user authorization.
Protocol eras
MCP changed how a client and server agree on what each supports. Today there are two "eras":
| Legacy (handshake) era | Modern era | |
|---|---|---|
| Version | 2025-11-25 and earlier |
2026-07-28 and later |
| Start | Every connection begins with an initialize handshake |
The server's server/discover endpoint is probed |
| Session | Persistent session and back-channel | Stateless; every request carries its own information |
| Server asking the client | Pushed (ctx.elicit(), sampling, roots) |
Multi-round requests via InputRequiredResult |
| Cache hints | None | ttlMs, cacheScope |
| LangChain elicitation (interrupt) | Not supported | Supported |
FastMCP negotiates the era per connection; on the LangChain side we don't need to know which era a given server speaks. When building a prebuilt fastmcp.Client, we can choose the era with the mode parameter:
mode |
Behavior |
|---|---|
"auto" (default) |
Probes server/discover; adopts the modern era if the server responds, otherwise falls back to the legacy handshake |
"legacy" |
Forces the initialize handshake; for older servers that push requests |
A version such as "2026-07-28" |
Adopts that modern version directly, without discovery |
To combine tools from servers on different eras in one agent, we need to give each server its own connection, either through a ClientGroup or one adapter per server:
from fastmcp.client import Client
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter
async def agent_across_eras(legacy_target, modern_target):
legacy = Client(legacy_target, mode="legacy")
modern = Client(modern_target, 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()
return create_agent("openai:gpt-6.1-sol", tools)
Had we passed both servers as one MCPConfig fleet, the fleet would negotiate a single era for everything and drop all servers to the oldest era any member requires. That means the modern server would lose features like elicitation and caching.
One more note: the SSE transport can only carry the legacy era. A client connecting over SSE always negotiates the handshake era, even with mode="auto".
Wrapping up
In this article we talked about how we manage MCP connections. As we said at the start, it all comes down to two questions: how do we combine servers, and how long do we keep the connection open? In most cases getting the tools inside async with and leaving the block is enough, because every tool call opens its own connection anyway. When working with several servers, we use MCPConfig for simple setups and ClientGroup when different protocol eras or credentials are involved. In applications serving many requests, we can get the tool list on every request and keep costs down with a shared connection pool and cache.
In the last article of the series we move on to authentication. We'll talk about bearer tokens, OAuth 2.1, using separate credentials for each server and running each request on behalf of the user who made it. See you in the next article.
Sources
The langchain.mcp API described here is in beta, and FastMCP's connection details may change between releases. It's a good habit to verify the details for the version you're using against the official documentation.
- LangChain – MCP Connections – lifecycle, multiple servers, scaling, caching and protocol eras
- FastMCP – The FastMCP Client –
mode, protocol negotiation and response caching - FastMCP – Client Groups – a single tool catalog over independent connections
- FastMCP – MCP JSON Configuration – the
mcpServersformat and its fields - LangGraph – Run a local server –
langgraph devand graph factories
- langchain
- mcp
- agents
- fastmcp
- python