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:
# 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.
flowchart LR
accTitle: Claude shopping host and local MCP server
accDescr: The Python host talks to Claude and uses an MCP client over stdio to reach shopping functions in a server process.
U[User] --> H[Python shopping chatbot / MCP host]
H <-->|Messages API| L[Claude]
H --> C[MCP client]
C <-->|stdio: MCP tools/list and tools/call| S[MCP server process]
S --> F[Shopping functions]
F --> J[(products.json)]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:
TOOLS = [{"name": "search_products", "input_schema": {...}}, ...]
TOOL_FUNCTIONS = {"search_products": search_products, ...}The previous article moved those functions to an MCP server:
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.
| Concern | Direct tool calling | MCP client |
|---|---|---|
| Where shopping functions live | Python chatbot process | MCP server process |
| Where tool definitions originate | Written in the chatbot | Discovered from MCP server |
| How Python executes a requested tool | TOOL_FUNCTIONS[name](**args) | await client.call_tool(name, args) |
| Who chooses the tool | Claude | Claude |
| Who keeps Claude history | Python chatbot | Python chatbot |
| What repeats | Messages API tool-use loop | Messages 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.
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 serverThe client launches the server and maintains the local connection:
StdioServerParameterstells the MCP client which executable to launch: the current Python interpreter, with the absolute path toshopping_server.py.- Entering
async with Client(params)launches the MCP server as a separate subprocess and opens a localstdiotransport. - MCP requests travel through the pipe between the client and server processes, without an HTTP port.
- 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:
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:
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.
sequenceDiagram
accTitle: Discover shopping tools before calling Claude
accDescr: The Python host lists tools through its MCP client, adapts their schemas, and sends them to Claude.
participant H as Python chatbot
participant C as MCP Client
participant S as MCP Server
participant L as Claude API
H->>C: list_tools()
C->>S: tools/list
S-->>C: Two tool descriptions + input schemas
C-->>H: MCP Tool objects
Note over H: Adapt schemas for Claude
H->>L: messages.create(tools=available_tools, messages=...)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:
{
"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:
# 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:
# 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:
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.
sequenceDiagram
accTitle: Execute a shopping tool through MCP
accDescr: Claude requests a tool, and the Python host routes the request through an MCP client to the shopping server before receiving its result.
participant H as Python host
participant L as Claude API
participant C as MCP client
participant S as MCP server
participant F as Shopping function
H->>L: messages.create(question, discovered tools)
L-->>H: tool_use(name, input, id)
H->>C: call_tool(name, input)
C->>S: tools/call
S->>F: search_products(**input)
F-->>S: Matching products
S-->>C: MCP tool result
C-->>H: CallToolResult objectThe 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:
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 errorFor 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 MCP | Sent to Claude |
|---|---|
CallToolResult | tool_result content block |
structured_content or content | content (a string or supported content blocks) |
is_error | is_error |
| No Claude tool-use identifier | tool_use_id from Claude's earlier request |
For the shopping tools, a text/JSON conversion is enough:
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:
# 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
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.
sequenceDiagram
accTitle: Return an MCP tool result to Claude
accDescr: The Python host converts an MCP result into a Claude tool result and sends updated messages so Claude can continue or answer.
participant S as MCP server
participant C as MCP client
participant H as Python host
participant L as Claude API
S-->>C: MCP CallToolResult
C-->>H: Product kb-101, price $79
Note over H: Convert to Claude tool_result using original tool_use_id
Note over H: Append assistant request + user-role tool result
H->>L: messages.create(updated messages)
alt Claude needs stock information
L-->>H: tool_use check_inventory(kb-101)
else Claude has enough information
L-->>H: Final text answer
endEach 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:
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
sequenceDiagram
accTitle: Shopping request across Claude and MCP calls
accDescr: The host discovers tools, asks Claude, runs product search and inventory checks through MCP, and sends each result back to Claude before displaying an answer.
autonumber
actor U as User
participant H as Python chatbot (host)
participant L as Claude API
participant C as MCP client
participant S as MCP server
U->>H: Wireless keyboard under $100 and check stock
H->>C: list_tools()
C->>S: tools/list
S-->>C: search_products, check_inventory schemas
C-->>H: Tool list
H->>L: Claude API request 1: question + tool schemas
L-->>H: tool_use search_products
H->>C: call_tool(search_products, args)
C->>S: tools/call
S-->>C: kb-101, $79
C-->>H: MCP result
Note over H: Append Claude tool request + result
H->>L: Claude API request 2: updated messages
L-->>H: tool_use check_inventory
H->>C: call_tool(check_inventory, kb-101)
C->>S: tools/call
S-->>C: 8 in stock
C-->>H: MCP result
Note over H: Append tool request + result
H->>L: Claude API request 3: updated messages
L-->>H: end_turn: final recommendation
H-->>U: Display answerThis 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:
| Method | Responsibility |
|---|---|
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:
stackfable_mcp_client/
├── shopping_server.py
├── mcp_chatbot.py
├── inspect_client.py
└── products.jsonRequirements: Python 3.11+, MCP Python SDK v2, and Anthropic's Python SDK.
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.pyThe 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
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:
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 → toolMCP 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
References
- MCP Python SDK v2 — Client
- MCP Python SDK v2 — Getting Started
- MCP Specification 2026-07-28
- Anthropic — Handle tool calls
- Course reference: DeepLearning.AI, Lesson 5: Creating an MCP Client. The fictional Stackfable shopping example and code are independently written using current SDK APIs.