Stackfable · MCP series, Part 4
Builds directly on our earlier articles: direct tool calling → shopping MCP server → shopping MCP client.
The core idea
In the previous article, our Claude-powered shopping assistant had one MCP client connected to one MCP server. That server exposed search_products() and check_inventory().
What if our user wants more than a recommendation?
Find a wireless mechanical keyboard under $100, check stock, and save your recommendation to
shopping_notes.md.
Our shopping server can search products and check inventory, but it doesn't know how to write files. Rather than adding unrelated file-writing code to the shopping server, we'll connect to another MCP server: the official filesystem server. The host will need to remember which server owns each tool so it can send a file write to the filesystem server, not the shopping server.
One host can talk to multiple MCP servers through separate MCP clients. The host discovers their tools, routes each tool request to the right server, and sends results back to Claude.
# Conceptual pseudocode
for server in configured_servers:
client = await connect(server)
tools = await client.list_tools()
register_tools(server, client, tools)
response = await ask_claude(question, all_discovered_tools)
while response_requests_tools(response):
for request in response.tool_requests:
client, original_name = find_server_for(request.name)
result = await client.call_tool(original_name, request.input)
append_result_for_claude(request.id, result)
response = await ask_claude(updated_history, all_discovered_tools)This is conceptual pseudocode. Notice what doesn't change: Python still owns the Claude tool-calling loop, and Claude still chooses which tool to request.
1. From one server to multiple servers
Before:
flowchart LR
accTitle: One MCP server before adding notes
accDescr: The Python host talks to Claude and uses one MCP client to reach the shopping server and its tools.
U[User] --> H[Python host]
H <-->|Messages API| L[Claude]
H --> C[One MCP client]
C --> S[Shopping MCP server]
S --> F[Search and inventory tools]After:
flowchart TB
accTitle: Shopping and notes servers connected to one host
accDescr: The Python host talks to Claude and connects separate MCP clients to shopping and filesystem servers.
U[User] --> H[Python shopping host]
H <-->|Messages API| L[Claude]
H --> C1[MCP client: shop]
H --> C2[MCP client: notes]
C1 <-->|stdio| S1[Our shopping MCP server]
C2 <-->|stdio| S2[Official filesystem MCP server]
S1 --> P[(products.json)]
S2 --> N[(notes/ folder)]An MCP host is the application coordinating the AI experience. In our example, that is the Python chatbot. It creates two MCP clients, each connected to its own MCP server. The servers provide independent capabilities:
| Server | Tools we'll expose to Claude | Responsibility |
|---|---|---|
shop (our server) | search_products, check_inventory | Read product and stock data |
notes (official filesystem server) | write_file, read_file, list_directory | Read and write inside a restricted notes folder |
Unlike the previous article, we do not define one hardcoded client called self.mcp_client. We now need a way to track which tool belongs to which client.
2. Make server connections configurable
We could hardcode two Client(...) blocks, but every new server would require another code edit. Instead, move the connection details into server_config.json:
{
"mcpServers": {
"shop": {
"command": "${PYTHON}",
"args": ["${PROJECT_DIR}/shopping_server.py"]
},
"notes": {
"command": "npx",
"args": [
"-y", "@modelcontextprotocol/server-filesystem@2.0.1",
"${PROJECT_DIR}/notes"
]
}
}
}The ${PROJECT_DIR} and ${PYTHON} placeholders are our application's convenience variables, not MCP protocol fields. Our Python code replaces them with the project folder and the active Python interpreter.
The second server is the official @modelcontextprotocol/server-filesystem package. It starts using npx and is allowed to access only the notes/ directory. We're pinning a known package version in this teaching project; review and update that dependency when adopting it in a real application.
Security note: Never give a file-writing MCP server access to your entire home directory just to demonstrate a chatbot. Keep its allowed paths narrow, and consider requiring explicit user approval before writes.
3. One client per server: why AsyncExitStack?
In Part 3, our connection lifetime looked like this:
async with Client(server_params) as client:
# Discover tools and chat here
...For two servers, we could nest these contexts, but that becomes awkward when the server count comes from a JSON file. Python's AsyncExitStack lets us enter a variable number of asynchronous context managers, then close them together in reverse order.
from contextlib import AsyncExitStack
from mcp import Client, StdioServerParameters
stack = AsyncExitStack()
# Run this inside an async function.
client = await stack.enter_async_context(Client(server_params))
# ...repeat for each configured server...
# When the host shuts down:
await stack.aclose()Each Client(StdioServerParameters(...)) starts its own local server subprocess over stdio. The SDK handles MCP request formatting and protocol negotiation. With the 2026-07-28 protocol, a current server does not require the old initialize / initialized handshake. AsyncExitStack manages Python resource lifetimes, not an MCP protocol-level session.
Our MultiServerHub wraps this setup in async with MultiServerHub() as hub, so cleanup also happens when an error occurs.
4. Discover all tools—but keep track of their server
Let's take the precise transition that is easy to miss.
For one server, we wrote:
listed = await client.list_tools()With multiple servers, we run discovery for each client and build two pieces of state:
available_tools: Claude-compatible tool schemas from all servers.tool_routes: a lookup table that remembers which MCP client and original tool name to use when Claude requests a specific tool.
Why do we need a route table?
Suppose both servers defined a tool named search. If we keyed the mapping only by the raw tool name, one server could overwrite the other.
We'll give every Claude-visible tool a namespaced name:
MCP server's original tool Name exposed to Claude
------------------------------------------------------
shop: search_products → shop__search_products
shop: check_inventory → shop__check_inventory
notes: write_file → notes__write_file
notes: read_file → notes__read_file
notes: list_directory → notes__list_directoryThese prefixes are added by our Python host, not by the MCP server or specification. They protect against duplicate tool names and make request routing explicit.
A simplified registration step:
exposed_name = f"{server_name}__{tool.name}"
tool_routes[exposed_name] = (client, tool.name)
available_tools.append({
"name": exposed_name,
"description": f"[{server_name}] {tool.description}",
"input_schema": tool.input_schema,
})Remember: the tool schema goes to Claude; the route table stays in Python.
flowchart TD
accTitle: Discover tools and retain their routes
accDescr: The host gets tool lists from two servers, shares schemas with Claude, and keeps client routes locally.
S1[Shop server] -->|tools/list| H[Python host]
S2[Notes server] -->|tools/list| H
H --> A[available_tools: schemas for Claude]
H --> R[tool_routes: Claude name → client + original name]
A -->|tools=| C[Claude API]
R -.->|Stored locally| HIn the complete implementation we also handle pagination via list_tools(cursor=...) until next_cursor is None. We deliberately expose only three safe-to-demonstrate filesystem operations, even though the filesystem server offers more.
5. Follow one tool request to the correct server
Now Claude has seen tool schemas from both servers. The user's request is:
Find a wireless mechanical keyboard under $100, check stock, and save your recommendation to
shopping_notes.md.
A possible sequence is:
- Claude requests
shop__search_products. - It receives
kb-101for $79 and requestsshop__check_inventory. - It learns that eight units are in stock and requests
notes__write_file. - The filesystem server writes the recommendation, and Claude produces a final answer.
Claude decides which steps to request. The sequence is illustrative, not hardcoded.
A request travels through two names
Claude might return:
{
"type": "tool_use",
"id": "toolu_example_3",
"name": "notes__write_file",
"input": {
"path": "/absolute/project/path/notes/shopping_notes.md",
"content": "Keyboard Lite 75 — $79, wireless, 8 in stock."
}
}The path shown is illustrative; the real filesystem tool will be given the actual allowed directory. The host sees the Claude-visible name notes__write_file, then looks up the original MCP name and the right client:
client, original_name = tool_routes["notes__write_file"]
# original_name == "write_file"
mcp_result = await client.call_tool(original_name, arguments)The notes MCP client sends tools/call to the notes server, not to our shopping server. This is why the mapping is necessary.
sequenceDiagram
accTitle: Route a notes write request
accDescr: The host looks up Claude's namespaced write request and calls the notes server using the original tool name.
participant H as Python host
participant L as Claude API
participant R as Tool route table
participant C as Notes MCP client
participant S as Filesystem MCP server
H->>L: messages.create(all discovered tools)
L-->>H: tool_use notes__write_file, args, id
H->>R: Look up notes__write_file
R-->>H: notes client + original name write_file
H->>C: call_tool(write_file, args)
C->>S: MCP tools/call
S-->>C: Tool result: file written
C-->>H: CallToolResultThe tool result has returned to Python, but not yet to Claude. That is exactly the same boundary as in our previous article.
6. The return path hasn't changed
Whether a result comes from the shopping server or the filesystem server, our host still converts it into Claude's tool_result format and appends the history:
# block: Claude's tool_use request
# mcp_result: result returned by the selected MCP client
tool_result = {
"type": "tool_result",
"tool_use_id": block.id,
"content": tool_text,
"is_error": bool(mcp_result.is_error),
}
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": [tool_result]})
# A separate Claude API call sends the history back to the model.
response = await claude.messages.create(...)This simplified snippet shows one tool request. The real code appends all results from the response together, so it also handles several tool_use blocks in one Claude response.
Three identifiers have different jobs:
| Identifier | Who defines it? | What it does |
|---|---|---|
notes__write_file | Our Python host | Name Claude sees and requests |
write_file | Filesystem MCP server | Original name used in MCP tools/call |
toolu_example_3 | Claude | Connects the tool_result to Claude's original request |
Don't confuse a Claude tool_use_id with MCP's internal JSON-RPC request ID. They belong to different conversations/protocols.
7. The complete end-to-end sequence
sequenceDiagram
accTitle: Shopping recommendation saved through two MCP servers
accDescr: The host discovers tools, routes search and inventory calls to the shop server, then routes a note write to the filesystem server before Claude answers.
autonumber
actor U as User
participant H as Python host
participant L as Claude
participant SC as Shop MCP client
participant SS as Shop MCP server
participant FC as Notes MCP client
participant FS as Filesystem MCP server
Note over H,FS: Startup: discover tools from both servers
H->>SC: list_tools()
SC->>SS: tools/list
SS-->>SC: Shopping tool schemas
H->>FC: list_tools()
FC->>FS: tools/list
FS-->>FC: Filesystem tool schemas
Note over H: Build available_tools and tool_routes
U->>H: Find keyboard, check stock, save recommendation
H->>L: API #1: question + combined tools
L-->>H: shop__search_products
H->>SC: call_tool(search_products)
SC->>SS: tools/call
SS-->>SC: kb-101, $79
SC-->>H: MCP result
Note over H: Append request and result
H->>L: API #2: updated history
L-->>H: shop__check_inventory
H->>SC: call_tool(check_inventory)
SC->>SS: tools/call
SS-->>SC: 8 in stock
SC-->>H: MCP result
H->>L: API #3: updated history
L-->>H: notes__write_file
H->>FC: call_tool(write_file)
FC->>FS: tools/call
FS-->>FC: File written
FC-->>H: MCP result
H->>L: API #4: updated history
L-->>H: Final answer
H-->>U: Recommendation and file confirmationClaude might request multiple independent tools in a single response. The diagram shows a sequential path for teaching purposes; do not mistake it for a mandated order.
8. Build the multi-server host
Our runnable project has these files:
stackfable_multi_mcp/
├── products.json # Fictional catalog
├── shopping_server.py # Our existing MCP server
├── server_config.json # Two server launch configurations
├── multi_hub.py # Connect, discover, namespace, route, clean up
├── chatbot.py # Claude API and tool-calling loop
├── inspect_tools.py # Test MCP connections without Claude
├── requirements.txt
└── notes/ # Only directory the filesystem server can accessThe implementation separates MCP mechanics from Claude conversation mechanics. That makes the difference from Part 3 especially easy to see.
8.1 The multi-server hub
The following file dynamically connects to our configured servers and maintains the routing table:
multi_hub.py
"""Connect to multiple MCP servers, discover tools, and route calls safely."""
import json
import sys
from contextlib import AsyncExitStack
from pathlib import Path
from mcp import Client, StdioServerParameters
ROOT = Path(__file__).resolve().parent
CONFIG = ROOT / "server_config.json"
# Only give Claude the filesystem operations needed for this article.
NOTES_ALLOWED_TOOLS = {"write_file", "read_file", "list_directory"}
class MultiServerHub:
def __init__(self):
self.stack = AsyncExitStack()
self.available_tools: list[dict] = []
# Claude-visible name -> (MCP client, original tool name)
self.tool_routes: dict[str, tuple[Client, str]] = {}
def _expand(self, value: str) -> str:
return (value.replace("${PROJECT_DIR}", str(ROOT))
.replace("${PYTHON}", sys.executable))
async def __aenter__(self):
try:
(ROOT / "notes").mkdir(exist_ok=True)
servers = json.loads(CONFIG.read_text(encoding="utf-8"))["mcpServers"]
for server_name, spec in servers.items():
params = StdioServerParameters(
command=self._expand(spec["command"]),
args=[self._expand(arg) for arg in spec["args"]],
)
client = await self.stack.enter_async_context(Client(params))
count = 0
cursor = None
while True:
page = await client.list_tools(cursor=cursor)
for tool in page.tools:
if server_name == "notes" and tool.name not in NOTES_ALLOWED_TOOLS:
continue
# Avoid collisions: two servers could both expose "search".
exposed_name = f"{server_name}__{tool.name}"
if exposed_name in self.tool_routes:
raise RuntimeError(f"Tool name collision: {exposed_name}")
self.tool_routes[exposed_name] = (client, tool.name)
self.available_tools.append({
"name": exposed_name,
"description": f"[{server_name}] {tool.description or ''}",
"input_schema": tool.input_schema,
})
count += 1
if page.next_cursor is None:
break
cursor = page.next_cursor
print(f"Connected to {server_name}: {count} tools exposed")
return self
except BaseException:
await self.stack.aclose()
raise
async def call_tool(self, exposed_name: str, args: dict):
if exposed_name not in self.tool_routes:
raise ValueError(f"Unregistered tool: {exposed_name}")
client, original_name = self.tool_routes[exposed_name]
return await client.call_tool(original_name, args)
async def __aexit__(self, exc_type, exc, tb):
await self.stack.aclose()Notice the three key components: AsyncExitStack, available_tools, and tool_routes. Together they replace the single-client field in our earlier chatbot.
8.2 Our Claude chatbot
chatbot.py
"""Claude host: discovers tools across servers, then routes Claude's requests."""
import asyncio
import json
import os
from anthropic import AsyncAnthropic
from mcp.types import TextContent
from multi_hub import MultiServerHub
MODEL = os.getenv("CLAUDE_MODEL", "claude-sonnet-4-6")
MAX_ROUNDS = 8
def as_claude_result(block, result):
"""Adapt MCP tool output into Claude's tool_result block."""
if result.structured_content is not None and not result.is_error:
content = json.dumps(result.structured_content)
else:
content = "\n".join(
part.text for part in result.content if isinstance(part, TextContent)
) or "(No text content returned)"
return {
"type": "tool_result",
"tool_use_id": block.id,
"content": content,
"is_error": bool(result.is_error),
}
async def process_query(question: str, hub: MultiServerHub, claude: AsyncAnthropic) -> str:
messages = [{"role": "user", "content": question}]
for round_no in range(1, MAX_ROUNDS + 1):
response = await claude.messages.create(
model=MODEL,
max_tokens=2048,
tools=hub.available_tools,
messages=messages,
)
print(f"[Claude API request #{round_no}] {response.stop_reason}")
if response.stop_reason == "end_turn":
return "\n".join(b.text for b in response.content if b.type == "text")
if response.stop_reason != "tool_use":
raise RuntimeError(f"Claude stopped unexpectedly: {response.stop_reason}")
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type != "tool_use":
continue
print(f"[Route] {block.name}({block.input})")
try:
mcp_result = await hub.call_tool(block.name, block.input)
results.append(as_claude_result(block, mcp_result))
except Exception as exc:
results.append({
"type": "tool_result", "tool_use_id": block.id,
"content": f"Tool invocation failed: {type(exc).__name__}",
"is_error": True,
})
messages.append({"role": "user", "content": results})
raise RuntimeError(f"Stopped after {MAX_ROUNDS} rounds to avoid an unbounded loop")
async def main():
claude = AsyncAnthropic()
async with MultiServerHub() as hub:
print("Available Claude tool names:", [t["name"] for t in hub.available_tools])
while True:
query = (await asyncio.to_thread(input, "\nQuestion (or quit): ")).strip()
if query.lower() == "quit":
break
if not query:
continue
try:
print("\nAssistant:", await process_query(query, hub, claude))
except Exception as exc:
print(f"Error: {exc}")
if __name__ == "__main__":
asyncio.run(main())process_query() still starts a fresh messages list for each question. Each API request within that question receives the accumulated history. We preserve the original Claude tool_use blocks and return the MCP results using the matching tool_use_id.
The tool-calling loop has a maximum-round guard. The example deliberately serializes tool calls. More advanced hosts could execute independent, safe operations concurrently, but those optimizations are not necessary here.
9. Run it
You need Python 3.11+, Node.js 24+ for the current filesystem reference server, and npx on your PATH.
From the project directory:
python -m pip install -r requirements.txt
export ANTHROPIC_API_KEY="your-api-key"
# Verify connections and shopping tools without using Claude:
python inspect_tools.py
# Run the Claude-powered multi-server chatbot:
python chatbot.pyOn Windows, set the environment variable with your shell's corresponding syntax, and the filesystem server's npx launcher may require cmd /c as documented by that server.
Try this prompt:
Find a wireless mechanical keyboard under $100, check that it's in stock, then save a brief recommendation as
shopping_notes.mdinside the allowed notes directory. Explain what you saved.
The filesystem server is restricted to notes/. The chatbot's tool schema tells Claude how to call write_file, but doesn't guarantee it will follow the suggested tool order. The example may make paid Anthropic API requests.
Illustrative console output
Connected to shop: 2 tools exposed
Connected to notes: 3 tools exposed
Available Claude tool names: ['shop__search_products', 'shop__check_inventory',
'notes__read_file', 'notes__write_file', 'notes__list_directory']
[Claude API request #1] tool_use
[Route] shop__search_products(...)
[Claude API request #2] tool_use
[Route] shop__check_inventory(...)
[Claude API request #3] tool_use
[Route] notes__write_file(...)
[Claude API request #4] end_turn
Assistant: I found Keyboard Lite 75 for $79, confirmed 8 in stock,
and saved a recommendation to shopping_notes.md.The exact order of discovered filesystem tools, Claude's decisions, and its wording may differ. This is not a captured live execution trace.
10. What Lesson 6 taught us—and the next layer
This builds on the progression of Lesson 6: Connecting the MCP Chatbot to Reference Servers. The lesson introduces a configuration file, multiple client connections, a unified available-tools list, a map from tool names to sessions, and AsyncExitStack for cleanup. We keep that structure and mental model, but use the current MCP Python SDK v2 Client instead of the older ClientSession + stdio_client + manual initialize() sequence.
Our example uses the official filesystem reference server alongside our existing shopping server. The course also uses the reference fetch server for web extraction; we intentionally leave it out of this version of the runnable example because its published README currently describes an SDK-v1 dependency. More importantly, one additional server is enough to teach multi-server discovery and routing without bringing arbitrary webpage content into the model's context.
The important insight is not the number of servers. It's this:
Claude sees a combined set of tools. The Python host knows which MCP client owns each tool. Each MCP client talks only to its own server.
Our host still manages Claude's conversation history and loop. MCP doesn't automatically make Claude remember past API calls, and MCP's stateless protocol does not mean our product catalog or notes must disappear between requests.
Production considerations
For real systems, treat third-party MCP servers and tool output as untrusted. Restrict accessible directories, review allowed tools, require authorization for side effects, protect secrets, and consider human approval before file writes or other destructive actions. Avoid auto-installing unreviewed packages at runtime; pin versions and audit updates. A production host should also enforce timeout limits, sensible tool-round limits, and per-server error handling.
Knowledge check
Further reading
- MCP Python SDK v2 — Client
- MCP Python SDK v2 — Client transports
- MCP Python SDK — What's new in v2
- MCP official reference servers
- Filesystem MCP server README
- MCP specification 2026-07-28
Course basis: DeepLearning.AI Lesson 6 notebook supplied by the reader. The shopping/catalog example, naming strategy, diagrams, and implementation in this article are original adaptations; modern SDK details are independently verified against the official Python SDK.