# Building an MCP Client in Python from Scratch

> Source: <https://machinelearningmastery.com/building-an-mcp-client-in-python-from-scratch/>
> Published: 2026-11-30 11:00:00+00:00

**Recommendation:** Build the MCP client as a translation loop: connect over stdio, list the server's tools, convert them to Claude's tool format, and route each tool call back until the model stops requesting tools, handling chained calls and tool errors.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

In this article, you will learn how to build a working MCP client in Python with the official MCP Python SDK 2.0, connect it to a local server over stdio, and let Claude call that server’s tools.

Topics we will cover include:

- How an MCP client connects to a server over stdio, lists its tools, and calls them directly.
- What the JSON-RPC messages behind a tool call look like under the stateless 2026-07-28 spec revision.
- How to convert MCP tools into Claude’s tool format and route Claude’s tool calls in a loop that handles chained calls and tool errors.

## What an MCP Client Does

Three roles show up in the [MCP architecture](https://modelcontextprotocol.io/docs/2026-07-28/learn/architecture). The host is the AI application. The **server** exposes tools, resources, or prompts. The **client** sits inside the host and keeps one connection to one server. Its job is simple. It connects, asks the server what tools exist, and calls a tool when the model asks for one. The model never talks to the server directly. Your client translates in both directions, and that translation is the code you are about to write.

### Prerequisites

You need Python 3.10 or higher, the uv package manager, and an [Anthropic API key](https://console.anthropic.com/settings/keys). You must also use the Python MCP SDK 2.0.0 or higher, as the [official client guide](https://modelcontextprotocol.io/docs/2026-07-28/develop/build-client) requires.

That version note matters. The SDK reached [v2.0.0](https://github.com/modelcontextprotocol/python-sdk/releases/tag/v2.0.0) to support the 2026-07-28 spec revision, and **pip install mcp** now installs 2.x. Many tutorials still show the v1 API (**ClientSession, session.initialize()**), which does not match what you will install today. The [migration guide](https://py.sdk.modelcontextprotocol.io/migration/) covers every change if you have older code.

## Project Setup

If you do not have uv yet, install it with the command from the [official server guide](https://modelcontextprotocol.io/docs/2026-07-28/develop/build-server):

```
curl -LsSf https://astral.sh/uv/install.sh | sh

1

curl -LsSf https://astral.sh/uv/install.sh | sh
```

Then create the project:

```
# Create the project and a virtual environment
uv init mcp-client
cd mcp-client
uv venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate

# Install the MCP SDK (with CLI extras), the Anthropic SDK, and dotenv
uv add "mcp[cli]" anthropic python-dotenv

# Remove the boilerplate file and create the files we will fill in
rm main.py                  # Windows: del main.py
touch server.py explore.py client.py

# Store the API key outside your code, and keep it out of git
echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
echo ".env" >> .gitignore

12345678910111213141516

# Create the project and a virtual environmentuv init mcp-clientcd mcp-clientuv venvsource .venv/bin/activate   # Windows: .venv\Scripts\activate # Install the MCP SDK (with CLI extras), the Anthropic SDK, and dotenvuv add "mcp[cli]" anthropic python-dotenv # Remove the boilerplate file and create the files we will fill inrm main.py                  # Windows: del main.pytouch server.py explore.py client.py # Store the API key outside your code, and keep it out of gitecho "ANTHROPIC_API_KEY=your-api-key-goes-here" > .envecho ".env" >> .gitignore
```

This gives you one project that holds both sides of the connection. **mcp[cli]** brings in the server and client classes. **python-dotenv** loads your key from **.env** so it never lands in source control.

## The Test Server

A client needs something to talk to. Put this in **server.py**. It exposes two tools, so you can later watch Claude chain them.

``` python
import logging
from typing import Any
from urllib.parse import urlencode

import httpx2
from mcp.server import MCPServer

# In a stdio server, stdout carries the protocol. Logs must go to stderr.
logging.basicConfig(level=logging.INFO)  # logging writes to stderr by default
logger = logging.getLogger(__name__)

mcp = MCPServer("weather-tools")

GEOCODE_URL = "https://geocoding-api.open-meteo.com/v1/search"
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"

async def fetch_json(url: str) -> dict[str, Any] | None:
    """GET a URL and return parsed JSON, or None if anything goes wrong."""
    async with httpx2.AsyncClient() as http:
        try:
            response = await http.get(url, timeout=15.0)
            response.raise_for_status()
            return response.json()
        except Exception:
            logger.exception("Request to %s failed", url)
            return None

@mcp.tool()
async def get_weather(city: str) -> str:
    """Get the current temperature and wind speed for a city.

    Args:
        city: City name, for example Lagos or Tokyo
    """
    geo = await fetch_json(f"{GEOCODE_URL}?{urlencode({'name': city, 'count': 1})}")
    if not geo or not geo.get("results"):
        return f"Could not find a city called '{city}'."
    place = geo["results"][0]

    query = urlencode(
        {
            "latitude": place["latitude"],
            "longitude": place["longitude"],
            "current": "temperature_2m,wind_speed_10m",
        }
    )
    forecast = await fetch_json(f"{FORECAST_URL}?{query}")
    if not forecast or "current" not in forecast:
        return "Weather data is unavailable right now."

    current = forecast["current"]
    return (
        f"{place['name']}, {place.get('country', 'unknown country')}: "
        f"{current['temperature_2m']} °C, wind {current['wind_speed_10m']} km/h"
    )

@mcp.tool()
def convert_temperature(value: float, from_unit: str, to_unit: str) -> str:
    """Convert a temperature between celsius, fahrenheit and kelvin.

    Args:
        value: The temperature to convert
        from_unit: celsius, fahrenheit or kelvin
        to_unit: celsius, fahrenheit or kelvin
    """
    units = {"celsius", "fahrenheit", "kelvin"}
    source, target = from_unit.lower(), to_unit.lower()
    if source not in units or target not in units:
        # Raised errors come back to the client as a tool error the model can read
        raise ValueError("Units must be celsius, fahrenheit or kelvin.")

    # Normalise to celsius first, then convert out
    if source == "fahrenheit":
        celsius = (value - 32) * 5 / 9
    elif source == "kelvin":
        celsius = value - 273.15
    else:
        celsius = value

    if target == "fahrenheit":
        result = celsius * 9 / 5 + 32
    elif target == "kelvin":
        result = celsius + 273.15
    else:
        result = celsius
    return f"{value} {source} is {result:.1f} {target}"

if __name__ == "__main__":
    mcp.run(transport="stdio")

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293

import loggingfrom typing import Anyfrom urllib.parse import urlencode import httpx2from mcp.server import MCPServer # In a stdio server, stdout carries the protocol. Logs must go to stderr.logging.basicConfig(level=logging.INFO)  # logging writes to stderr by defaultlogger = logging.getLogger(__name__) mcp = MCPServer("weather-tools") GEOCODE_URL = "https://geocoding-api.open-meteo.com/v1/search"FORECAST_URL = "https://api.open-meteo.com/v1/forecast"  async def fetch_json(url: str) -> dict[str, Any] | None:    """GET a URL and return parsed JSON, or None if anything goes wrong."""    async with httpx2.AsyncClient() as http:        try:            response = await http.get(url, timeout=15.0)            response.raise_for_status()            return response.json()        except Exception:            logger.exception("Request to %s failed", url)            return None  @mcp.tool()async def get_weather(city: str) -> str:    """Get the current temperature and wind speed for a city.     Args:        city: City name, for example Lagos or Tokyo    """    geo = await fetch_json(f"{GEOCODE_URL}?{urlencode({'name': city, 'count': 1})}")    if not geo or not geo.get("results"):        return f"Could not find a city called '{city}'."    place = geo["results"][0]     query = urlencode(        {            "latitude": place["latitude"],            "longitude": place["longitude"],            "current": "temperature_2m,wind_speed_10m",        }    )    forecast = await fetch_json(f"{FORECAST_URL}?{query}")    if not forecast or "current" not in forecast:        return "Weather data is unavailable right now."     current = forecast["current"]    return (        f"{place['name']}, {place.get('country', 'unknown country')}: "        f"{current['temperature_2m']} °C, wind {current['wind_speed_10m']} km/h"    )  @mcp.tool()def convert_temperature(value: float, from_unit: str, to_unit: str) -> str:    """Convert a temperature between celsius, fahrenheit and kelvin.     Args:        value: The temperature to convert        from_unit: celsius, fahrenheit or kelvin        to_unit: celsius, fahrenheit or kelvin    """    units = {"celsius", "fahrenheit", "kelvin"}    source, target = from_unit.lower(), to_unit.lower()    if source not in units or target not in units:        # Raised errors come back to the client as a tool error the model can read        raise ValueError("Units must be celsius, fahrenheit or kelvin.")     # Normalise to celsius first, then convert out    if source == "fahrenheit":        celsius = (value - 32) * 5 / 9    elif source == "kelvin":        celsius = value - 273.15    else:        celsius = value     if target == "fahrenheit":        result = celsius * 9 / 5 + 32    elif target == "kelvin":        result = celsius + 273.15    else:        result = celsius    return f"{value} {source} is {result:.1f} {target}"  if __name__ == "__main__":    mcp.run(transport="stdio")
```

**MCPServer** is the SDK 2.0 name for what v1 called **FastMCP**. The **@mcp.tool()** decorator turns each function’s type hints and docstring into the tool’s name, description, and input schema, which is exactly what the client will read later. **httpx2** is the HTTP client the SDK itself depends on, as the [official server guide](https://modelcontextprotocol.io/docs/2026-07-28/develop/build-server) notes, so there is nothing extra to install. The weather data comes from the free, keyless [Open-Meteo API](https://open-meteo.com/).

The comment about stderr is not decoration. In the [stdio transport](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio), the server reads from stdin and writes JSON-RPC to stdout, and anything else written there corrupts the stream. A single stray **print()** is enough to break the server.

## Step 1: Connect and List Tools

Before any model gets involved, prove the connection works. Put this in **explore.py**:

``` python
import asyncio
import json
import sys

from mcp import Client, StdioServerParameters
from mcp.client.stdio import stdio_client

# Launch server.py with the same Python interpreter that runs this script
params = StdioServerParameters(command=sys.executable, args=["server.py"])

async def main() -> None:
    # Entering the block starts the server and connects. Leaving it shuts both down.
    async with Client(stdio_client(params)) as client:
        tool_list = await client.list_tools()
        for tool in tool_list.tools:
            print(f"\n{tool.name}: {tool.description}")
            print(json.dumps(tool.input_schema, indent=2))

if __name__ == "__main__":
    asyncio.run(main())

12345678910111213141516171819202122

import asyncioimport jsonimport sys from mcp import Client, StdioServerParametersfrom mcp.client.stdio import stdio_client # Launch server.py with the same Python interpreter that runs this scriptparams = StdioServerParameters(command=sys.executable, args=["server.py"])  async def main() -> None:    # Entering the block starts the server and connects. Leaving it shuts both down.    async with Client(stdio_client(params)) as client:        tool_list = await client.list_tools()        for tool in tool_list.tools:            print(f"\n{tool.name}: {tool.description}")            print(json.dumps(tool.input_schema, indent=2))  if __name__ == "__main__":    asyncio.run(main())
```

Run it with **uv run explore.py** from the project folder.

**StdioServerParameters** only describes the subprocess to launch. **stdio_client()** turns that description into a transport, and **Client** opens the transport when you enter its async with block. According to the [official guide](https://modelcontextprotocol.io/docs/2026-07-28/develop/build-client), that block is the entire connection lifecycle, so there is nothing to close by hand. Using **sys.executable** instead of the string **“python”** guarantees the server runs in the same virtual environment as the client.

You should see both tools printed with their JSON Schema. That schema is what the model will use to decide how to call them.

## Step 2: Call a Tool Directly

Now call a tool yourself, with no model involved. Replace **main()** in **explore.py** with the code below. Put the new import with the others at the top of the file, and the helper function just above **main()**:

``` php
from mcp_types import TextContent

def result_text(result) -> str:
    """Join the text blocks of a tool result into one string."""
    return "\n".join(
        block.text for block in result.content if isinstance(block, TextContent)
    )

async def main() -> None:
    async with Client(stdio_client(params)) as client:
        ok = await client.call_tool(
            "convert_temperature",
            {"value": 30, "from_unit": "celsius", "to_unit": "fahrenheit"},
        )
        print(result_text(ok), "| is_error:", ok.is_error)

        # An invalid unit makes the tool raise on the server side
        bad = await client.call_tool(
            "convert_temperature",
            {"value": 1, "from_unit": "celsius", "to_unit": "rankine"},
        )
        print(result_text(bad), "| is_error:", bad.is_error)

123456789101112131415161718192021222324

from mcp_types import TextContent  def result_text(result) -> str:    """Join the text blocks of a tool result into one string."""    return "\n".join(        block.text for block in result.content if isinstance(block, TextContent)    )  async def main() -> None:    async with Client(stdio_client(params)) as client:        ok = await client.call_tool(            "convert_temperature",            {"value": 30, "from_unit": "celsius", "to_unit": "fahrenheit"},        )        print(result_text(ok), "| is_error:", ok.is_error)         # An invalid unit makes the tool raise on the server side        bad = await client.call_tool(            "convert_temperature",            {"value": 1, "from_unit": "celsius", "to_unit": "rankine"},        )        print(result_text(bad), "| is_error:", bad.is_error)
```

**call_tool** returns a **CallToolResult**. Its **content** is a list of blocks, which is why **result_text** narrows to **TextContent** before reading **.text**. The second call shows the part people miss: a failing tool does not raise an exception in your client. It answers with **is_error** set to True, and the message tells the model what went wrong so it can try again. Remember this flag, because the next steps depend on it.

## What Just Happened on the Wire

The SDK hid the messages. Here is what crossed the connection, simplified. Under the [stdio transport](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio), each JSON-RPC message is sent on a single line. The examples below are pretty-printed for readability.

Your **call_tool** call produced a request like this:

```
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "convert_temperature",
    "arguments": { "value": 30, "from_unit": "celsius", "to_unit": "fahrenheit" }
  }
}

123456789

{  "jsonrpc": "2.0",  "id": 2,  "method": "tools/call",  "params": {    "name": "convert_temperature",    "arguments": { "value": 30, "from_unit": "celsius", "to_unit": "fahrenheit" }  }}
```

And the server answered:

```
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "resultType": "complete",
    "content": [{ "type": "text", "text": "30.0 celsius is 86.0 fahrenheit" }],
    "isError": false
  }
}

123456789

{  "jsonrpc": "2.0",  "id": 2,  "result": {    "resultType": "complete",    "content": [{ "type": "text", "text": "30.0 celsius is 86.0 fahrenheit" }],    "isError": false  }}
```

These shapes follow the [tools section of the 2026-07-28 spec](https://modelcontextprotocol.io/specification/2026-07-28/server/tools.md). Four details are worth knowing.

1. First, there is no handshake anymore. The [2026-07-28 revision](https://modelcontextprotocol.io/specification/2026-07-28/changelog.md) removed**initialize** and made MCP stateless. Every request carries its protocol version and client capabilities in**_meta** , which the examples above leave out for brevity, as the spec’s own examples do.
2. Second, servers must implement a new **server/discover** call that advertises their supported versions, capabilities, and identity. Clients can use it to pick a version up front or to probe older servers. You never call it yourself, because the[SDK’s Client negotiates the version automatically](https://github.com/modelcontextprotocol/python-sdk/releases/tag/v2.0.0) and still works with 2025-era servers.
3. Third, every result carries a **resultType** , and**“complete”** means an ordinary result.
4. Fourth, errors come in two kinds. A malformed request or unknown tool is a protocol-level JSON-RPC error. A tool that ran and failed returns a normal result with **isError: true** . Your client should pass the second kind to the model, because the spec says tool execution errors are what let a model correct itself.

## Step 3: Turn MCP Tools into Claude Tools

Claude needs each tool described in its own format. The two formats line up almost one to one:

| **MCP tool field** | **Claude tool field** | 
|---|---|
| name | name | 
| description | description | 
| input_schema | input_schema | 

The [official guide](https://modelcontextprotocol.io/docs/2026-07-28/develop/build-client) does the same mapping. This is the first piece of **client.py**:

``` python
import asyncio
import sys

from anthropic import AsyncAnthropic
from dotenv import load_dotenv
from mcp import Client, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp_types import TextContent

load_dotenv()  # loads ANTHROPIC_API_KEY from .env

MODEL = "claude-opus-5-5"  # any tool-capable Claude model works here
MAX_TURNS = 8  # hard stop so a confused model cannot loop forever
anthropic = AsyncAnthropic()

def server_params(server_script_path: str) -> StdioServerParameters:
    """Describe the subprocess that runs the server script."""
    if server_script_path.endswith(".py"):
        command = sys.executable
    elif server_script_path.endswith(".js"):
        command = "node"
    else:
        raise ValueError("Server script must be a .py or .js file")
    return StdioServerParameters(command=command, args=[server_script_path])

def to_claude_tools(tool_list) -> list[dict]:
    """Convert MCP tool definitions into Claude's tool format."""
    return [
        {
            "name": tool.name,
            "description": tool.description or "",
            "input_schema": tool.input_schema,
        }
        for tool in tool_list.tools
    ]

def result_text(result) -> str:
    """Join the text blocks of a tool result into one string."""
    return "\n".join(
        block.text for block in result.content if isinstance(block, TextContent)
    )

1234567891011121314151617181920212223242526272829303132333435363738394041424344

import asyncioimport sys from anthropic import AsyncAnthropicfrom dotenv import load_dotenvfrom mcp import Client, StdioServerParametersfrom mcp.client.stdio import stdio_clientfrom mcp_types import TextContent load_dotenv()  # loads ANTHROPIC_API_KEY from .env MODEL = "claude-opus-5-5"  # any tool-capable Claude model works hereMAX_TURNS = 8  # hard stop so a confused model cannot loop foreveranthropic = AsyncAnthropic()  def server_params(server_script_path: str) -> StdioServerParameters:    """Describe the subprocess that runs the server script."""    if server_script_path.endswith(".py"):        command = sys.executable    elif server_script_path.endswith(".js"):        command = "node"    else:        raise ValueError("Server script must be a .py or .js file")    return StdioServerParameters(command=command, args=[server_script_path])  def to_claude_tools(tool_list) -> list[dict]:    """Convert MCP tool definitions into Claude's tool format."""    return [        {            "name": tool.name,            "description": tool.description or "",            "input_schema": tool.input_schema,        }        for tool in tool_list.tools    ]  def result_text(result) -> str:    """Join the text blocks of a tool result into one string."""    return "\n".join(        block.text for block in result.content if isinstance(block, TextContent)    )
```

**server_params** accepts a Python or Node server, so the client works with servers written in either language. **AsyncAnthropic** is used instead of the sync client so model calls do not block the event loop that is serving the MCP connection. Swap **MODEL** for any tool-capable model from [Anthropic’s model list](https://platform.claude.com/docs/en/models/opus-5-5/overview).

## Step 4: Route the Model’s Tool Calls

This is the core of the client. When Claude wants a tool, your code runs it through the server and returns the result. That can happen several times in a row, so it needs a loop. Add this to **client.py**:

``` php
async def process_query(client: Client, tools: list[dict], query: str) -> str:
    """Answer a query, letting Claude call MCP tools until it is done."""
    messages = [{"role": "user", "content": query}]

    for _ in range(MAX_TURNS):
        response = await anthropic.messages.create(
            model=MODEL,
            max_tokens=2048,
            messages=messages,
            tools=tools,
        )

        # No tool request means Claude has given its final answer
        if response.stop_reason != "tool_use":
            return "\n".join(b.text for b in response.content if b.type == "text")

        # Keep Claude's full turn in the history, exactly as returned
        messages.append({"role": "assistant", "content": response.content})

        tool_results = []
        for block in response.content:
            if block.type != "tool_use":
                continue
            print(f"[Calling tool {block.name} with args {block.input}]")
            result = await client.call_tool(block.name, block.input)
            tool_results.append(
                {
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": result_text(result),
                    "is_error": result.is_error,
                }
            )

        # Tool results go back as a user message, then the loop asks Claude again
        messages.append({"role": "user", "content": tool_results})

    return "Stopped after reaching the turn limit."

1234567891011121314151617181920212223242526272829303132333435363738

async def process_query(client: Client, tools: list[dict], query: str) -> str:    """Answer a query, letting Claude call MCP tools until it is done."""    messages = [{"role": "user", "content": query}]     for _ in range(MAX_TURNS):        response = await anthropic.messages.create(            model=MODEL,            max_tokens=2048,            messages=messages,            tools=tools,        )         # No tool request means Claude has given its final answer        if response.stop_reason != "tool_use":            return "\n".join(b.text for b in response.content if b.type == "text")         # Keep Claude's full turn in the history, exactly as returned        messages.append({"role": "assistant", "content": response.content})         tool_results = []        for block in response.content:            if block.type != "tool_use":                continue            print(f"[Calling tool {block.name} with args {block.input}]")            result = await client.call_tool(block.name, block.input)            tool_results.append(                {                    "type": "tool_result",                    "tool_use_id": block.id,                    "content": result_text(result),                    "is_error": result.is_error,                }            )         # Tool results go back as a user message, then the loop asks Claude again        messages.append({"role": "user", "content": tool_results})     return "Stopped after reaching the turn limit."
```

Here is the flow. Claude replies either with text or with one or more **tool_use** blocks, and **stop_reason** tells you which. For each **tool_use** block, **client.call_tool** sends a **tools/call** request to the server, and the result goes back to Claude as a **tool_result** tied to the block’s id. Passing **is_error** along lets Claude read a failure and recover, which is the behavior you saw in Step 2.

Two details are easy to get wrong. Append **response.content** untouched instead of rebuilding it, because the model’s thinking blocks must stay with the conversation that produced them, as the [Opus 5.5 docs](https://platform.claude.com/docs/en/models/opus-5-5/overview) describe. And keep **MAX_TURNS**. The official quickstart makes a single round of tool calls, which breaks on any question that needs two tools in sequence.

## Step 5: Chat Loop and Entry Point

Finish **client.py** with the chat loop and **main**:

``` php
async def chat_loop(client: Client, tools: list[dict]) -> None:
    print("\nType a question, or 'quit' to exit.")
    while True:
        try:
            # input() blocks, so run it on a worker thread
            query = (await asyncio.to_thread(input, "\nQuery: ")).strip()
        except EOFError:
            break
        if query.lower() == "quit":
            break
        if not query:
            continue
        try:
            print("\n" + await process_query(client, tools, query))
        except Exception as e:
            print(f"\nError: {e}")  # report it, keep the session alive

async def main() -> None:
    if len(sys.argv) < 2:
        print("Usage: python client.py <path_to_server_script>")
        sys.exit(1)

    async with Client(stdio_client(server_params(sys.argv[1]))) as client:
        tools = to_claude_tools(await client.list_tools())
        print("Connected to server with tools:", [t["name"] for t in tools])
        await chat_loop(client, tools)

if __name__ == "__main__":
    asyncio.run(main())

12345678910111213141516171819202122232425262728293031

async def chat_loop(client: Client, tools: list[dict]) -> None:    print("\nType a question, or 'quit' to exit.")    while True:        try:            # input() blocks, so run it on a worker thread            query = (await asyncio.to_thread(input, "\nQuery: ")).strip()        except EOFError:            break        if query.lower() == "quit":            break        if not query:            continue        try:            print("\n" + await process_query(client, tools, query))        except Exception as e:            print(f"\nError: {e}")  # report it, keep the session alive  async def main() -> None:    if len(sys.argv) < 2:        print("Usage: python client.py <path_to_server_script>")        sys.exit(1)     async with Client(stdio_client(server_params(sys.argv[1]))) as client:        tools = to_claude_tools(await client.list_tools())        print("Connected to server with tools:", [t["name"] for t in tools])        await chat_loop(client, tools)  if __name__ == "__main__":    asyncio.run(main())
```

**asyncio.to_thread(input, …)** keeps the event loop free to service the connection while you type. The tool list is fetched once and reused for every query. A failed query prints an error, and the session continues. Leaving the **async with** block disconnects and shuts the server subprocess down.

Let’s run it:

```
uv run client.py server.py

1

uv run client.py server.py
```

You should see **Connected to server with tools:** followed by both tool names. Try three prompts in order:

1. “What is the capital of France?” — Claude answers directly, and no tool is called.
2. “What is the weather in Lagos?” — You see one [Calling tool get_weather …] line, then an answer.
3. “What is the temperature in Lagos in Fahrenheit?” — You see two tool lines. Claude fetches Celsius with **get_weather** , then calls**convert_temperature** on that number. Your loop made the chain possible.

The first response can be slow while the server starts and the model thinks, so give it a moment.

## Conclusion

You built an MCP client that launches a server over stdio, lists its tools, calls them directly, converts them into Claude’s format, and routes the model’s tool calls in a loop that handles chained requests and tool errors. You also saw the messages underneath: stateless **JSON-RPC**, **tools/list**, **tools/call**, and the difference between protocol errors and tool errors.
