A shopping assistant can search a product catalog and check stock by calling Python functions directly. That works when the functions live inside one application. If another application needs the same tools, an MCP server can expose them through a standard interface.
From direct dispatch to an MCP server
With direct tool calling, the application describes its Python functions to Claude using tool schemas and dispatches Claude's tool_use requests itself. The MCP version keeps those functions but exposes them through a server.
MCP standardizes how an application discovers and invokes externally provided tools. Claude's reasoning and the host's tool-calling loop still have their own roles.
# Direct Python dispatch — conceptual
result = TOOL_FUNCTIONS[tool_name](**tool_args)
# MCP dispatch — conceptual
result = await mcp_client.call_tool(tool_name, tool_args)The first line executes a function from a local Python dictionary. The second sends a standardized MCP request to an MCP server, which runs the function and returns a structured result.
flowchart LR
accTitle: Direct dispatch compared with an MCP server
accDescr: Direct tool calling runs shopping functions through a local dispatcher. With MCP, a client sends requests over stdio to a separate server that runs the same functions.
subgraph Before[Direct tool calling]
A1[Claude application] --> B1[Local dispatcher] --> C1[Python shopping functions]
end
subgraph After[With MCP]
A2[MCP host / application] --> B2[MCP client] -->|stdio| C2[MCP server] --> D2[Same Python shopping functions]
endThe server can be built and tested before it is connected back to Claude.
What stays the same
The example keeps the fictional store, the user's question, and the two tools:
Find a wireless mechanical keyboard under $100 and check whether the best match is in stock.
def search_products(query: str, max_price: float) -> list[dict]: ...
def check_inventory(product_id: str) -> dict: ...The example's products.json holds three fictional keyboards. The first tool returns matching products without inventory. The second returns stock for one product_id.
No real shopping API, database, or authentication is required. The local catalog keeps the example focused on the MCP connection.
Why use a server for these tools?
In the direct implementation, the chatbot maintains a list of Claude tool schemas and a dispatch dictionary:
TOOLS = [{"name": "search_products", "input_schema": {"...": "..."}}, ...]
TOOL_FUNCTIONS = {"search_products": search_products, "check_inventory": check_inventory}
result = TOOL_FUNCTIONS[tool_name](**tool_args)That works for a small application. But another AI host using these shopping tools would need its own connection and tool descriptions.
MCP provides a standard interface with operations such as tools/list and tools/call. A client can ask which tools are available and invoke one by name, without inventing its own discovery and calling interface.
Where each part runs
An MCP host is the application that coordinates the AI experience. It creates one or more MCP clients, which connect to MCP servers. A server can expose tools, resources, and prompts; this example uses only tools.
flowchart TD
accTitle: Shopping MCP server and its local client
accDescr: The shopping application uses a client to send stdio requests to an MCP server process, which runs shopping functions backed by products.json.
H[AI shopping host application] --> L[Claude API]
H --> C[MCP client]
C -->|MCP requests over stdio| S[MCP shopping server process]
S --> F[search_products / check_inventory]
F --> J[(products.json)]For this local example, the host/client and server are separate Python processes on the same machine. The MCP client communicates with the server over its standard input and standard output, known as stdio. No public URL or HTTP port is needed.
A local server over stdio is still an MCP server; it need not be a remote web service.
Stateless requests and a live server process
Under the 2026-07-28 MCP specification, an MCP request does not depend on a protocol-level session established by a previous request. The local server process can still stay running between requests.
Earlier protocol: initialization before requests
Older MCP versions had an initialization handshake. A client would call initialize, receive server details and capabilities, and send an initialized notification. With session-based Streamable HTTP, a server could also issue an Mcp-Session-Id that the client reused on later requests.
sequenceDiagram
accTitle: Earlier MCP initialization before tool calls
accDescr: A client initializes with a server, sends an initialized notification, then lists and calls tools.
participant C as MCP client
participant S as MCP server
C->>S: initialize
S-->>C: Server info and capabilities
C->>S: initialized notification
C->>S: tools/list
S-->>C: Available tools
C->>S: tools/call
S-->>C: Tool resultCurrent protocol: self-contained requests
The protocol removes the mandatory initialize / initialized exchange and the protocol-level Mcp-Session-Id. Each request carries the information needed to interpret it, including protocol version and client context. A client can optionally use server/discover to learn capabilities first; it does not have to do so before calling a tool.
sequenceDiagram
accTitle: Tool requests under MCP 2026-07-28
accDescr: A client may discover server capabilities, then lists and calls tools with self-contained requests.
participant C as MCP client
participant S as MCP server
opt Client wants to discover capabilities first
C->>S: server/discover
S-->>C: Capabilities
end
C->>S: tools/list (self-contained request)
S-->>C: Available tools
C->>S: tools/call (self-contained request)
S-->>C: Tool resultFor remote Streamable HTTP, this makes it easier to distribute independent requests across multiple server instances. It avoids requiring sticky routing or a shared protocol session just to process a tool request. This example uses local stdio instead: the client starts and communicates with a server process through a live pipe, but that pipe is a transport connection, not a mandatory MCP protocol session.
Stateless protocol doesn't mean a stateless application
The protocol's request state is separate from the shopping application's data and Claude's conversation history:
- MCP protocol state: No prior handshake or session ID is required for a request under the 2026-07-28 protocol.
- Shopping application data: The
products.jsonfile remains available between tool calls. Each tool reads that data independently. - Claude conversation history: The host application can still keep and resend its
messageslist. MCP does not manage Claude's conversation memory. - Multi-step business workflows: A shopping cart could use an explicit
cart_idreturned by one tool and accepted by later calls, with the underlying cart stored separately.
For example, a future shopping tool could return {"cart_id": "cart-42"}. A later call might use add_to_cart(cart_id="cart-42", product_id="kb-101"). That explicit identifier carries the relationship between calls without depending on an invisible protocol session.
Neither search_products() nor check_inventory() needs to change for this request model. The SDK handles the request metadata and protocol details. The functions can still be exposed as tools and tested through tools/list and tools/call.
Discovering and calling the tools
The test client uses two MCP operations:
A. Discover tools
MCP client → server: tools/list
MCP server → client: search_products, check_inventory (names, descriptions, input schemas)B. Call a tool
MCP client → server: tools/call(name="check_inventory", arguments={"product_id":"kb-101"})
MCP server → client: {"product_id":"kb-101","in_stock":true,"quantity":8}Claude is not involved in either operation yet. A small MCP client can test discovery and invocation. Later, the AI host can use the same operations to fulfill Claude's tool requests.
Implement the shopping MCP server
With the MCP Python SDK (v2), MCPServer and @mcp.tool() register a Python function as an MCP tool. The SDK derives tool descriptions and parameter schemas from the function signature and docstring and handles the protocol machinery.
File: shopping_server.py
import json
from pathlib import Path
from mcp.server import MCPServer
CATALOG = Path(__file__).with_name("products.json")
mcp = MCPServer("stackfable-shop")
def load_products() -> list[dict]:
return json.loads(CATALOG.read_text(encoding="utf-8"))
@mcp.tool()
def search_products(query: str, max_price: float) -> list[dict]:
"""Find products matching all keywords within a maximum USD price; omit stock."""
words = query.lower().split()
matches = []
for product in load_products():
searchable = f"{product['name']} {product['category']} " + (
"wireless" if product["wireless"] else "wired"
)
if product["price"] <= max_price and all(w in searchable.lower() for w in words):
matches.append({k: product[k] for k in ("id", "name", "price", "wireless")})
return matches
@mcp.tool()
def check_inventory(product_id: str) -> dict:
"""Check current stock for one exact product ID."""
for product in load_products():
if product["id"] == product_id:
return {
"product_id": product_id,
"in_stock": product["stock"] > 0,
"quantity": product["stock"],
}
return {"product_id": product_id, "error": "Product not found"}
if __name__ == "__main__":
mcp.run(transport="stdio")This example expects products.json beside the script. Each product needs the id, name, category, price, wireless, and stock fields read by these functions.
Registering and running the server
mcp = MCPServer("stackfable-shop")Creates the MCP server object. It is not starting the server yet.
@mcp.tool()Registers the function so the server can expose it to MCP clients. The application no longer needs to maintain Claude-specific JSON tool schemas for these functions inside the chatbot.
mcp.run(transport="stdio")Starts the MCP server's local stdio request handling. The program runs, waiting to serve MCP requests from its client. It does not call Claude. Keep regular logs on stderr rather than printing arbitrary output to stdout, which carries MCP protocol messages.
Verify the server without Claude
A small MCP client can launch the server, list its tools, and call them before an LLM is attached.
File: inspect_shopping_server.py
import asyncio
import sys
from pathlib import Path
from mcp import Client, StdioServerParameters
SERVER = Path(__file__).with_name("shopping_server.py")
async def main():
params = StdioServerParameters(command=sys.executable, args=[str(SERVER)])
async with Client(params) as client:
discovered = await client.list_tools()
print([tool.name for tool in discovered.tools])
products = await client.call_tool(
"search_products",
{"query": "wireless mechanical keyboard", "max_price": 100},
)
print(products.structured_content or products.content)
stock = await client.call_tool(
"check_inventory", {"product_id": "kb-101"}
)
print(stock.structured_content or stock.content)
asyncio.run(main())async with Client(params) launches the server as a subprocess and manages the transport lifetime. Under MCP 2026-07-28, this does not imply the older initialize / initialized protocol handshake or protocol-level session. await client.list_tools() and await client.call_tool(...) use the MCP interface. The SDK handles serialization and protocol messages.
result.structured_content holds machine-readable output when supplied. result.content holds model-readable content blocks. A real client should also inspect result.is_error; the demonstration calls valid tools with valid arguments.
The request flow, end to end
sequenceDiagram
accTitle: Testing the shopping server with an MCP client
accDescr: A test program launches the server through a client, lists tools, and calls search_products; the server runs the function and returns the result.
participant P as Test Python program
participant C as MCP Client
participant S as MCP Server (subprocess)
participant F as Shopping functions
P->>C: async with Client(server parameters)
C->>S: Launch server and open stdio transport
P->>C: list_tools()
C->>S: tools/list
S-->>C: Tool names + auto-generated schemas
C-->>P: Discovered tools
P->>C: call_tool(search_products, args)
C->>S: tools/call
S->>F: search_products(**args)
F-->>S: Matching products
S-->>C: MCP tool result
C-->>P: CallToolResultclient.call_tool() asks the MCP server to run the registered function and return its result; the function does not execute in the client process.
Run it locally
Running the example requires Python 3.11+ and a working Python environment. From the directory containing shopping_server.py, inspect_shopping_server.py, and products.json:
python -m pip install "mcp>=2,<3"
python inspect_shopping_server.pyOr with uv:
uv init
uv add "mcp>=2,<3"
uv run inspect_shopping_server.pyTo interactively inspect the server, install the CLI extra and launch the Inspector:
uv add "mcp[cli]>=2,<3"
uv run mcp dev shopping_server.pyThe Inspector lists tools and accepts tool arguments without an AI host. For this local stdio example, the Inspector or test client launches the server process; no separate background server is needed.
Expected behavior: With the example catalog data, search_products returns a fictional $79 wireless keyboard, and check_inventory("kb-101") returns quantity 8. The exact formatting of the SDK's result wrapper may differ. These examples are expected outputs, not captured live executions.
What changed from direct tool calling?
| Concern | Direct tool calling | MCP server |
|---|---|---|
| Business logic | search_products() | Same function |
| Tool description | Handwritten Claude-specific tools schemas | MCP server exposes generated tool definitions |
| Discovering tools | App maintains TOOLS itself | Client asks tools/list |
| Running tools | TOOL_FUNCTIONS[name](**args) | Client calls tools/call; server dispatches |
| Where tools run | Inside chatbot process | Inside MCP server process |
| Model decision | Claude decides tool requests | Still Claude's responsibility once connected |
| Conversation history | App sends messages to Claude | Still app's responsibility |
| Repeat/stop loop | App inspects Claude responses | Still needed in a Claude-powered host |
MCP standardizes tool access. Claude's decision-making and the host's tool-calling loop remain separate from the server built here.
Protocol version and scope
This example targets the 2026-07-28 MCP specification with the official Python SDK v2. It uses only current APIs:
MCPServerand@mcp.tool()to expose tools and generate input schemas.Clientto make MCPtools/listandtools/callrequests.- Local stdio transport to send protocol messages between the client and server processes.
structured_content,content, andis_errorto interpret tool results.
In this protocol version, client requests are self-describing, there is no mandatory initialize / initialized handshake and no protocol-level session. A client can optionally request capabilities using server/discover; the local example does not need it. The async with Client(...) context still starts and manages the local subprocess/transport lifetime, which is not the same thing as an MCP protocol session.
For remote deployment, the recommended transport is Streamable HTTP, not the legacy HTTP+SSE transport. The local server here does not cover HTTP authentication, routing headers, extensions, or remote deployment.
Connecting Claude next
The test client calls the tools explicitly. The next step is to attach Claude so the model can request a tool:
# Conceptual view of the next step — not yet complete code
mcp_tools = await mcp_client.list_tools()
claude_tools = adapt_to_anthropic_tool_schemas(mcp_tools)
response = ask_claude(question, claude_tools)
# If Claude requests search_products:
mcp_result = await mcp_client.call_tool("search_products", arguments)
# Convert result to Claude's tool_result, append history,
# and repeat the Claude tool-calling loop.The host still calls the Claude API and manages the model/tool loop. The MCP client reaches the shopping server, which executes the requested function without deciding what Claude should do next.
In the direct version, Python executes the requested function inside the chatbot. With MCP, a client asks a separate server process to execute it. Connecting that path to Claude's tool-calling loop is the next step.