Creating an MCP Client in Python from Scratch

Overview of the MCP Client in Python

This article covers the development of an MCP (Model Context Protocol) client in Python using the official MCP Python SDK 2.0. The client connects to a local server through stdio, facilitating interactions with designated tools.

Core Functionality

The MCP client serves multiple roles as part of its architecture:

  • It connects to a server that exposes tools and resources.
  • It queries the server for available tools and invokes them as required by an AI model.
  • The model interacts indirectly with the server through the client, ensuring a streamlined translation of commands.

Prerequisites

To build the MCP Client, you will need the following:

  • Python version 3.10 or higher
  • The uv package manager
  • An active Anthropic API key
  • The MCP Python SDK version 2.0.0 or newer

Installation of the SDK can be accomplished using pip install mcp in your command line.

Project Setup

To create the project, use the following commands:

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

This setup equips you with the necessary environment for both the client and server components.

Building the Test Server

The server component is defined in server.py and provides two tools for interaction:

import logging
from mcp.server import MCPServer
# additional imports...

mcp = MCPServer("weather-tools")

@mcp.tool()
async def get_weather(city: str) -> str:
    # Implementation to fetch and return weather...
   
@mcp.tool()
def convert_temperature(value: float, from_unit: str, to_unit: str) -> str:
    # Implementation to convert temperature...
   
if __name__ == "__main__":
    mcp.run(transport="stdio")

This server operates via standard input and output, responding to requests for weather data and temperature conversion.

Connecting and Listing Tools

To verify the connection with the server, you can create explore.py:

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

async def main():
    params = StdioServerParameters(command=sys.executable, args=["server.py"])
    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}")

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

Calling Tools Directly

This allows manual invocation of server tools without the model’s involvement:

async def main():
    # existing code...
    ok = await client.call_tool("convert_temperature", {"value": 30, "from_unit": "celsius", "to_unit": "fahrenheit"})
    # additional calls...

Conclusion

This guide illustrates the construction of an MCP client capable of connecting to a server, listing its tools, and executing tool calls. The implementation of JSON-RPC messages assists in the interaction process, ensuring a structured approach to requests and responses.

Source: machinelearningmastery.com

Related Articles

Recent advancements in artificial intelligence (AI) have reached a significant milestone, as researchers reported solving the Riemann hypothesis, long considered...
During Dubai Future Week, two startups, Xpanceo and Grapheal, showcased innovative advancements in wearable health technology, presenting a potential future...
LlamaIndex has introduced OCRia-nano-1, the smallest model in its OCRia family, featuring 8.1 million parameters. This model offers a CPU-based...