MCP: From Motivation to DeploymentLesson 05

Connecting One MCP Client to Multiple Servers: Build a Shopping Assistant That Can Save Notes

Connect a shopping assistant to separate shopping and filesystem MCP servers, then discover and route their tools through one Python host.

A shopping request routed to two MCP servers1 · Keyboardrequest2 · Pythonhost3 · Shopsearch + stock4 · Notessave file

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.

PYTHON
# 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:

After:

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:

ServerTools we'll expose to ClaudeResponsibility
shop (our server)search_products, check_inventoryRead product and stock data
notes (official filesystem server)write_file, read_file, list_directoryRead 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:

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:

PYTHON
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.

PYTHON
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:

PYTHON
listed = await client.list_tools()

With multiple servers, we run discovery for each client and build two pieces of state:

  1. available_tools: Claude-compatible tool schemas from all servers.
  2. 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:

TEXT
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_directory

These 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:

PYTHON
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.

In 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:

  1. Claude requests shop__search_products.
  2. It receives kb-101 for $79 and requests shop__check_inventory.
  3. It learns that eight units are in stock and requests notes__write_file.
  4. 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:

JSON
{
  "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:

PYTHON
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.

The 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:

PYTHON
# 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:

IdentifierWho defines it?What it does
notes__write_fileOur Python hostName Claude sees and requests
write_fileFilesystem MCP serverOriginal name used in MCP tools/call
toolu_example_3ClaudeConnects 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

Claude 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:

TEXT
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 access

The 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

PYTHON
"""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

PYTHON
"""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:

BASH
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.py

On 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.md inside 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

TEXT
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

Both the shop and notes servers expose a tool named search. What should the Python host do before offering them to Claude?
Claude requests notes__write_file for shopping_notes.md. What does the host send to the notes MCP client?
The notes server has written shopping_notes.md and returned success to Python. What must happen before Claude can confirm the saved recommendation to the user?

Further reading

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.

Related Posts

Shopping inventory call through a remote MCP server1 · Shoppinghost2 · MCPclient3 · Remoteserver4 · ProductcatalogHTTPS /mcp

Deploy a Remote MCP Server: Streamable HTTP, Cloudflare, AWS, and Capacity Planning

  • Stackfable
  • 08 Nov 2026

Move a shopping MCP server from local stdio to remote HTTP, compare deployment options, and estimate the capacity it needs.

Read More: Deploy a Remote MCP Server: Streamable HTTP, Cloudflare, AWS, and Capacity Planning
Product resource selected by the shopping host1 · Shopperchooses ID2 · Pythonhost3 · Productresource4 · Displayonly5 · Claudegets context

MCP Beyond Tools: Add Resources and Prompts to Our Shopping Assistant

  • Stackfable
  • 08 Nov 2026

Extend a shopping MCP server with product resources and a reusable prompt, and see when the host passes each to Claude.

Read More: MCP Beyond Tools: Add Resources and Prompts to Our Shopping Assistant
Shopping tool request through an MCP client1 · Clauderequest2 · Pythonhost3 · MCPclient4 · Shopserver5 · result to Claude

From MCP Server to MCP Client: Connect Our Shopping Assistant to Claude

  • Stackfable
  • 08 Nov 2026

Connect a shopping MCP server to Claude by discovering tools, routing tool calls, and returning results through a Python host.

Read More: From MCP Server to MCP Client: Connect Our Shopping Assistant to Claude