{"slug": "building-an-mcp-client-in-python-from-scratch", "title": "Building an MCP Client in Python from Scratch", "summary": "A tutorial demonstrates building a working Model Context Protocol (MCP) client in Python using the official MCP Python SDK 2.0.0 or higher, connecting to a local server over stdio and routing Claude's tool calls through a loop that handles chained calls and tool errors. The guide targets the stateless 2026-07-28 spec revision and warns that many existing tutorials still show the v1 API (ClientSession, session.initialize()), which no longer matches what `pip install mcp` installs. It requires Python 3.10 or higher, the uv package manager, and an Anthropic API key.", "body_md": "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.\n\nTopics we will cover include:\n\n- How an MCP client connects to a server over stdio, lists its tools, and calls them directly.\n- What the JSON-RPC messages behind a tool call look like under the stateless 2026-07-28 spec revision.\n- 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.\n\n## What an MCP Client Does\n\nThree 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.\n\n### Prerequisites\n\nYou 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.\n\nThat 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.\n\n## Project Setup\n\nIf 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):\n\n```\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n1\n\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n```\n\nThen create the project:\n\n```\n# Create the project and a virtual environment\nuv init mcp-client\ncd mcp-client\nuv venv\nsource .venv/bin/activate   # Windows: .venv\\Scripts\\activate\n\n# Install the MCP SDK (with CLI extras), the Anthropic SDK, and dotenv\nuv add \"mcp[cli]\" anthropic python-dotenv\n\n# Remove the boilerplate file and create the files we will fill in\nrm main.py                  # Windows: del main.py\ntouch server.py explore.py client.py\n\n# Store the API key outside your code, and keep it out of git\necho \"ANTHROPIC_API_KEY=your-api-key-goes-here\" > .env\necho \".env\" >> .gitignore\n\n12345678910111213141516\n\n# 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\n```\n\nThis 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.\n\n## The Test Server\n\nA client needs something to talk to. Put this in **server.py**. It exposes two tools, so you can later watch Claude chain them.\n\n``` python\nimport logging\nfrom typing import Any\nfrom urllib.parse import urlencode\n\nimport httpx2\nfrom mcp.server import MCPServer\n\n# In a stdio server, stdout carries the protocol. Logs must go to stderr.\nlogging.basicConfig(level=logging.INFO)  # logging writes to stderr by default\nlogger = logging.getLogger(__name__)\n\nmcp = MCPServer(\"weather-tools\")\n\nGEOCODE_URL = \"https://geocoding-api.open-meteo.com/v1/search\"\nFORECAST_URL = \"https://api.open-meteo.com/v1/forecast\"\n\nasync def fetch_json(url: str) -> dict[str, Any] | None:\n    \"\"\"GET a URL and return parsed JSON, or None if anything goes wrong.\"\"\"\n    async with httpx2.AsyncClient() as http:\n        try:\n            response = await http.get(url, timeout=15.0)\n            response.raise_for_status()\n            return response.json()\n        except Exception:\n            logger.exception(\"Request to %s failed\", url)\n            return None\n\n@mcp.tool()\nasync def get_weather(city: str) -> str:\n    \"\"\"Get the current temperature and wind speed for a city.\n\n    Args:\n        city: City name, for example Lagos or Tokyo\n    \"\"\"\n    geo = await fetch_json(f\"{GEOCODE_URL}?{urlencode({'name': city, 'count': 1})}\")\n    if not geo or not geo.get(\"results\"):\n        return f\"Could not find a city called '{city}'.\"\n    place = geo[\"results\"][0]\n\n    query = urlencode(\n        {\n            \"latitude\": place[\"latitude\"],\n            \"longitude\": place[\"longitude\"],\n            \"current\": \"temperature_2m,wind_speed_10m\",\n        }\n    )\n    forecast = await fetch_json(f\"{FORECAST_URL}?{query}\")\n    if not forecast or \"current\" not in forecast:\n        return \"Weather data is unavailable right now.\"\n\n    current = forecast[\"current\"]\n    return (\n        f\"{place['name']}, {place.get('country', 'unknown country')}: \"\n        f\"{current['temperature_2m']} °C, wind {current['wind_speed_10m']} km/h\"\n    )\n\n@mcp.tool()\ndef convert_temperature(value: float, from_unit: str, to_unit: str) -> str:\n    \"\"\"Convert a temperature between celsius, fahrenheit and kelvin.\n\n    Args:\n        value: The temperature to convert\n        from_unit: celsius, fahrenheit or kelvin\n        to_unit: celsius, fahrenheit or kelvin\n    \"\"\"\n    units = {\"celsius\", \"fahrenheit\", \"kelvin\"}\n    source, target = from_unit.lower(), to_unit.lower()\n    if source not in units or target not in units:\n        # Raised errors come back to the client as a tool error the model can read\n        raise ValueError(\"Units must be celsius, fahrenheit or kelvin.\")\n\n    # Normalise to celsius first, then convert out\n    if source == \"fahrenheit\":\n        celsius = (value - 32) * 5 / 9\n    elif source == \"kelvin\":\n        celsius = value - 273.15\n    else:\n        celsius = value\n\n    if target == \"fahrenheit\":\n        result = celsius * 9 / 5 + 32\n    elif target == \"kelvin\":\n        result = celsius + 273.15\n    else:\n        result = celsius\n    return f\"{value} {source} is {result:.1f} {target}\"\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"stdio\")\n\n123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293\n\nimport 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\")\n```\n\n**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/).\n\nThe 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.\n\n## Step 1: Connect and List Tools\n\nBefore any model gets involved, prove the connection works. Put this in **explore.py**:\n\n``` python\nimport asyncio\nimport json\nimport sys\n\nfrom mcp import Client, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\n\n# Launch server.py with the same Python interpreter that runs this script\nparams = StdioServerParameters(command=sys.executable, args=[\"server.py\"])\n\nasync def main() -> None:\n    # Entering the block starts the server and connects. Leaving it shuts both down.\n    async with Client(stdio_client(params)) as client:\n        tool_list = await client.list_tools()\n        for tool in tool_list.tools:\n            print(f\"\\n{tool.name}: {tool.description}\")\n            print(json.dumps(tool.input_schema, indent=2))\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n\n12345678910111213141516171819202122\n\nimport 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())\n```\n\nRun it with **uv run explore.py** from the project folder.\n\n**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.\n\nYou should see both tools printed with their JSON Schema. That schema is what the model will use to decide how to call them.\n\n## Step 2: Call a Tool Directly\n\nNow 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()**:\n\n``` php\nfrom mcp_types import TextContent\n\ndef result_text(result) -> str:\n    \"\"\"Join the text blocks of a tool result into one string.\"\"\"\n    return \"\\n\".join(\n        block.text for block in result.content if isinstance(block, TextContent)\n    )\n\nasync def main() -> None:\n    async with Client(stdio_client(params)) as client:\n        ok = await client.call_tool(\n            \"convert_temperature\",\n            {\"value\": 30, \"from_unit\": \"celsius\", \"to_unit\": \"fahrenheit\"},\n        )\n        print(result_text(ok), \"| is_error:\", ok.is_error)\n\n        # An invalid unit makes the tool raise on the server side\n        bad = await client.call_tool(\n            \"convert_temperature\",\n            {\"value\": 1, \"from_unit\": \"celsius\", \"to_unit\": \"rankine\"},\n        )\n        print(result_text(bad), \"| is_error:\", bad.is_error)\n\n123456789101112131415161718192021222324\n\nfrom 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)\n```\n\n**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.\n\n## What Just Happened on the Wire\n\nThe 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.\n\nYour **call_tool** call produced a request like this:\n\n```\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 2,\n  \"method\": \"tools/call\",\n  \"params\": {\n    \"name\": \"convert_temperature\",\n    \"arguments\": { \"value\": 30, \"from_unit\": \"celsius\", \"to_unit\": \"fahrenheit\" }\n  }\n}\n\n123456789\n\n{  \"jsonrpc\": \"2.0\",  \"id\": 2,  \"method\": \"tools/call\",  \"params\": {    \"name\": \"convert_temperature\",    \"arguments\": { \"value\": 30, \"from_unit\": \"celsius\", \"to_unit\": \"fahrenheit\" }  }}\n```\n\nAnd the server answered:\n\n```\n{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 2,\n  \"result\": {\n    \"resultType\": \"complete\",\n    \"content\": [{ \"type\": \"text\", \"text\": \"30.0 celsius is 86.0 fahrenheit\" }],\n    \"isError\": false\n  }\n}\n\n123456789\n\n{  \"jsonrpc\": \"2.0\",  \"id\": 2,  \"result\": {    \"resultType\": \"complete\",    \"content\": [{ \"type\": \"text\", \"text\": \"30.0 celsius is 86.0 fahrenheit\" }],    \"isError\": false  }}\n```\n\nThese 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.\n\n1. 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.\n2. 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.\n3. Third, every result carries a **resultType** , and**“complete”** means an ordinary result.\n4. 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.\n\n## Step 3: Turn MCP Tools into Claude Tools\n\nClaude needs each tool described in its own format. The two formats line up almost one to one:\n\n| **MCP tool field** | **Claude tool field** | \n|---|---|\n| name | name | \n| description | description | \n| input_schema | input_schema | \n\nThe [official guide](https://modelcontextprotocol.io/docs/2026-07-28/develop/build-client) does the same mapping. This is the first piece of **client.py**:\n\n``` python\nimport asyncio\nimport sys\n\nfrom anthropic import AsyncAnthropic\nfrom dotenv import load_dotenv\nfrom mcp import Client, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\nfrom mcp_types import TextContent\n\nload_dotenv()  # loads ANTHROPIC_API_KEY from .env\n\nMODEL = \"claude-opus-5-5\"  # any tool-capable Claude model works here\nMAX_TURNS = 8  # hard stop so a confused model cannot loop forever\nanthropic = AsyncAnthropic()\n\ndef server_params(server_script_path: str) -> StdioServerParameters:\n    \"\"\"Describe the subprocess that runs the server script.\"\"\"\n    if server_script_path.endswith(\".py\"):\n        command = sys.executable\n    elif server_script_path.endswith(\".js\"):\n        command = \"node\"\n    else:\n        raise ValueError(\"Server script must be a .py or .js file\")\n    return StdioServerParameters(command=command, args=[server_script_path])\n\ndef to_claude_tools(tool_list) -> list[dict]:\n    \"\"\"Convert MCP tool definitions into Claude's tool format.\"\"\"\n    return [\n        {\n            \"name\": tool.name,\n            \"description\": tool.description or \"\",\n            \"input_schema\": tool.input_schema,\n        }\n        for tool in tool_list.tools\n    ]\n\ndef result_text(result) -> str:\n    \"\"\"Join the text blocks of a tool result into one string.\"\"\"\n    return \"\\n\".join(\n        block.text for block in result.content if isinstance(block, TextContent)\n    )\n\n1234567891011121314151617181920212223242526272829303132333435363738394041424344\n\nimport 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)    )\n```\n\n**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).\n\n## Step 4: Route the Model’s Tool Calls\n\nThis 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**:\n\n``` php\nasync def process_query(client: Client, tools: list[dict], query: str) -> str:\n    \"\"\"Answer a query, letting Claude call MCP tools until it is done.\"\"\"\n    messages = [{\"role\": \"user\", \"content\": query}]\n\n    for _ in range(MAX_TURNS):\n        response = await anthropic.messages.create(\n            model=MODEL,\n            max_tokens=2048,\n            messages=messages,\n            tools=tools,\n        )\n\n        # No tool request means Claude has given its final answer\n        if response.stop_reason != \"tool_use\":\n            return \"\\n\".join(b.text for b in response.content if b.type == \"text\")\n\n        # Keep Claude's full turn in the history, exactly as returned\n        messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n        tool_results = []\n        for block in response.content:\n            if block.type != \"tool_use\":\n                continue\n            print(f\"[Calling tool {block.name} with args {block.input}]\")\n            result = await client.call_tool(block.name, block.input)\n            tool_results.append(\n                {\n                    \"type\": \"tool_result\",\n                    \"tool_use_id\": block.id,\n                    \"content\": result_text(result),\n                    \"is_error\": result.is_error,\n                }\n            )\n\n        # Tool results go back as a user message, then the loop asks Claude again\n        messages.append({\"role\": \"user\", \"content\": tool_results})\n\n    return \"Stopped after reaching the turn limit.\"\n\n1234567891011121314151617181920212223242526272829303132333435363738\n\nasync 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.\"\n```\n\nHere 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.\n\nTwo 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.\n\n## Step 5: Chat Loop and Entry Point\n\nFinish **client.py** with the chat loop and **main**:\n\n``` php\nasync def chat_loop(client: Client, tools: list[dict]) -> None:\n    print(\"\\nType a question, or 'quit' to exit.\")\n    while True:\n        try:\n            # input() blocks, so run it on a worker thread\n            query = (await asyncio.to_thread(input, \"\\nQuery: \")).strip()\n        except EOFError:\n            break\n        if query.lower() == \"quit\":\n            break\n        if not query:\n            continue\n        try:\n            print(\"\\n\" + await process_query(client, tools, query))\n        except Exception as e:\n            print(f\"\\nError: {e}\")  # report it, keep the session alive\n\nasync def main() -> None:\n    if len(sys.argv) < 2:\n        print(\"Usage: python client.py <path_to_server_script>\")\n        sys.exit(1)\n\n    async with Client(stdio_client(server_params(sys.argv[1]))) as client:\n        tools = to_claude_tools(await client.list_tools())\n        print(\"Connected to server with tools:\", [t[\"name\"] for t in tools])\n        await chat_loop(client, tools)\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n\n12345678910111213141516171819202122232425262728293031\n\nasync 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())\n```\n\n**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.\n\nLet’s run it:\n\n```\nuv run client.py server.py\n\n1\n\nuv run client.py server.py\n```\n\nYou should see **Connected to server with tools:** followed by both tool names. Try three prompts in order:\n\n1. “What is the capital of France?” — Claude answers directly, and no tool is called.\n2. “What is the weather in Lagos?” — You see one [Calling tool get_weather …] line, then an answer.\n3. “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.\n\nThe first response can be slow while the server starts and the model thinks, so give it a moment.\n\n## Conclusion\n\nYou 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.", "url": "https://wpnews.pro/news/building-an-mcp-client-in-python-from-scratch", "canonical_source": "https://machinelearningmastery.com/building-an-mcp-client-in-python-from-scratch/", "published_at": "2026-11-30 11:00:00+00:00", "updated_at": "2026-11-30 13:46:31.583269+00:00", "lang": "en", "topics": ["ai-agents", "agent-protocols", "developer-tools", "large-language-models", "ai-tools"], "entities": ["Model Context Protocol", "MCP Python SDK", "Anthropic", "Claude", "uv", "Python"], "also_reported_by": [], "takeaway": "With MCP Python SDK 2.0.0+ targeting the 2026-07-28 spec, the client connects to a server over stdio, lists tools, converts them to Claude's tool format, and loops on Claude's tool calls to handle chained calls and tool errors; the v1 ClientSession/session.initialize() API no longer matches what pip", "recommendation": {"advice": "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.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/building-an-mcp-client-in-python-from-scratch", "markdown": "https://wpnews.pro/news/building-an-mcp-client-in-python-from-scratch.md", "text": "https://wpnews.pro/news/building-an-mcp-client-in-python-from-scratch.txt", "jsonld": "https://wpnews.pro/news/building-an-mcp-client-in-python-from-scratch.jsonld"}}