什么是 MCP

MCP(Model Context Protocol)是 Anthropic 于 2024 年底推出的开放协议,旨在标准化 AI 模型与外部工具/数据源之间的通信。它定义了统一的接口规范,让任何 AI 模型都能通过标准方式访问工具、资源和提示模板。2026 年,MCP 已成为 AI Agent 开发的事实标准。

MCP 核心概念

概念说明示例
Server提供工具/资源的服务端GitHub Server、Filesystem Server
Client使用工具的 AI 宿主Claude Desktop、自定义 Agent
Tool可调用的函数能力search_code、create_issue
Resource可读取的数据源文件内容、数据库记录
Prompt预定义的提示词模板代码审查模板

构建一个 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="获取指定城市的天气信息",
            inputSchema={
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名称"}
                },
                "required": ["city"]
            }
        ),
        types.Tool(
            name="get-forecast",
            description="获取未来天气预报",
            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"]
        # 调用真实天气 API
        weather = f"{city}今天晴天,25°C"
        return [types.TextContent(type="text", text=weather)]

    elif name == "get-forecast":
        city = arguments["city"]
        days = arguments.get("days", 3)
        forecast = f"{city}未来{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 集成

# 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):
        """从 MCP Server 加载工具列表"""
        # 实际应通过 MCP 协议通信,这里简化为预定义
        return [{
            "type": "function",
            "function": {
                "name": "get-weather",
                "description": "获取城市天气",
                "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):
        # 调用 MCP Server 执行工具
        result = subprocess.run(
            ['python', self.server, name, json.dumps(args)],
            capture_output=True, text=True
        )
        return result.stdout

# 使用
client = DeepSeekMCPClient('weather_server.py')
result = client.chat_with_tools("北京今天天气怎么样?")
print(result)

配置 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"]
    }
  }
}

常用 MCP Server 推荐

Server安装命令功能
filesystemnpx -y @modelcontextprotocol/server-filesystem /path文件读写
githubnpx -y @modelcontextprotocol/server-githubGitHub 操作
postgresnpx -y @modelcontextprotocol/server-postgres数据库查询
brave-searchnpx -y @modelcontextprotocol/server-brave-search网页搜索
memorynpx -y @modelcontextprotocol/server-memory知识记忆

MCP vs Function Calling 对比

MCPFunction Calling
标准化✅ 开放协议,跨平台厂商特定实现
复用性一次构建,多模型通用需按模型适配
生态30+ 官方 Server需自行开发
复杂度需要独立 Server 进程内嵌在应用代码中

建议:对外提供通用工具时使用 MCP,应用内私有工具使用 Function Calling。