iTranslated by AI
Introduction to Python MCP Server Development: Connecting LLM Applications with Context
Introduction to Python MCP Server Development
Introduction
In recent AI development, the use of Large Language Models (LLMs) has been expanding rapidly. However, to link LLMs with existing data and functions, it is necessary to develop individual integrations, which consumes significant time and resources.
This is where the Model Context Protocol (MCP) comes in. MCP is an open protocol that standardizes the integration between LLMs and external data sources or tools. In this article, we will explain how to develop an MCP server in Python, aiming to enable you to easily build powerful integrations for LLM applications.
Table of Contents
- What is Model Context Protocol (MCP)?
- MCP Architecture and Concepts
- Preparing the Development Environment
- Creating a Basic MCP Server
- Implementing Resources, Tools, and Prompts
- Practical MCP Server Examples
- Integration with Clients
- Deployment and Operation
- Summary and Next Steps
1. What is Model Context Protocol (MCP)?
Model Context Protocol (MCP) is an open protocol for seamlessly connecting AI/LLM applications with external data sources and tools. While LLMs possess excellent reasoning capabilities, dedicated integrations were required to access the latest external data or specific application functions.
MCP is often referred to as the "USB-C for AI applications," providing a standardized interface that allows various data sources and tools to connect easily with LLMs.
Key Benefits of MCP
- Standardized Interface: Once created, an MCP server can collaborate with any MCP-compatible client.
- Separation of Concerns: Decouples context provision from LLM interaction, improving modularity.
- Security: Enables safe control of access to local data.
- Reusability: Allows the creation and sharing of MCP wrappers for existing data sources or APIs.
2. MCP Architecture and Concepts
MCP consists of the following components:
Source: https://modelcontextprotocol.io/
Major Components
- MCP Host: Applications like Claude Desktop that interact with LLMs and access MCP servers.
- MCP Client: A protocol client that maintains a 1-to-1 connection with the server.
- MCP Server: A lightweight program that exposes specific functionality through a standardized protocol.
- Data Sources: Local or remote data sources that the server accesses.
Basic Concepts
The MCP protocol defines three fundamental "primitives":
- Resources: A mechanism to provide data or content to the LLM (analogous to a GET concept).
- Tools: A mechanism to provide functionality to the LLM (analogous to a POST concept).
- Prompts: Reusable templates that define interaction patterns with the LLM.
3. Preparing the Development Environment
First, let's set up the environment for developing an MCP server.
Installing Necessary Tools
You will need Python 3.8 or higher and the official MCP SDK.
# Using pip
pip install mcp
# Using uv (recommended)
uv add "mcp[cli]"
Project Structure
The project structure for an MCP server is relatively simple. It can work as a single Python file or a more complex project structure.
Below is an example of a basic project structure:
my_mcp_server/
├── server.py # Main MCP server code
├── pyproject.toml # Project configuration (optional)
└── README.md # Documentation (optional)
4. Creating a Basic MCP Server
Let's create the simplest possible MCP server. Below is an example of a basic server that provides an "echo" function.
"""
Simple Echo MCP Server
This example demonstrates a basic MCP server that exposes a simple echo tool.
"""
from mcp.server.fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("Echo Server")
# Define a tool that echoes back the input text
@mcp.tool()
def echo(text: str) -> str:
"""Echo the input text back to the caller."""
return f"Echo: {text}"
# Run the server (when the script is executed directly)
if __name__ == "__main__":
# Start the server using stdio transport by default
mcp.run()
This simple server:
- Initializes the MCP server using the
FastMCPclass - Defines a tool using the
@mcp.tool()decorator - Starts the server with
mcp.run()
.
How to Run the Server
The script you created can be executed as follows:
# Direct execution
python simple_echo_server.py
# Via MCP command line
mcp run simple_echo_server.py
# Development mode (check operation with MCP Inspector)
mcp dev simple_echo_server.py
5. Implementing Resources, Tools, and Prompts
Let's take a closer look at the three basic elements of MCP.
Implementing Resources
Resources are a mechanism for providing information to LLMs. They are similar to GET endpoints in a RESTful API.
# Define a static resource
@mcp.resource("echo://static")
def static_echo() -> str:
"""Provide a static echo message."""
return "This is a static echo message from the MCP server!"
# Define a resource with dynamic parameters
@mcp.resource("echo://{message}")
def dynamic_echo(message: str) -> str:
"""Echo the message specified in the resource URI."""
return f"Resource Echo: {message}"
Resources:
- Are defined with a URI-formatted path (
scheme://path) - Can specify dynamic parameters within the path using
{} - Return values can be text, images, embedded resources, etc.
Implementing Tools
Tools are functions for the LLM to perform some action. They are similar to POST endpoints in a RESTful API.
# Define a basic tool
@mcp.tool()
def calculate_sum(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
# Define an asynchronous tool
@mcp.tool()
async def fetch_data(url: str) -> str:
"""Fetch data from a URL."""
async with httpx.AsyncClient() as client:
# Send a GET request to the specified URL
response = await client.get(url)
return response.text
Characteristics of tools:
- Argument and return types are specified using Python type hints
- Can be implemented as asynchronous functions
- Can receive a context (
ctx: Context) for progress reporting and more
Implementing Prompts
Prompts are templates that define interaction patterns with the LLM.
# Simple prompt template
@mcp.prompt()
def echo_prompt(message: str) -> str:
"""Create a prompt that includes the provided message."""
return f"Please process this message: {message}"
# Prompt consisting of multiple messages
from mcp.types import UserMessage, AssistantMessage
@mcp.prompt()
def debug_error(error: str) -> list[Message]:
return [
UserMessage("I'm seeing this error:"),
UserMessage(error),
AssistantMessage("I'll help debug that. What have you tried so far?")
]
Characteristics of prompts:
- Can consist of simple strings or multiple messages
- Function as templates that users can select and call
6. Practical MCP Server Examples
Here are some examples of more practical MCP servers. The following is a server that can fetch the content of websites.
"""
Web Fetcher MCP Server
This example demonstrates an MCP server that can fetch and return content from websites.
"""
import httpx
from mcp.server.fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("Web Fetcher")
# Tool to fetch website content
@mcp.tool()
async def fetch_website(url: str) -> str:
"""
Fetch the content from a specified URL.
"""
# Set user agent (to avoid blocking)
headers = {
"User-Agent": "MCP Web Fetcher Example"
}
# Asynchronous HTTP request with httpx
async with httpx.AsyncClient(follow_redirects=True, headers=headers) as client:
try:
# Send GET request to the specified URL
response = await client.get(url)
# Raise an exception for error codes
response.raise_for_status()
# Return the response text
return response.text
except httpx.HTTPStatusError as e:
return f"Error: HTTP status error - {e.response.status_code}"
except httpx.RequestError as e:
return f"Error: Request failed - {str(e)}"
except Exception as e:
return f"Error: {str(e)}"
# Resource to access recently fetched sites
@mcp.resource("webhistory://last")
def last_fetch() -> str:
"""Return information about the last fetched website."""
# In a real implementation, you would track the fetch history.
# This is a simplified example.
return "No fetch history available yet."
# Run the server when the script is executed directly
if __name__ == "__main__":
# Use stdio transport by default
mcp.run()
Database Integration Example
Here is an example of an MCP server that integrates with a SQLite database:
"""
SQLite Explorer MCP Server
This example demonstrates an MCP server that provides access to a SQLite database.
"""
import sqlite3
from mcp.server.fastmcp import FastMCP, Context
# Create an MCP server
mcp = FastMCP("SQLite Explorer")
# Use an in-memory database for this sample
DB_PATH = ":memory:"
# Initialize the database with sample data
def init_database():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Create the users table
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
age INTEGER
)
""")
# Insert sample data
sample_users = [
(1, "Alice Smith", "alice@example.com", 28),
(2, "Bob Johnson", "bob@example.com", 35),
(3, "Carol Williams", "carol@example.com", 42),
]
# Use INSERT OR REPLACE to avoid duplicates
cursor.executemany("""
INSERT OR REPLACE INTO users (id, name, email, age) VALUES (?, ?, ?, ?)
""", sample_users)
conn.commit()
conn.close()
# Initialize the database
init_database()
# Resource to retrieve the database schema
@mcp.resource("schema://tables")
def get_schema() -> str:
"""Retrieve the database schema for all tables."""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Get all tables
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = cursor.fetchall()
schema = []
for table in tables:
table_name = table[0]
cursor.execute(f"PRAGMA table_info({table_name})")
columns = cursor.fetchall()
column_info = [f" {col[1]} {col[2]}" + (" PRIMARY KEY" if col[5] else "") for col in columns]
schema.append(f"Table: {table_name}\n" + "\n".join(column_info))
conn.close()
return "\n\n".join(schema)
# Tool to execute queries against the database
@mcp.tool()
def query_database(sql: str, ctx: Context) -> str:
"""
Execute an SQL query against the database.
"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
try:
# Log the query to be executed
ctx.info(f"Executing query: {sql}")
# Execute the query
cursor.execute(sql)
# Get column names
column_names = [description[0] for description in cursor.description] if cursor.description else []
# Fetch results
results = cursor.fetchall()
# Format results in table format
if not column_names or not results:
return "Query executed successfully. No results or empty result set."
# Build a simple text table
header = " | ".join(column_names)
separator = "-" * len(header)
rows = [" | ".join([str(cell) for cell in row]) for row in results]
return f"{header}\n{separator}\n" + "\n".join(rows)
except Exception as e:
return f"Error executing query: {str(e)}"
finally:
conn.close()
# Run the server when the script is executed directly
if __name__ == "__main__":
mcp.run()
7. Integration with Clients
Once you have created an MCP server, let's look at how to connect to it from a client. Below is an example of implementing an MCP client in Python.
"""
Simple MCP Client Example
This example demonstrates how to use the MCP client to connect to and interact with an MCP server.
"""
import asyncio
from mcp.client.session import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client
async def main():
# Define parameters for connecting to the server via stdio
server_params = StdioServerParameters(
command="python", # Command to run the server
args=["simple_echo_server.py"], # Script implementing the MCP server
env=None # Environment variables (None inherits from the current process)
)
# Connect to the server
async with stdio_client(server_params) as (read, write):
# Create a client session
async with ClientSession(read, write) as session:
# Initialize connection with the server
await session.initialize()
print("Successfully connected to the server!")
# List available tools
tools = await session.list_tools()
print(f"Available tools: {tools}")
# Call the echo tool
echo_result = await session.call_tool("echo", {"text": "Hello from MCP client!"})
print(f"Result from echo tool: {echo_result}")
# List available resources
resources = await session.list_resources()
print(f"Available resources: {resources}")
# Read static resource
static_content, mime_type = await session.read_resource("echo://static")
print(f"Static resource content: {static_content}")
print(f"Static resource MIME type: {mime_type}")
# Read dynamic resource
dynamic_content, mime_type = await session.read_resource("echo://Hello from resource!")
print(f"Dynamic resource content: {dynamic_content}")
print(f"Dynamic resource MIME type: {mime_type}")
# List available prompts
prompts = await session.list_prompts()
print(f"Available prompts: {prompts}")
# Get a prompt
if prompts:
prompt_name = prompts[0].name
prompt_result = await session.get_prompt(prompt_name, {"message": "Please process this message"})
print(f"Prompt result: {prompt_result}")
if __name__ == "__main__":
# Execute the asynchronous main function
asyncio.run(main())
Integration with Claude Desktop
To use an MCP server with Claude Desktop, you can install it using the MCP command-line tool:
# Install the MCP server into Claude Desktop
mcp install server.py
# Specify a custom name
mcp install server.py --name "My Analytics Server"
# Set environment variables
mcp install server.py -v API_KEY=abc123 -v DB_URL=postgres://...
mcp install server.py -f .env
After installation, your server will appear in the "Servers" section of Claude Desktop, allowing Claude AI to access your server's features.
8. Deployment and Operation
There are several ways to deploy an MCP server:
1. Local Installation
For development or personal use, the easiest way is to install it directly to Claude Desktop using the mcp install command.
2. Transport Selection
MCP supports multiple transport methods:
- stdio: The default transport. Uses standard input/output.
- SSE: An HTTP-based transport using Server-Sent Events.
Example of using the SSE transport:
if __name__ == "__main__":
import sys
# Specify the transport via command line arguments
transport = "sse" if "--sse" in sys.argv else "stdio"
port = 8000 # Default port for SSE
# Run the server with the specified transport
mcp.run(transport=transport, port=port)
3. Packaging
When sharing with multiple users, it is convenient to package the MCP server as a Python package:
# pyproject.toml
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "my-mcp-server"
version = "0.1.0"
description = "My MCP Server"
authors = [{name = "Your Name", email = "your.email@example.com"}]
dependencies = [
"mcp>=1.0.0",
"httpx>=0.24.0",
]
[project.scripts]
my-mcp-server = "my_mcp_server:main"
4. Security Considerations
Consider the following security matters when deploying an MCP server:
- Properly limit the scope of access to resources
- Implement appropriate authentication when handling sensitive information
- Properly sanitize user inputs (especially for SQL queries, etc.)
- Run the server with the minimum necessary permissions
9. Summary and Next Steps
In this article, we introduced the basic concepts of Model Context Protocol (MCP) and how to develop MCP servers in Python. By leveraging MCP, the integration between AI applications and external data sources or tools is standardized, leading to improved development efficiency.
Resources for Future Learning
- Model Context Protocol Official Documentation
- Python SDK Repository
- MCP Servers Repository - Practical server examples
MCP is a rapidly evolving technology, and more integrations and use cases are expected to emerge. We hope you use this article as a starting point to develop your own MCP servers and expand the potential of LLMs.
Discussion