Sub topic 13
Working with several servers at once
This chapter assumes you have read the earlier chapters. You should be able to open a ClientSession over stdio, list tools, convert them to LLM tool definitions, and run the agent loop. Here you extend that setup to more than one server.
Why one session is not enough
Each MCP server needs its own connection, so each needs its own ClientSession. A host that uses a filesystem server and a calendar server holds two sessions. The model sees one combined list of tools. Your code must remember which session owns each tool.
Two problems appear once you merge tools:
- Name collisions. Two servers can both expose a tool called
search. LLM APIs need unique tool names, and a duplicate would send calls to the wrong server or fail. - Routing. When the model calls a tool, you need to find the right session.
Namespacing tools
Give each server a short label and prefix every tool name with it. Many LLM APIs restrict tool names to letters, digits, underscores and hyphens, so avoid characters such as . or /. This example uses a double underscore as the separator.
import asyncio
from contextlib import AsyncExitStack
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
SEP = "__"
class Hub:
def __init__(self):
self.stack = AsyncExitStack()
self.sessions = {} # label -> ClientSession
self.routes = {} # namespaced name -> (label, original name)
async def add_server(self, label, 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()
self.sessions[label] = session
async def list_tools(self):
tools = []
self.routes.clear()
for label, session in self.sessions.items():
for t in (await session.list_tools()).tools:
name = f"{label}{SEP}{t.name}"
self.routes[name] = (label, t.name)
tools.append(
{
"name": name,
"description": t.description or "",
"input_schema": t.inputSchema,
}
)
return tools
async def call_tool(self, name, arguments):
label, original = self.routes[name]
return await self.sessions[label].call_tool(original, arguments)
async def close(self):
await self.stack.aclose()
async def main():
hub = Hub()
try:
await hub.add_server(
"calc", StdioServerParameters(command="python", args=["server.py"])
)
await hub.add_server(
"calc2", StdioServerParameters(command="python", args=["server.py"])
)
for tool in await hub.list_tools():
print(tool["name"])
result = await hub.call_tool("calc2__add", {"a": 2, "b": 3})
print([c.text for c in result.content if c.type == "text"])
finally:
await hub.close()
asyncio.run(main())This starts the minimal server.py twice under two labels. The output lists calc__add and calc2__add, then prints the result of the call. The routing table maps the namespaced name back to the original, so the server never sees the prefix.
In your agent loop, replace session.list_tools() with hub.list_tools() and session.call_tool(...) with hub.call_tool(...). Nothing else changes.
Common errors
- Unknown tool names. The model may invent a name that is not in
routes. Catch theKeyErrorand return an errortool_resultso the model can recover. - Stale lists. Rebuild the routing table whenever you re-list tools. Servers can announce changes, so a cached list can go out of date.
- One failing server. If one server crashes at startup, decide whether to skip it or abort. Skipping keeps the app usable but hides the loss of tools, so log it.
- Tool overload. Combining many servers can put dozens of tool definitions into every request. This costs tokens and can make the model choose worse. Expose only the servers a task needs.
Exercise
Two servers both expose a tool named search. After you add the prefixes docs and web, the model calls web__search. What does the hub send to the web server, and why?
Show answer
It sends a call_tool request for search. The routing table maps web__search to the label web and the original name search. The prefix exists only in the host and the model's view, so the server never sees it.