Sub topic 13
Working with several servers at once
This chapter assumes you can already connect to one MCP server with the Python SDK, list its tools, and run the tool-calling loop from the previous chapters. You should be comfortable with async/await and with AsyncExitStack from the standard library.
A real host rarely talks to a single server. You might combine a filesystem server, a database server, and a search server. The host then has to do three things. It has to keep one client session per server alive, give the model one combined tool list without name collisions, and route each tool call back to the server that owns the tool.
One session per server
An MCP client session is bound to one server connection. The protocol has no way to multiplex several servers through one session. A host that uses three servers therefore holds three sessions, each with its own transport, its own initialization handshake, and its own negotiated capabilities.
Opening several async with blocks by hand gets awkward as the number of servers grows. contextlib.AsyncExitStack lets you enter an unknown number of async context managers and close them all, in reverse order, when the stack exits.
Name collisions
Two servers can expose a tool with the same name. A search tool from a documentation server and a search tool from a web server are a realistic example. Most LLM APIs require unique tool names in one request, and even if yours accepted duplicates, the model could not tell them apart.
The usual fix is to prefix each tool with the name you give its server, and to keep a lookup table from the prefixed name back to the original pair of session and tool name. Two details matter:
- Many model APIs restrict tool names to letters, digits, underscores and hyphens, with a length limit (commonly 64 characters). Use a separator such as
__and check your provider's rules. - Do not parse the prefixed name to find the owner. Store the mapping explicitly. Server names and tool names can both contain your separator.
A registry that merges and routes
The following example defines a small registry. It connects to several stdio servers, builds the merged tool list, and routes calls. It reuses the server from the earlier chapter (server.py) and a second copy of it under another name so you can run it as shown.
import asyncio
from contextlib import AsyncExitStack
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
SEPARATOR = "__"
class ToolRegistry:
def __init__(self):
self._stack = AsyncExitStack()
self._routes = {} # exposed name -> (session, original tool name)
self.tools = [] # tool definitions in the LLM API format
async def __aenter__(self):
await self._stack.__aenter__()
return self
async def __aexit__(self, *exc):
return await self._stack.__aexit__(*exc)
async def add_server(self, name, params):
read, write = await self._stack.enter_async_context(stdio_client(params))
session = await self._stack.enter_async_context(ClientSession(read, write))
await session.initialize()
listed = await session.list_tools()
for tool in listed.tools:
exposed = f"{name}{SEPARATOR}{tool.name}"
if exposed in self._routes:
raise ValueError(f"Duplicate tool name: {exposed}")
self._routes[exposed] = (session, tool.name)
self.tools.append(
{
"name": exposed,
"description": tool.description or "",
"input_schema": tool.inputSchema,
}
)
async def call(self, exposed_name, arguments):
if exposed_name not in self._routes:
raise KeyError(f"Unknown tool: {exposed_name}")
session, original = self._routes[exposed_name]
return await session.call_tool(original, arguments)
async def main():
params = StdioServerParameters(command="python", args=["server.py"])
async with ToolRegistry() as registry:
await registry.add_server("calc_a", params)
await registry.add_server("calc_b", params)
print([t["name"] for t in registry.tools])
result = await registry.call("calc_b__add", {"a": 2, "b": 3})
print([c.text for c in result.content if c.type == "text"])
asyncio.run(main())Running this prints ['calc_a__add', 'calc_b__add'] and then the result of the call to the second server. Both servers have an add tool, and the prefix keeps them separate.
Plugging the registry into the agent loop
The loop from the earlier chapter needs two small changes. It passes registry.tools to the model instead of one session's list, and it calls registry.call(block.name, block.input) instead of session.call_tool. The rest, including the tool_result blocks and the step limit, stays the same.
Because the registry raises KeyError for an unknown name, wrap that call. A model can occasionally request a tool that is not in the list. Return the problem as an error tool_result so the model can correct itself, rather than letting the exception end the conversation.
async def safe_call(registry, name, arguments):
try:
result = await registry.call(name, arguments)
text = "\n".join(c.text for c in result.content if c.type == "text")
return text, bool(result.isError)
except Exception as exc:
return f"Tool call failed: {exc}", TrueFailure of one server
With several servers, one failure should not take down the whole application. Think through the cases:
- A server fails to start. Catch the error in
add_server, log it, and continue with the servers that did start. The model then simply sees fewer tools. Decide whether a missing server is fatal for your application. A coding assistant can usually run without its search server. A data pipeline may not be able to. - A server dies mid-session. Calls to it raise an exception. Return an error result for that call. Reconnecting is a separate decision. A restart means a new subprocess and a new
initialize(), so the old session object cannot be reused. - A server is slow. Wrap each call in
asyncio.wait_forwith a timeout. One slow server should not hold up unrelated calls.
If the model requests several tools in one response, you can run those calls concurrently with asyncio.gather. Calls to different servers are independent. Calls to the same server share one session, which handles concurrent requests by matching responses to request ids, but the server itself may not be safe for parallel work. Check the server's behavior before parallelizing writes.
Context size grows with each server
Every tool you expose costs tokens on every request, because its name, description, and schema are sent each time. Five servers with ten tools each means fifty definitions in every call. This has two effects. Cost and latency rise, and the model's tool selection gets less reliable as similar tools compete.
Practical ways to control it:
- Expose only the tools a given task needs, using an allow-list per server.
- Choose which servers to connect based on the task or the user's settings.
- Write specific tool descriptions. A vague description such as "search" is a poor guide when three servers each have a search tool.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| API rejects the request with an invalid tool name error | The prefixed name contains characters the provider disallows, or is too long | Use only letters, digits, underscores and hyphens, and shorten server names |
| `KeyError` for a tool the model called | The model used the original name, or invented a name | Return an error result that lists valid names |
| Cleanup errors on exit | Sessions were closed in the wrong order | Enter every context through one `AsyncExitStack` |
| Whole app fails at startup | One server's launch command is wrong | Catch errors per server in `add_server` |
Exercise
Your registry exposes tools as server__tool. A server is named docs__v2 and has a tool named search. Why is parsing the exposed name with name.split("__", 1) unreliable for routing, and what does the registry in this chapter do instead?
Show answer
Splitting on the separator breaks when a server name or tool name itself contains the separator. docs__v2__search would split into docs and v2__search, which names the wrong server. The registry avoids parsing. It stores a dictionary from each exposed name to the exact (session, original tool name) pair when it registers the tool, and routing is a dictionary lookup.
Exercise
A model response contains three tool calls: two to the filesystem server and one to the search server. Name one reason to run them concurrently and one reason to be careful about it.
Show answer
Concurrency reduces total latency, because the search call does not need to wait for the filesystem calls, and a slow call does not block the others. The care is needed because the two filesystem calls use the same session and the same server process. If both write to the same file, running them in parallel can produce a race that the sequential order would have avoided.