Back to Blog

Build an MCP Server in Python: Claude Tool Guide

Tutorials and Guides8160
Build an MCP Server in Python: Claude Tool Guide

Introduction

The Model Context Protocol, or MCP, is an open standard released by Anthropic in late 2024. It has quickly become one of the most important protocols for connecting large language models with external tools, data sources, and business systems.

MCP is built on the JSON-RPC 2.0 communication specification. Its main goal is simple: provide a unified way for AI clients to call external services. With MCP, developers no longer need to build separate adapters for every AI platform. Once a service exposes standard MCP interfaces, clients such as Claude Desktop, Claude Code, and Cursor can discover and use it more easily.

By April 2026, the MCP Python SDK had exceeded 164 million monthly downloads on PyPI. Public service directories had also collected more than 20,000 independent MCP servers. Major AI companies, including OpenAI and Google, have adopted the protocol, which further strengthens MCP’s role as a common standard for AI tool integration.

This guide explains how to build an MCP Server from scratch with Python and connect it to Claude clients. It covers protocol concepts, environment setup, server implementation, Claude Desktop configuration, Claude Code integration, deployment modes, production best practices, and troubleshooting.

The tutorial is designed for developers who want to extend Claude with custom tools, internal APIs, databases, or business workflows.

1. MCP Core Concepts and Basic Architecture

Before writing code, it is important to understand the three core roles in the MCP architecture.

MCP uses a three-layer structure based on JSON-RPC 2.0. Each layer has a clear responsibility.

RoleCore ResponsibilityTypical Example
MCP HostThe main AI client that initiates tool callsClaude Desktop, Claude Code, Cursor
MCP ClientThe protocol component inside the Host that parses and forwards requestsNative MCP component in Claude clients
MCP ServerThe backend service that exposes tools, data, and promptsCustom Python services

An MCP Server can expose three types of capabilities to AI clients.

Tools

Tools are executable functions. They can perform actions such as database queries, HTTP requests, file operations, system checks, or business workflow execution.

Resources

Resources are readable data sources. They can include file content, API responses, database schemas, logs, documents, or structured business data.

Prompts

Prompts are reusable prompt templates. They help standardize task instructions and reduce inconsistent model behavior across repeated workflows.

According to research data released by Bloomberry Research in 2026, the median number of tools deployed on a single public MCP Server is 5. This is a useful reference. Too many tools can make it harder for the model to choose the right one. In practical development, tools should be concise, clear, and task-focused.

A good MCP Server does not expose every internal function. It exposes the functions that the AI client truly needs.

2. Step One: Environment Setup and SDK Installation

The MCP Python SDK requires Python 3.10 or above. This tutorial provides two installation options.

The first option uses uv, which is recommended for macOS and Linux users. The second option uses traditional pip, which works across Windows, macOS, and Linux.

The uv tool has a cold start speed about 10 times faster than pip, so it can improve setup and dependency management efficiency.

2.1 Install with uv

Run the following commands in your terminal:

bash
# Install the uv tool
curl -LsSf https://astral.sh/uv/install.sh | sh

# Create a new project and initialize the virtual environment
uv init my-mcp-server
cd my-mcp-server

# Install MCP CLI and related dependencies
uv add "mcp[cli]"

This creates a new project directory and installs the MCP command-line tools.

2.2 Install with pip

This method is suitable for Windows, macOS, and Linux.

bash
# Create a virtual environment
python -m venv .venv

# Activate the virtual environment
# macOS / Linux
source .venv/bin/activate

# Windows
.venv\Scripts\activate

# Install MCP and HTTP request dependencies
pip install "mcp[cli]" httpx

Using a virtual environment is strongly recommended. It avoids dependency conflicts with other Python projects.

2.3 Verify the Installation

After installation, run:

bash
mcp version

A normal output should look like this:

bash
mcp 1.x.x

If the version number appears, the environment is ready.

3. Step Two: Write Your First MCP Server

In this tutorial, we will build a simple weather query MCP Server. It will expose two tools:

text
get_weather
get_forecast

Create a file named server.py in your project directory.

The @mcp.tool() decorator is the core feature of the FastMCP framework. It registers a Python function as an MCP tool.

One important detail deserves attention: the function docstring will be read by the AI model. It helps the model understand what the tool does, what parameters it needs, and what result it returns.

In MCP development, clear docstrings are more important than ordinary code comments.

3.1 Complete Server Code

python
from mcp.server.fastmcp import FastMCP

# Initialize the MCP server and set a recognizable service name
mcp = FastMCP("weather-assistant")

@mcp.tool()
def get_weather(city: str) -> str:
    """
    Query the real-time weather of the specified city.

    Args:
        city: Name of the city, supporting Chinese characters such as Beijing and Shanghai.

    Returns:
        A string containing temperature and weather conditions.
    """
    # Replace with a real weather API in production projects
    return f"{city}: Sunny, temperature 28°C, humidity 55%"

@mcp.tool()
def get_forecast(city: str, days: int = 3) -> dict:
    """
    Get the weather forecast for the next several days.

    Args:
        city: Name of the city.
        days: Number of forecast days. The default value is 3.

    Returns:
        A dictionary containing multi-day forecast information.
    """
    forecast_list = [f"Day {i+1}: Cloudy, 22-29°C" for i in range(days)]
    return {
        "city": city,
        "forecast": forecast_list
    }

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

This server is intentionally simple. In a production project, get_weather and get_forecast can call real APIs, internal databases, or enterprise services.

3.2 Debug with MCP Inspector

MCP provides a built-in debugging tool called MCP Inspector. It allows developers to test tools in a browser before connecting them to Claude.

Run:

bash
fastmcp dev server.py

Then open:

text
http://localhost:5173

In the Inspector interface, you can manually enter parameters and test each tool’s input and output.

This is useful for early development. It helps verify tool behavior before the MCP Server is connected to a real AI client.

4. Step Three: Connect the MCP Server to Claude Desktop

Claude Desktop discovers local MCP services by reading a fixed JSON configuration file. The file path is different on each operating system.

4.1 Locate the Configuration File

For macOS:

text
~/Library/Application Support/Claude/claude_desktop_config.json

For Windows:

text
%APPDATA%\Claude\claude_desktop_config.json

If the file does not exist, create it manually.

4.2 Write the Configuration

Add your MCP Server information to the configuration file.

Replace the example path with the absolute path of your local server.py.

json
{
  "mcpServers": {
    "weather-assistant": {
      "command": "python",
      "args": ["/Users/yourname/my-mcp-server/server.py"],
      "env": {
        "WEATHER_API_KEY": "your_api_key_here"
      }
    }
  }
}

The command field defines how Claude starts the server. The args field passes the server file path. The env field injects environment variables such as API keys.

Do not hard-code sensitive credentials directly into Python source code. Use environment variables instead.

4.3 Verify the Connection

After saving the configuration, restart Claude Desktop.

Then enter a natural language request such as:

text
Check today's weather in Beijing.

Claude should identify the get_weather tool and call it automatically.

On macOS, you can check the MCP log with:

bash
tail -f ~/Library/Logs/Claude/mcp.log

The log file is helpful for diagnosing connection failures, invalid paths, syntax errors, and runtime exceptions.

5. Step Four: Connect the MCP Server to Claude Code

Claude Code uses command-line commands to register and manage MCP services. This is more suitable for developers who work in terminal environments.

5.1 Register the MCP Server

Use the following command to add a local stdio-mode MCP Server:

bash
claude mcp add weather-assistant -- python /path/to/server.py

View all registered MCP servers:

bash
claude mcp list

Check a specific server:

bash
claude mcp get weather-assistant

These commands make MCP service management more direct. Developers do not need to manually edit Claude Desktop’s JSON configuration when working inside Claude Code.

5.2 Test the Tool in Claude Code

After successful registration, start Claude Code in your project directory.

Then enter:

text
Query the weather forecast of Shanghai and return the result in JSON format.

Claude Code should match the get_forecast tool and return structured forecast data.

This shows how MCP turns natural language instructions into real tool calls.

6. Step Five: Choose a Deployment Mode

MCP supports two main deployment modes:

text
stdio
streamable HTTP

Each mode fits different usage scenarios.

DimensionStdio Local ProcessStreamable HTTP Remote Service
Best ForPersonal local development and standalone toolsTeam sharing and production deployment
Startup ModeHost client creates a child processHTTP service runs independently
Configuration DifficultyLowMedium
Multi-User SupportNot supportedSupported
SecurityProcess isolation by defaultRequires authentication, usually Bearer Token

6.1 Stdio Mode

Stdio mode is the simplest deployment method. The AI client starts the MCP Server as a child process and communicates through standard input and output.

It is ideal for:

text
local development
personal tools
quick prototypes
single-user automation

Its main limitation is that it does not support multi-user sharing.

6.2 Streamable HTTP Mode

Streamable HTTP mode runs the MCP Server as an independent HTTP service. It is better suited for teams and production environments.

Modify the main function in server.py:

python
if __name__ == "__main__":
    # Start Streamable HTTP service for team sharing
    mcp.run(transport="streamable-http", host="0.0.0.0", port=8000)

Team members can connect to the remote MCP service through a URL.

Example configuration:

json
{
  "mcpServers": {
    "weather-assistant": {
      "url": "http://your-server-ip:8000/mcp"
    }
  }
}

For teams that need to connect multiple AI services or manage model access costs, 4sapi can be used as a supplementary API access layer. It helps teams integrate different model services with lower operational complexity.

7. Production Deployment Best Practices

According to Workato statistics in 2026, after MCP tools were introduced, Claude product usage increased by 700%. Higher invocation volume creates higher requirements for reliability, security, and permission control.

Production MCP services should follow three basic rules.

7.1 Read First, Then Write

When launching a new MCP tool, start with read-only operations.

For the first week, only expose query functions. After observing stable model behavior, gradually enable write, update, or delete operations.

This reduces the risk of accidental data changes.

Examples of safer first-stage tools include:

text
read database records
query order status
retrieve log files
summarize documents
inspect configuration

More sensitive actions should be opened later:

text
update database rows
delete records
send emails
modify files
trigger deployments

7.2 Manage Credentials with Environment Variables

All API keys and sensitive credentials should be injected through environment variables.

Avoid writing secrets directly into source code.

Example:

json
{
  "env": {
    "WEATHER_API_KEY": "your_api_key_here",
    "DB_TOKEN": "your_database_token"
  }
}

This makes the service safer and easier to deploy across different environments.

7.3 Add Timeout Protection

Every tool that calls an external API or database should have a timeout.

Without timeout protection, a slow third-party service may block the entire MCP Server.

Reference code:

python
import httpx

@mcp.tool()
async def query_database(sql: str) -> list:
    """Execute read-only SQL queries."""
    # Prohibit write operations such as insertion, update, and deletion
    forbidden_ops = ["INSERT", "UPDATE", "DELETE", "DROP"]
    if any(op in sql.upper() for op in forbidden_ops):
        return {"error": "Only SELECT queries are allowed"}

    # Set 10-second timeout to avoid service blocking
    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.post(DB_ENDPOINT, json={"sql": sql})
        return resp.json()

This example also includes a basic SQL safety check. It blocks write operations and only allows read-only queries.

8. Common Errors and Troubleshooting

8.1 ModuleNotFoundError: No module named 'mcp'

This usually means the Python virtual environment is not activated, or the MCP SDK was not installed correctly.

Check the current Python path:

bash
which python

Reinstall dependencies:

bash
pip install "mcp[cli]"

On Windows, use:

bash
where python

Make sure Claude is using the same Python environment where MCP is installed.

8.2 Claude Desktop Cannot Detect the MCP Server

Common causes include:

text
wrong file path
invalid JSON syntax
extra comma in the config file
incorrect Windows backslash escaping
missing Python executable

Check JSON validity:

bash
python3 -c "import json; json.load(open('$HOME/Library/Application Support/Claude/claude_desktop_config.json'))"

View recent logs:

bash
tail -20 ~/Library/Logs/Claude/mcp.log

On Windows, pay special attention to path escaping. You may need to use double backslashes or forward slashes.

8.3 MCP Inspector Works, but Claude Cannot Call Tools

This often happens when the tool docstring is incomplete or ambiguous.

The model depends on tool descriptions to decide when and how to call a tool. If the docstring is too vague, Claude may ignore the tool or call it incorrectly.

A good docstring should clearly explain:

text
what the tool does
when the tool should be used
what each parameter means
what format the tool returns

For MCP tools, docstrings are part of the interface design.

8.4 HTTP Mode Encounters Cross-Origin or HTTPS Issues

When testing HTTP mode locally, cross-origin or insecure connection problems may occur.

A simple solution is to use ngrok to create an HTTPS tunnel:

bash
ngrok http 8000

Then replace the MCP URL with the generated HTTPS address.

This is useful for temporary testing, demos, and remote debugging.

For production use, deploy the service behind a proper HTTPS domain and add authentication.

9. Frequently Asked Questions

9.1 What Is the Difference Between an MCP Server and a REST API?

A REST API is a general-purpose interface for software systems.

An MCP Server is designed for AI clients. It provides structured metadata, tool descriptions, and invocation rules that large language models can understand more easily.

With MCP, the model can infer when to call a tool and what parameters to pass. With a normal REST API, developers usually need extra prompt engineering and custom adapters.

9.2 Which Clients Support MCP?

As of June 2026, MCP support is available in several mainstream AI products and developer tools, including:

text
Claude Desktop
Claude Code
Cursor
Cline
GitHub Copilot Agent in VS Code
OpenAI Agents SDK
LangChain

The original article also notes that the Linux Foundation maintains the MCP specification and that OpenAI and Google have officially adopted the protocol.

9.3 Can One MCP Server Connect to Multiple AI Clients?

Yes, but the deployment mode matters.

Stdio mode is usually designed for single-client local access.

Streamable HTTP mode can support multiple clients at the same time, making it more suitable for team collaboration and shared services.

9.4 Can an MCP Server Call Other LLM APIs Internally?

Yes. This is a common pattern for building Agent-to-Agent workflows.

For example, an MCP tool can receive a request from Claude, call another model internally, process the result, and return structured output to the client.

However, credentials should always be injected through environment variables. Do not write API keys directly into the code.

Conclusion

The Model Context Protocol provides a unified bridge between AI clients and external resources. It allows developers to connect Claude and other AI applications with tools, APIs, databases, documents, and business systems through a standard interface.

This tutorial demonstrated a complete five-step workflow using Python and FastMCP:

text
set up the environment
write the MCP Server
connect to Claude Desktop
connect to Claude Code
choose the right deployment mode

For personal development, stdio mode is simple and efficient. For team collaboration and production services, Streamable HTTP is the better choice.

Production deployment requires careful design. Developers should start with read-only tools, manage credentials through environment variables, add timeout protection, and monitor logs regularly.

As the MCP ecosystem continues to grow, more third-party services, hosting platforms, and AI clients will support this protocol. Mastering MCP Server development will help developers extend Claude’s tool capabilities and build more intelligent AI workflows.

For developers working with Claude Desktop, Claude Code, Cursor, or other AI coding tools, MCP is becoming a practical foundation for the next generation of AI-native application development.

Tags:MCP ServerPythonClaude CodeFastMCPAI Agent

Recommended reading

Explore more frontier insights and industry know-how.