Mon 30 Nov 2026 International edition
Outdoor and Survival Gear The Small Stick Climbing Device: A Climber’s Review of Innovation and Early Challenges
Consumer Electronics and Gadgets Astronomers detect the first direct radio signal from an exoplanet in a historic milestone for planetary science.
Artificial Intelligence and Future Tech Building Local Agentic AI Workflows with Hermes Agent and Ollama for Complete Privacy and Zero Cost
Automotive Tech and EVs Honda to Accelerate Next-Generation Hybrid Production with New CR-V Powertrain in 2027
Consumer Electronics and Gadgets UFC 331 Live Stream: How to Watch Van vs Pantoja 2 From Anywhere
Consumer Electronics and Gadgets Microsoft Edge Integrates Copilot Discover to Transform User Browsing and Content Curation
Everyday Carry and Lifestyle Gear How to Estimate Knife Steel Properties Based on Chemical Composition and Metallurgy
Consumer Electronics and Gadgets Samsung’s Galaxy Ring Achieves Pioneering FDA Clearance for Sleep Apnea Risk Detection, Redefining Wearable Health Monitoring
Automotive Tech and EVs The BMW XM: A Bold Leap into the Performance SUV Arena or a Niche Contender?
Everyday Carry and Lifestyle Gear Garmin Challenges Subscription-Based Wearables with Launch of Cirqa Screen-less Smart Band
Computing and Laptops Microsoft quietly retires Copilot+ PC branding as new Surface hardware signals a shift in AI marketing strategy
Audio and Hi-Fi Equipment Samsung S99H versus Sony Bravia 8 II: A comprehensive analysis of the flagship OLED landscape this Black Friday

Artificial Intelligence and Future Tech

Building An MCP Client In Python From Scratch

The modern landscape of artificial intelligence development has shifted toward open, interoperable architectures that allow large language models to interact seamlessly with external data sources and local computational environments. Among the most significant advancements in this domain is the Model Context Protocol (MCP), an open standard engineered by Anthropic to streamline how AI applications communicate with external data repositories, toolsets, and execution backends. As development frameworks evolve, engineering robust, secure, and performant client interfaces has become paramount for developers seeking to harness the full potential of context-aware AI systems. This comprehensive guide details the technical implementation of a fully functional MCP client built in Python utilizing the official Model Context Protocol Python SDK 2.0. By establishing a localized standard input/output (stdio) connection between an AI host application and a specialized tool-serving backend, developers can construct sophisticated execution pipelines where models like Claude dynamically discover, invoke, and chain remote capabilities without direct network exposure.

Understanding the Model Context Protocol Architecture

The foundational architecture of the Model Context Protocol relies on a distinct separation of concerns divided into three core entities: the host, the client, and the server. Within this ecosystem, the host functions as the primary AI application orchestrating the user interface and the underlying model calls. The server acts as a specialized provider, exposing a curated set of capabilities categorized into tools, resources, and prompts. Situated directly between the host application and the server is the MCP client.

The client maintains a dedicated, persistent communication link with a single server instance. Its primary responsibility is translation and lifecycle management. Upon initialization, the client queries the server to catalog available functionalities, dynamically transforms these definitions into a format compatible with the targeted large language model, and intercepts model-generated execution requests to invoke the appropriate backend tools. Crucially, the AI model never communicates directly with the server infrastructure. All requests and responses are brokered, validated, and translated by the client runtime code, ensuring strict security boundaries and predictable data flow.

Prerequisites and Environment Preparation

Before initiating development, developers must ensure their local environment meets specific technical requirements. The implementation requires Python version 3.10 or higher, the high-performance Astral uv package manager, and a valid Anthropic API key. Furthermore, utilizing version 2.0.0 or higher of the official Python MCP SDK is mandatory. The transition from version 1.x to version 2.0.0 introduced critical structural revisions designed to align with the latest protocol specifications, notably deprecating legacy classes such as ClientSession and initialization methods like session.initialize(). Developers migrating legacy codebases must consult the official migration documentation to update deprecated syntax.

To establish the project environment efficiently, developers can deploy the uv package manager via its official installation script:

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

Following the installation of uv, developers can initialize a dedicated project workspace, establish an isolated virtual environment, and install the required dependencies using the following terminal commands:

uv init mcp-client
cd mcp-client
uv venv
source .venv/bin/activate  # On Windows: .venvScriptsactivate
uv add "mcp[cli]" anthropic python-dotenv
rm main.py                 # On Windows: del main.py
touch server.py explore.py client.py
echo "ANTHROPIC_API_KEY=your-api-key-goes-here" > .env
echo ".env" >> .gitignore

The inclusion of the mcp[cli] package bundles both server and client runtime utilities, while python-dotenv ensures sensitive credentials remain externalized from source control repositories.

Designing and Implementing the Test Server

To test and validate the client implementation, developers require a functional server backend capable of handling requests over the stdio transport layer. The server module, designated as server.py, exposes multiple operational tools that allow the AI model to execute data retrieval and logical computation.

import logging
from typing import Any
from urllib.parse import urlencode
import httpx
from mcp.server import MCPServer

logging.basicConfig(level=logging.INFO)
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:
    async with httpx.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:
        raise ValueError("Units must be celsius, fahrenheit or kelvin.")

    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")

The MCPServer class serves as the high-level abstraction for exposing tools via Python functions decorated with @mcp.tool(). Type annotations and docstrings are automatically parsed into standardized JSON schemas that downstream clients and language models rely upon for parameter validation. When implementing stdio-based servers, developers must ensure that standard output is strictly reserved for the protocol stream; any extraneous logging or standard print statements written to stdout will corrupt the JSON-RPC message framing. Consequently, logging is explicitly configured to direct output to standard error (stderr).

Establishing Connectivity and Tool Discovery

Before integrating a large language model into the execution pipeline, developers must verify that the client can successfully establish a subprocess connection, initialize the transport layer, and catalog available tools. The discovery script (explore.py) accomplishes this by instantiating the client over the stdio transport layer:

import asyncio
import json
import sys
from mcp import Client, StdioServerParameters
from mcp.client.stdio import stdio_client

params = StdioServerParameters(command=sys.executable, args=["server.py"])

async def main() -> None:
    async with Client(stdio_client(params)) as client:
        tool_list = await client.list_tools()
        for tool in tool_list.tools:
            print(f"ntool.name: tool.description")
            print(json.dumps(tool.input_schema, indent=2))

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

By leveraging sys.executable, the client guarantees that the server subprocess executes within the exact same virtual environment context, preventing dependency resolution failures. The asynchronous context manager (async with) manages the complete lifecycle of the connection, automatically launching the subprocess upon entry and terminating it upon exit without requiring manual teardown logic.

Direct Tool Invocation and Error Handling Semantics

Once connectivity is verified, developers can execute direct tool calls programmatically to understand how data is returned and how execution errors are propagated across the protocol boundary. Expanding the exploration script allows for testing both successful executions and edge cases where servers raise exceptions:

from mcp_types import TextContent

def result_text(result) -> str:
    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)

        bad = await client.call_tool(
            "convert_temperature",
            "value": 1, "from_unit": "celsius", "to_unit": "rankine",
        )
        print(result_text(bad), "| is_error:", bad.is_error)

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

A critical architectural distinction within the Model Context Protocol is that server-side exceptions during tool execution do not manifest as client-side Python exceptions. Instead, the server encapsulates the error message within a CallToolResult object, setting the is_error boolean flag to True. This design choice empowers the language model to read the error diagnostic directly, allowing it to self-correct its argument structure and re-attempt execution in subsequent conversational turns.

Under the Hood: The JSON-RPC Wire Protocol

Beneath the abstraction layer of the Python SDK, communication between the client and server is governed by JSON-RPC 2.0 messages transmitted over standard input and output streams. Each message is serialized as a single newline-delimited JSON string. For instance, when the client invokes a tool conversion request, it dispatches a payload formatted as follows:


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

In response, the server processes the request and returns a standardized result object confirming execution success:


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

This stateless message interchange forms the bedrock of the protocol, ensuring language-agnostic interoperability where clients and servers written in Python, TypeScript, Go, or Rust can communicate seamlessly.

Translating MCP Definitions for Large Language Models

To enable a frontier model like Claude to interact with MCP servers, tool definitions retrieved via client.list_tools() must be mapped into the specific schema format expected by the Anthropic API. The structural mapping is remarkably straightforward, requiring direct transposition of tool names, descriptions, and input schemas. The implementation of client.py begins with initialization and schema translation logic:

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()

MODEL = "claude-3-7-sonnet-20250219"
MAX_TURNS = 8

anthropic = AsyncAnthropic()

def server_params(server_script_path: str) -> StdioServerParameters:
    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]:
    return [
        
            "name": tool.name,
            "description": tool.description or "",
            "input_schema": tool.input_schema,
        
        for tool in tool_list.tools
    ]

def result_text(result) -> str:
    return "n".join(
        block.text for block in result.content if isinstance(block, TextContent)
    )

By utilizing the asynchronous variant AsyncAnthropic, the client prevents blocking the asyncio event loop while awaiting responses from the model inference endpoints, ensuring responsive input/output handling.

Routing Model Tool Calls in an Execution Loop

The core orchestration engine resides within the query processing loop. When a user submits a prompt, the client sends the conversation history alongside the translated tool definitions to the Anthropic API. The model evaluates whether external tools are required to fulfill the request. If tool invocation is requested, the client intercepts the call, executes it against the local MCP server, and feeds the resulting output back into the conversation history.

async def process_query(client: Client, tools: list[dict], query: str) -> str:
    messages = ["role": "user", "content": query]
    for _ in range(MAX_TURNS):
        response = await anthropic.messages.create(
            model=MODEL,
            max_tokens=2048,
            messages=messages,
            tools=tools,
        )

        if response.stop_reason != "tool_use":
            return "n".join(b.text for b in response.content if b.type == "text")

        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,
                
            )

        messages.append("role": "user", "content": tool_results)

    return "Stopped after reaching the turn limit."

This iterative loop is vital for handling complex queries that necessitate multi-step reasoning or sequential tool chaining—such as retrieving geographic coordinates via one tool and subsequently querying meteorological forecasts using those coordinates. Enforcing a strict turn limit (MAX_TURNS) prevents recursive execution loops in scenarios where the model encounters persistent errors.

Interactive Terminal Interface and Application Entry Point

To complete the client architecture, developers implement an interactive chat loop that maintains conversational state while interfacing with the asynchronous client runtime:

async def chat_loop(client: Client, tools: list[dict]) -> None:
    print("nType a question, or 'quit' to exit.")
    while True:
        try:
            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")

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())

Running the client via the command line interface is initiated with the following command:

uv run client.py server.py

Developers can test the system with progressive prompts designed to evaluate multi-tool chaining and error recovery:

  1. "What is the current weather in Tokyo?"
  2. "Convert that temperature to Fahrenheit."
  3. "What is the weather in Atlantis and convert it to Rankine?"

Implications and Future Outlook

The successful implementation of a Model Context Protocol client in Python underscores the viability of decentralized, modular AI tooling. By decoupling tool providers from AI host applications via standardized transport layers like stdio, developers can construct secure, localized execution environments that minimize network overhead and enhance data privacy. As enterprise adoption of generative AI accelerates, architectures adhering to the MCP standard will likely serve as the foundational bedrock for scalable, extensible agentic workflows, empowering language models to interact reliably with disparate computational resources across diverse operating environments.

Related stories

More from Artificial Intelligence and Future Tech

View all →

Most viewed across the site

GearX News
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.