MCP(Model Context Protocol)是一种模型上下文协议,旨在通过本地运行的MCP服务器扩展系统的能力。MCP服务器提供额外的工具和资源,使系统能够更有效地完成任务。MCP的核心思想是通过非交互式环境中的服务器,提供动态的操作和数据处理能力。
MCP服务器通过标准输入输出(stdio)与系统进行通信,采用基于JSON的协议格式。通信过程遵循请求-响应模式,系统发送请求到MCP服务器,服务器处理请求并返回响应。
MCP采用基于JSON的轻量级通信协议,通过标准输入输出(stdio)进行数据传输。整个通信过程类似于客户-服务器模式,但更加轻量和高效。
系统发送JSON格式的请求,包含以下关键信息:
示例请求:
{
"type": "CallTool",
"id": "12345",
"name": "get_forecast",
"arguments": {
"city": "Beijing",
"days": 3
}
}
服务器处理请求后,返回JSON格式的响应,包含:
成功响应示例:
{
"id": "12345",
"status": "success",
"result": {
"forecast": [
{
"date": "2025-05-12",
"temperature": 22,
"condition": "sunny"
},
{
"date": "2025-05-13",
"temperature": 20,
"condition": "cloudy"
}
]
}
}
错误响应示例:
{
"id": "12345",
"status": "error",
"code": "INVALID_PARAM",
"message": "City parameter is required"
}
场景1:获取天气信息
场景2:执行数据分析
资源是MCP服务器提供的数据实体,分为两种类型:
weather://San Francisco/current
weather://{city}/current
资源处理流程:
工具是MCP服务器提供的可执行功能,具有以下特点:
工具调用流程:
工具参数通过JSON Schema定义,支持以下特性:
MCP服务器的架构包括以下几个关键组件:
创建MCP服务器的基本步骤包括:
mkdir mcp-server
cd mcp-server
python -m venv venv
source venv/bin/activate
pip install fastapi uvicorn pydantic
touch main.py
mkdir resources
mkdir tools
在main.py
中定义资源和工具的处理逻辑,示例:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# 资源示例
@app.get("/resources")
async def list_resources():
return {
"resources": [{
"uri": "example://resource1",
"name": "Example Resource",
"mimeType": "application/json"
}]
}
# 工具示例
class ToolRequest(BaseModel):
param1: str
param2: int
@app.post("/tools/example-tool")
async def example_tool(request: ToolRequest):
return {
"result": f"Processed {request.param1} with {request.param2}"
}
uvicorn main:app --reload
在MCP设置文件中添加服务器配置:
{
"mcpServers": {
"python-example": {
"command": "uvicorn",
"args": ["main:app", "--host", "0.0.0.0", "--port", "8000"],
"env": {
"PYTHONPATH": "."
}
}
}
}
使用curl或Postman测试API:
curl -X GET http://localhost:8000/resources
curl -X POST http://localhost:8000/tools/example-tool -H "Content-Type: application/json" -d '{"param1": "test", "param2": 123}'
以下是一个简单的MCP服务器示例,提供天气数据功能:
pip install fastapi uvicorn requests pydantic
from fastapi import FastAPI
from pydantic import BaseModel
import requests
import os
import uvicorn
app = FastAPI()
class WeatherRequest(BaseModel):
city: str
days: int = 3
class WeatherServer:
def __init__(self):
self.api_key = os.getenv('OPENWEATHER_API_KEY')
self.base_url = "http://api.openweathermap.org/data/2.5"
self.setup_routes()
def setup_routes(self):
@app.get("/resources")
async def list_resources():
return {
"resources": [{
"uri": "weather://San Francisco/current",
"name": "Current weather in San Francisco",
"mimeType": "application/json"
}]
}
@app.get("/resource-templates")
async def list_resource_templates():
return {
"resourceTemplates": [{
"uriTemplate": "weather://{city}/current",
"name": "Current weather for a given city",
"mimeType": "application/json"
}]
}
@app.get("/weather/{city}")
async def get_weather(city: str):
response = requests.get(
f"{self.base_url}/weather",
params={
"q": city,
"appid": self.api_key,
"units": "metric"
}
)
return response.json()
@app.post("/forecast")
async def get_forecast(request: WeatherRequest):
response = requests.get(
f"{self.base_url}/forecast",
params={
"q": request.city,
"cnt": request.days * 8,
"appid": self.api_key,
"units": "metric"
}
)
return response.json()
if __name__ == "__main__":
server = WeatherServer()
uvicorn.run(app, host="0.0.0.0", port=8000)
MCP通过本地服务器扩展系统的能力,提供资源和工具的动态操作功能。通过定义资源和工具,MCP服务器能够与外部系统交互,执行复杂的任务。创建MCP服务器的过程包括初始化项目、定义处理逻辑、编译运行和配置设置文件。