MCP: From Motivation to DeploymentLesson 04

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

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

Shopping tool request through an MCP client1 · Clauderequest2 · Pythonhost3 · MCPclient4 · Shopserver5 · result to Claude

MCP series, Part 4. Builds on From Tool Calling to MCP: Build Our First Shopping MCP Server.

The shopping assistant already exposes search_products() and check_inventory() through an MCP server. Its Python chatbot needs an MCP client to make those tools available to Claude and execute the calls Claude requests.

The key change from direct tool calling is where Python sends the tool request:

PYTHON
# Part 1: Direct tool calling
result = execute_tool(tool_name, tool_args)

# This article: MCP tool calling
result = await mcp_client.call_tool(tool_name, tool_args)

Claude still chooses a tool, the Python host invokes it and sends the result back, and the loop continues until Claude stops requesting tools.

The host is the Python chatbot application. It creates the MCP client, which talks to the MCP server that registers and executes the tools. Claude runs on Anthropic's servers; it is neither the MCP client nor the MCP server.

What the MCP client changes

With direct tool calling, the application owned the tool definitions:

PYTHON
TOOLS = [{"name": "search_products", "input_schema": {...}}, ...]
TOOL_FUNCTIONS = {"search_products": search_products, ...}

The previous article moved those functions to an MCP server:

PYTHON
from mcp.server import MCPServer

mcp = MCPServer("stackfable-shop")

@mcp.tool()
def search_products(query: str, max_price: float) -> list[dict]:
    ...

MCP makes the tool definitions discoverable. The server registers tools and derives argument schemas from their function signatures. The client retrieves those descriptions, and the host converts them into Claude's tools= format instead of hand-authoring them in each chatbot.

ConcernDirect tool callingMCP client
Where shopping functions livePython chatbot processMCP server process
Where tool definitions originateWritten in the chatbotDiscovered from MCP server
How Python executes a requested toolTOOL_FUNCTIONS[name](**args)await client.call_tool(name, args)
Who chooses the toolClaudeClaude
Who keeps Claude historyPython chatbotPython chatbot
What repeatsMessages API tool-use loopMessages API tool-use loop

Connect to the shopping MCP server

This example uses MCP Python SDK v2 and the 2026-07-28 MCP protocol. The high-level Client manages discovery and connection behavior. Unlike older versions of MCP, this protocol does not require a manual session.initialize() handshake. The SDK may negotiate compatibility with older servers; this example uses a current server.

PYTHON
import sys
from pathlib import Path
from mcp import Client, StdioServerParameters

server_file = Path(__file__).with_name("shopping_server.py")
params = StdioServerParameters(
    command=sys.executable,
    args=[str(server_file)]
)

async with Client(params) as client:
    ...  # Connected to our local MCP server

The client launches the server and maintains the local connection:

  1. StdioServerParameters tells the MCP client which executable to launch: the current Python interpreter, with the absolute path to shopping_server.py.
  2. Entering async with Client(params) launches the MCP server as a separate subprocess and opens a local stdio transport.
  3. MCP requests travel through the pipe between the client and server processes, without an HTTP port.
  4. When the block exits, the client closes the transport and its managed subprocess.

The open stdio pipe is a transport connection, not an MCP protocol-level session. Under the 2026-07-28 protocol, requests are self-describing and do not need the old initialize / initialized handshake. The product catalog and Claude's message history are application state, separate from that connection.

Discover tools: MCP server → MCP client → Claude

Before calling Claude, the client asks the server what tools it offers:

PYTHON
listed = await client.list_tools()
for tool in listed.tools:
    print(tool.name, tool.description, tool.input_schema)

The tools/list operation asks the MCP server for definitions of search_products and check_inventory, including descriptions and JSON input schemas. It does not call the Anthropic API.

The chatbot then adapts each MCP definition to the Claude Messages API format:

PYTHON
available_tools = [
    {
        "name": tool.name,
        "description": tool.description or "",
        "input_schema": tool.input_schema,
    }
    for tool in listed.tools
]

The MCP Python client exposes tool.input_schema; Claude's API expects the JSON property "input_schema". This converts the representation without rebuilding the schema manually.

Discovery happens before the first Claude request, so the host does not hardcode the shopping tool list. A full implementation should also handle pagination when a server returns multiple pages of tools.

Execute a tool request through MCP

After receiving the tool descriptions, Claude can request one of the tools. Consider the question:

Find a wireless mechanical keyboard under $100 and check whether your best match is in stock.

Claude returns a tool request

The host calls client.messages.create(...). Claude might return a tool_use content block:

JSON
{
  "type": "tool_use",
  "id": "toolu_example_1",
  "name": "search_products",
  "input": {
    "query": "wireless mechanical keyboard",
    "max_price": 100
  }
}

No search has happened yet. This block tells the host which tool Claude wants and supplies its arguments in name and input. The id identifies this particular request so the host can match it to the result it sends back.

The host invokes the tool through MCP

With direct tool calling, the host used a local dictionary to execute the Python function:

PYTHON
# Direct tool calling: execute in the host's own Python process
result = TOOL_FUNCTIONS[block.name](**block.input)

The shopping functions now live in a separate MCP server, so the host asks its MCP client to invoke the tool:

PYTHON
# With MCP: ask the server to execute the function
mcp_result = await mcp_client.call_tool(block.name, block.input)

For search_products, the call uses Claude's requested arguments:

PYTHON
await mcp_client.call_tool(
    "search_products",
    {"query": "wireless mechanical keyboard", "max_price": 100},
)

The MCP client sends a protocol request called tools/call over the local stdio connection. The MCP server matches the tool name to its registered @mcp.tool() function, runs search_products(...), reads our products.json, and returns the result.

The MCP result returns to the Python host. Claude receives it only after the host translates it and makes another Claude API request.

The MCP result

The SDK returns a CallToolResult with fields such as:

PYTHON
mcp_result.content             # Content blocks, such as text
mcp_result.structured_content  # Structured JSON, when available
mcp_result.is_error            # Whether the tool reported an error

For these JSON-compatible shopping tools, the host can serialize structured content or extract returned text blocks. If the server returns product kb-101 at $79, that data is available to Python for the next step.

Return the result to Claude

The host converts the MCP result to a Claude tool_result, records the exchange in its message history, and sends that history in the next API request.

Convert the result to Claude's format

The result formats belong to different protocols:

Returned from MCPSent to Claude
CallToolResulttool_result content block
structured_content or contentcontent (a string or supported content blocks)
is_erroris_error
No Claude tool-use identifiertool_use_id from Claude's earlier request

For the shopping tools, a text/JSON conversion is enough:

PYTHON
import json

# block is Claude's earlier tool_use block
# mcp_result is what await mcp_client.call_tool(...) returned
if mcp_result.structured_content is not None:
    tool_text = json.dumps(mcp_result.structured_content)
else:
    tool_text = "\n".join(
        item.text for item in mcp_result.content if item.type == "text"
    )

tool_result_for_claude = {
    "type": "tool_result",
    "tool_use_id": block.id,
    "content": tool_text,
    "is_error": mcp_result.is_error,
}

Results containing images or other content types need a more careful adapter.

block.id comes from Claude's original tool_use block and associates the result with that request. The MCP client's internal request identifiers are separate.

Record the request and its result

With the user's question already in messages, Python appends both sides of the tool exchange:

PYTHON
# 1. Remember what Claude requested (including its tool_use ID)
messages.append({
    "role": "assistant",
    "content": response.content,
})

# 2. Remember what the MCP server returned, adapted for Claude
messages.append({
    "role": "user",
    "content": [tool_result_for_claude],
})

The assistant message records Claude's request to call search_products; the following message records the result for keyboard kb-101. Claude's Messages API expects tool outputs in a user-role message, even though no human entered that data.

If Claude requests multiple tools in one response, the host runs each one and places all matching tool_result blocks in a single user-role message.

Send the updated history to Claude

PYTHON
response = anthropic_client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    tools=available_tools,
    messages=messages,
)

messages.append() only changes a local Python list. The messages.create() call sends that updated list to Claude, which can then request check_inventory(product_id="kb-101") or answer with the product information it has.

Each tool-requesting round crosses both boundaries: the MCP call brings data into Python, and the next Claude API call delivers it to Claude.

Keep the tool loop inside the chat loop

The chatbot has two loops:

  • The outer chat loop waits for new user questions until the user types quit.
  • The inner tool-calling loop handles a single question, repeatedly calling Claude while it requests tools.

The simplified structure is:

PYTHON
async def process_query(query):
    messages = [{"role": "user", "content": query}]

    while True:
        response = await call_claude(messages, available_tools)

        if response.stop_reason == "end_turn":
            return final_text(response)
        if response.stop_reason != "tool_use":
            raise RuntimeError("Unexpected stop reason")

        messages.append({"role": "assistant", "content": response.content})
        results = []
        for block in response.content:
            if block.type == "tool_use":
                result = await mcp_client.call_tool(block.name, block.input)
                results.append(convert_to_claude_tool_result(block.id, result))
        messages.append({"role": "user", "content": results})

async def chat_loop():
    while True:
        query = await get_user_input()
        if query == "quit":
            break
        print(await process_query(query))

This is explanatory pseudocode. A runnable implementation also needs imports, actual API calls, a maximum-round guard, error handling, and MCP result conversion.

A complete request

This flow is illustrative: the model could request both tools in one turn or answer using fewer turns. Each client.call_tool() is an MCP request, while each messages.create() is an Anthropic API request.

Organizing the chatbot

The ShoppingChatbot class divides the work into three methods:

MethodResponsibility
connect_to_server_and_run()Launch stdio server, discover MCP tools, adapt schemas, keep client open
process_query(query)Invoke Claude, route tool_use via MCP, append results, repeat until completion
chat_loop()Read successive questions until quit

The client connection stays open while the chatbot processes queries, so chat_loop() runs inside async with Client(...).

asyncio.to_thread(...) keeps the synchronous Anthropic SDK request and input() from blocking the Python event loop while it manages asynchronous MCP traffic.

Run the application

The example project consists of these files in one directory:

TEXT
stackfable_mcp_client/
├── shopping_server.py
├── mcp_chatbot.py
├── inspect_client.py
└── products.json

Requirements: Python 3.11+, MCP Python SDK v2, and Anthropic's Python SDK.

BASH
python -m pip install 'mcp>=2,<3' anthropic
export ANTHROPIC_API_KEY='your-api-key'

# First verify the MCP server without Claude:
python inspect_client.py

# Then start the full chatbot:
python mcp_chatbot.py

The example question is Find a wireless mechanical keyboard under $100 and check whether the best match is in stock. Type quit to exit. Each new question starts a fresh Claude conversation in this teaching example; the MCP connection remains open for the lifetime of the chat loop.

The script makes Anthropic API calls, which may incur charges. The example uses a fictional product catalog, not live retailer inventory.

Expected illustrative trace

TEXT
MCP tools discovered: ['search_products', 'check_inventory']
Question: Find a wireless mechanical keyboard under $100 and check stock
[Claude request #1] tool_use
[Claude tool_use] search_products({'query': 'wireless mechanical keyboard', 'max_price': 100})
[Claude request #2] tool_use
[Claude tool_use] check_inventory({'product_id': 'kb-101'})
[Claude request #3] end_turn
Assistant: Keyboard Lite 75 is $79, wireless, and 8 are in stock.

This is an illustrative trace, not a captured execution log. The number and order of Claude calls, as well as its wording, can vary.

What stays with the host

The MCP client/server connection takes the place of the local dispatcher in the tool execution path:

TEXT
Direct calling: Claude → Python dispatcher → local tool
Server test:    MCP client → MCP server → tool (no Claude required)
This article:   Claude → Python host → MCP client → MCP server → tool

MCP standardizes tool discovery and execution across the client/server boundary. The host still runs Claude's tool-calling loop, resends conversation history, and decides how to handle the model's requests.

This example keeps one server and one host, with a bounded number of tool rounds. Production work also needs to consider authentication for remote servers, tool authorization, timeouts, schema validation, a multi-server naming strategy, model context limits, and whether to allow multiple tool calls concurrently.

Next: Multiple MCP servers

The next article keeps the shopping tools and connects a filesystem server so the assistant can save a recommendation. The host then routes each request to the appropriate client. A later article moves the server from local stdio to remote Streamable HTTP.

Knowledge check

Claude requests search_products and the shopping MCP server returns a matching keyboard. What must happen before Claude can use that result to decide whether to check inventory?
The shopping server adds a new tool with its own argument schema. How does this chatbot make that tool available to Claude without writing another tool schema by hand?
Claude requests both search_products and check_inventory in one response. How should the host return the two MCP results?

References

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
A shopping request routed to two MCP servers1 · Keyboardrequest2 · Pythonhost3 · Shopsearch + stock4 · Notessave file

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

  • Stackfable
  • 08 Nov 2026

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

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