Agent Development
Beginner
Introduction to the MCP Protocol: Building Standard Interfaces for AI Tool Calls
2026-08
14 分钟阅读
#MCP协议
#工具调用
#标准接口
#Agent开发
#协议设计
What is MCP
MCP (Model Context Protocol) is an open protocol introduced by Anthropic at the end of 2024, designed to standardize communication between AI models and external tools/data sources. It defines a unified interface specification that allows any AI model to access tools, resources, and prompt templates in a standard way. By 2026, MCP has become the de facto standard for AI Agent development.
MCP Core Concepts
| Concept | Description | Example |
|---|
| Server | Server-side that provides tools/resources | GitHub Server, Filesystem Server |
| Client | AI host that uses tools | Claude Desktop, custom Agent |
| Tool | Callable function capability | search_code, create_issue |
| Resource | Readable data source | File content, database records |
| Prompt | Predefined prompt template | Code review template |
Building an MCP Server
# weather_server.py
from mcp.server import Server, NotificationOptions
from mcp.server.models import InitializationCapabilities
import mcp.server.stdio
import mcp.types as types
import json
app = Server("weather-server")
@app.list_tools()
async def handle_list_tools() -> list[types.Tool]:
return [
types.Tool(
name="get-weather",
description="Get weather information for a specified city",
inputSchema={
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
),
types.Tool(
name="get-forecast",
description="Get future weather forecast",
inputSchema={
"type": "object",
"properties": {
"city": {"type": "string"},
"days": {"type": "integer", "minimum": 1, "maximum": 7}
},
"required": ["city"]
}
)
]
@app.call_tool()
async def handle_call_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name == "get-weather":
city = arguments["city"]
# Call real weather API
weather = f"{city} is sunny today, 25°C"
return [types.TextContent(type="text", text=weather)]
elif name == "get-forecast":
city = arguments["city"]
days = arguments.get("days", 3)
forecast = f"{city} will be mostly sunny for the next {days} days"
return [types.TextContent(type="text", text=forecast)]
raise ValueError(f"Unknown tool: {name}")
async def main():
async with mcp.server.stdio.stdio_server() as (read, write):
await app.run(read, write, InitializationCapabilities())
if __name__ == "__main__":
import asyncio
asyncio.run(main())
DeepSeek + MCP Integration
# deepseek_mcp_client.py
from openai import OpenAI
import subprocess
import json
import os
class DeepSeekMCPClient:
def __init__(self, server_script):
self.client = OpenAI(
api_key=os.getenv('DEEPSEEK_API_KEY'),
base_url='https://api.deepseek.com'
)
self.server = server_script
self.tools = self._load_tools()
def _load_tools(self):
"""Load tool list from MCP Server"""
# In practice, should communicate via MCP protocol; simplified here as predefined
return [{
"type": "function",
"function": {
"name": "get-weather",
"description": "Get city weather",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
}]
def chat_with_tools(self, user_message):
messages = [{"role": "user", "content": user_message}]
response = self.client.chat.completions.create(
model='deepseek-v4-flash',
messages=messages,
tools=self.tools,
tool_choice='auto'
)
msg = response.choices[0].message
if msg.tool_calls:
for tc in msg.tool_calls:
result = self._execute_tool(tc.function.name, json.loads(tc.function.arguments))
messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})
final = self.client.chat.completions.create(
model='deepseek-v4-flash',
messages=messages
)
return final.choices[0].message.content
return msg.content
def _execute_tool(self, name, args):
# Call MCP Server to execute tool
result = subprocess.run(
['python', self.server, name, json.dumps(args)],
capture_output=True, text=True
)
return result.stdout
# Usage
client = DeepSeekMCPClient('weather_server.py')
result = client.chat_with_tools("What's the weather in Beijing today?")
print(result)
Configuring Claude Desktop MCP
// ~/Library/Application Support/Claude/claude_desktop_config.json (macOS)
// %APPDATA%\Claude\claude_desktop_config.json (Windows)
{
"mcpServers": {
"deepseek-tools": {
"command": "python",
"args": ["/path/to/weather_server.py"]
}
}
}
Recommended Common MCP Servers
| Server | Installation Command | Function |
|---|
| filesystem | npx -y @modelcontextprotocol/server-filesystem /path | File read/write |
| github | npx -y @modelcontextprotocol/server-github | GitHub operations |
| postgres | npx -y @modelcontextprotocol/server-postgres | Database queries |
| brave-search | npx -y @modelcontextprotocol/server-brave-search | Web search |
| memory | npx -y @modelcontextprotocol/server-memory | Knowledge memory |
MCP vs Function Calling Comparison
| MCP | Function Calling |
|---|
| Standardization | ✅ Open protocol, cross-platform | Vendor-specific implementation |
| Reusability | Build once, works with multiple models | Needs adaptation per model |
| Ecosystem | 30+ official Servers | Need to develop yourself |
| Complexity | Requires separate Server process | Embedded in application code |
Recommendation: Use MCP for providing general-purpose tools externally, and Function Calling for private tools within the application.