MCP: From Motivation to DeploymentLesson 03

From Tool Calling to MCP: Build Our First Shopping MCP Server

Build and test a local shopping MCP server that exposes product search and inventory checks through standard tool discovery and calls.

Shopping tool call through a local MCP server1 · Testprogram2 · MCPclient3 · Shopserver4 · Productcatalogtools/call

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.

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

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

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

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

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.

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

For 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.json file remains available between tool calls. Each tool reads that data independently.
  • Claude conversation history: The host application can still keep and resend its messages list. MCP does not manage Claude's conversation memory.
  • Multi-step business workflows: A shopping cart could use an explicit cart_id returned 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

TEXT
MCP client → server: tools/list
MCP server → client: search_products, check_inventory (names, descriptions, input schemas)

B. Call a tool

TEXT
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

PYTHON
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

PYTHON
mcp = MCPServer("stackfable-shop")

Creates the MCP server object. It is not starting the server yet.

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

PYTHON
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

PYTHON
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

client.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:

BASH
python -m pip install "mcp>=2,<3"
python inspect_shopping_server.py

Or with uv:

BASH
uv init
uv add "mcp>=2,<3"
uv run inspect_shopping_server.py

To interactively inspect the server, install the CLI extra and launch the Inspector:

BASH
uv add "mcp[cli]>=2,<3"
uv run mcp dev shopping_server.py

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

ConcernDirect tool callingMCP server
Business logicsearch_products()Same function
Tool descriptionHandwritten Claude-specific tools schemasMCP server exposes generated tool definitions
Discovering toolsApp maintains TOOLS itselfClient asks tools/list
Running toolsTOOL_FUNCTIONS[name](**args)Client calls tools/call; server dispatches
Where tools runInside chatbot processInside MCP server process
Model decisionClaude decides tool requestsStill Claude's responsibility once connected
Conversation historyApp sends messages to ClaudeStill app's responsibility
Repeat/stop loopApp inspects Claude responsesStill 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:

  • MCPServer and @mcp.tool() to expose tools and generate input schemas.
  • Client to make MCP tools/list and tools/call requests.
  • Local stdio transport to send protocol messages between the client and server processes.
  • structured_content, content, and is_error to 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:

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

Knowledge check

A second AI host needs to use check_inventory without copying the shopping chatbot's dispatch dictionary. What should it do?
The test client calls check_inventory for kb-101. Which process reads products.json?
The client sends another tools/call request over its open stdio pipe. Under the 2026-07-28 request model, which statement fits?

Sources and further reading

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