CSDN 2026年7月热榜:MCP(Model Context Protocol)已成为AI Agent工具调用的事实标准。Chrome DevTools MCP 41K+ Stars,Claude Code通过MCP连接11000+工具,从浏览器自动化到数据库操作,从Git管理到云服务编排,MCP让Agent真正"动手做事"。本文深度解析MCP协议原理、工具开发、生态集成与生产实战。

1. MCP协议2026生态爆发

1.1 什么是MCP

MCP (Model Context Protocol) 协议定义:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

定位: AI Agent与外部工具的标准通信协议
类比: AI时代的"USB接口"——即插即用

核心概念:
┌─────────────────────────────────────────┐
│           MCP Host (Claude Code等)       │
├─────────────────────────────────────────┤
│         MCP Client (协议客户端)          │
└─────────────────────────────────────────┘
         ↕ JSON-RPC 2.0
┌─────────────────────────────────────────┐
│         MCP Server (工具服务端)          │
├─────────────────────────────────────────┤
│  Resources | Tools | Prompts            │
└─────────────────────────────────────────┘

三大核心能力:
1. Resources: 静态资源访问(文件、数据库记录)
2. Tools: 动态工具调用(函数、API)
3. Prompts: 预定义提示词模板

设计原则:
✅ 简单:JSON-RPC 2.0,易于实现
✅ 开放:开源协议,社区驱动
✅ 安全:权限控制,沙箱隔离
✅ 可扩展:支持自定义工具
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1.2 MCP生态现状

2026年MCP生态数据:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

工具数量: 11000+ MCP Servers

热门MCP工具 (GitHub Stars):
┌─────────────────────────────────────────┐
│ 1. Chrome DevTools MCP     41K+ ⭐      │
│    浏览器自动化、截图、调试              │
├─────────────────────────────────────────┤
│ 2. PostgreSQL MCP          28K+ ⭐      │
│    数据库查询、Schema管理                │
├─────────────────────────────────────────┤
│ 3. GitHub MCP              24K+ ⭐      │
│    仓库操作、Issue、PR管理               │
├─────────────────────────────────────────┤
│ 4. Filesystem MCP          19K+ ⭐      │
│    文件读写、目录操作                    │
├─────────────────────────────────────────┤
│ 5. Slack MCP               16K+ ⭐      │
│    消息发送、频道管理                    │
└─────────────────────────────────────────┘

市场平台:
• ClawHub.ai: OpenClaw官方技能市场
• Skills.sh: Vercel精品目录
• SkillsMP.com: 40万+技能聚合

发展趋势:
→ 企业内部MCP工具快速增长
→ 行业垂直MCP(医疗、金融、法律)
→ 安全合规MCP需求激增
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

2. MCP协议深度解析

2.1 协议架构

MCP协议架构:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

┌────────────────────────────────────────────────────┐
│                   MCP Host Layer                   │
│  Claude Code | Cursor | Trae | 自定义Agent         │
└────────────────────┬───────────────────────────────┘
                     │
┌────────────────────▼───────────────────────────────┐
│                MCP Client Layer                    │
│  • 协议握手 (Initialize)                           │
│  • 能力协商 (Capabilities)                         │
│  • 消息路由 (Request/Response/Notification)       │
└────────────────────┬───────────────────────────────┘
                     │ JSON-RPC 2.0 over stdio/SSE
┌────────────────────▼───────────────────────────────┐
│                MCP Server Layer                    │
│  ┌──────────────┬──────────────┬──────────────┐   │
│  │  Resources   │    Tools     │   Prompts    │   │
│  │  list/read   │  list/call   │  list/get    │   │
│  └──────────────┴──────────────┴──────────────┘   │
└────────────────────┬───────────────────────────────┘
                     │
┌────────────────────▼───────────────────────────────┐
│              External Systems Layer                │
│  Browser | Database | Git | Cloud | API           │
└────────────────────────────────────────────────────┘

通信模式:
• stdio: 进程间通信,本地工具
• SSE (Server-Sent Events): HTTP长连接,远程工具
• WebSocket: 双向通信,实时交互
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

2.2 协议消息格式

# MCP协议消息格式定义

"""
MCP使用JSON-RPC 2.0协议
所有消息都是JSON格式
"""

# 1. 初始化请求
INITIALIZE_REQUEST = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
        "protocolVersion": "2024-11-05",
        "capabilities": {
            "roots": {"listChanged": True},
            "sampling": {}
        },
        "clientInfo": {
            "name": "claude-code",
            "version": "1.0.0"
        }
    }
}

# 2. 初始化响应
INITIALIZE_RESPONSE = {
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
        "protocolVersion": "2024-11-05",
        "capabilities": {
            "resources": {"subscribe": True, "listChanged": True},
            "tools": {},
            "prompts": {}
        },
        "serverInfo": {
            "name": "filesystem-mcp",
            "version": "1.0.0"
        }
    }
}

# 3. 列出工具请求
LIST_TOOLS_REQUEST = {
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/list",
    "params": {}
}

# 4. 工具列表响应
LIST_TOOLS_RESPONSE = {
    "jsonrpc": "2.0",
    "id": 2,
    "result": {
        "tools": [
            {
                "name": "read_file",
                "description": "Read the contents of a file",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "File path to read"
                        }
                    },
                    "required": ["path"]
                }
            },
            {
                "name": "write_file",
                "description": "Write content to a file",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {"type": "string"},
                        "content": {"type": "string"}
                    },
                    "required": ["path", "content"]
                }
            }
        ]
    }
}

# 5. 调用工具请求
CALL_TOOL_REQUEST = {
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
        "name": "read_file",
        "arguments": {
            "path": "/home/user/project/main.py"
        }
    }
}

# 6. 工具调用响应
CALL_TOOL_RESPONSE = {
    "jsonrpc": "2.0",
    "id": 3,
    "result": {
        "content": [
            {
                "type": "text",
                "text": "# main.py\nprint('Hello, MCP!')"
            }
        ]
    }
}

# 7. 通知消息 (Notification)
RESOURCE_UPDATED_NOTIFICATION = {
    "jsonrpc": "2.0",
    "method": "notifications/resources/updated",
    "params": {
        "uri": "file:///home/user/project/main.py"
    }
}

3. 开发自定义MCP工具

3.1 Python MCP Server开发

# 使用官方Python SDK开发MCP Server

"""
安装: pip install mcp
文档: https://modelcontextprotocol.io
"""

from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import asyncio
import json

# 创建MCP Server
server = Server("my-custom-mcp")

# ===== 1. 定义工具 =====

@server.list_tools()
async def list_tools():
    """列出所有可用工具"""
    return [
        Tool(
            name="query_database",
            description="Execute SQL query on PostgreSQL database",
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "SQL query to execute"
                    },
                    "database": {
                        "type": "string",
                        "description": "Database name",
                        "default": "production"
                    }
                },
                "required": ["query"]
            }
        ),
        Tool(
            name="analyze_logs",
            description="Analyze application logs for errors",
            inputSchema={
                "type": "object",
                "properties": {
                    "log_path": {
                        "type": "string",
                        "description": "Path to log file or directory"
                    },
                    "pattern": {
                        "type": "string",
                        "description": "Regex pattern to search",
                        "default": "ERROR|WARN"
                    },
                    "hours": {
                        "type": "integer",
                        "description": "Hours to look back",
                        "default": 24
                    }
                },
                "required": ["log_path"]
            }
        ),
        Tool(
            name="deploy_service",
            description="Deploy a service to Kubernetes",
            inputSchema={
                "type": "object",
                "properties": {
                    "service_name": {"type": "string"},
                    "image": {"type": "string"},
                    "namespace": {"type": "string", "default": "default"},
                    "replicas": {"type": "integer", "default": 3}
                },
                "required": ["service_name", "image"]
            }
        )
    ]


# ===== 2. 实现工具调用 =====

@server.call_tool()
async def call_tool(name: str, arguments: dict):
    """执行工具调用"""
    
    if name == "query_database":
        result = await execute_query(
            query=arguments["query"],
            database=arguments.get("database", "production")
        )
        return [TextContent(
            type="text",
            text=json.dumps(result, indent=2)
        )]
    
    elif name == "analyze_logs":
        result = await analyze_logs(
            log_path=arguments["log_path"],
            pattern=arguments.get("pattern", "ERROR|WARN"),
            hours=arguments.get("hours", 24)
        )
        return [TextContent(
            type="text",
            text=result
        )]
    
    elif name == "deploy_service":
        result = await deploy_to_k8s(
            service_name=arguments["service_name"],
            image=arguments["image"],
            namespace=arguments.get("namespace", "default"),
            replicas=arguments.get("replicas", 3)
        )
        return [TextContent(
            type="text",
            text=f"Deployed {result['service']} to {result['namespace']}"
        )]
    
    else:
        raise ValueError(f"Unknown tool: {name}")


# ===== 3. 工具实现 =====

async def execute_query(query: str, database: str) -> dict:
    """执行SQL查询"""
    import asyncpg
    
    conn = await asyncpg.connect(
        host="localhost",
        database=database,
        user="postgres",
        password="password"
    )
    
    try:
        rows = await conn.fetch(query)
        return {
            "success": True,
            "row_count": len(rows),
            "data": [dict(r) for r in rows]
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }
    finally:
        await conn.close()


async def analyze_logs(log_path: str, pattern: str, hours: int) -> str:
    """分析日志文件"""
    import re
    from datetime import datetime, timedelta
    from pathlib import Path
    
    results = []
    cutoff_time = datetime.now() - timedelta(hours=hours)
    
    regex = re.compile(pattern, re.IGNORECASE)
    
    for log_file in Path(log_path).rglob("*.log"):
        with open(log_file, 'r') as f:
            for line in f:
                if regex.search(line):
                    # 提取时间戳(假设格式:2026-07-01 10:30:45)
                    try:
                        timestamp_str = line[:19]
                        timestamp = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")
                        
                        if timestamp >= cutoff_time:
                            results.append({
                                "file": str(log_file),
                                "line": line.strip(),
                                "timestamp": timestamp_str
                            })
                    except:
                        pass
    
    # 统计分析
    summary = {
        "total_matches": len(results),
        "files_affected": len(set(r["file"] for r in results)),
        "by_hour": {}
    }
    
    for r in results:
        hour = r["timestamp"][:13]
        summary["by_hour"][hour] = summary["by_hour"].get(hour, 0) + 1
    
    return json.dumps({
        "summary": summary,
        "sample_matches": results[:10]  # 返回前10条
    }, indent=2)


async def deploy_to_k8s(service_name: str, image: str, 
                       namespace: str, replicas: int) -> dict:
    """部署到Kubernetes"""
    from kubernetes import client, config
    
    config.load_kube_config()
    apps_v1 = client.AppsV1Api()
    
    deployment = client.V1Deployment(
        metadata=client.V1ObjectMeta(name=service_name),
        spec=client.V1DeploymentSpec(
            replicas=replicas,
            selector=client.V1LabelSelector(
                match_labels={"app": service_name}
            ),
            template=client.V1PodTemplateSpec(
                metadata=client.V1ObjectMeta(
                    labels={"app": service_name}
                ),
                spec=client.V1PodSpec(
                    containers=[
                        client.V1Container(
                            name=service_name,
                            image=image,
                            ports=[client.V1ContainerPort(container_port=80)]
                        )
                    ]
                )
            )
        )
    )
    
    try:
        apps_v1.create_namespaced_deployment(
            namespace=namespace,
            body=deployment
        )
        return {
            "success": True,
            "service": service_name,
            "namespace": namespace,
            "replicas": replicas
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }


# ===== 4. 启动服务器 =====

async def main():
    async with stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            server.create_initialization_options()
        )

if __name__ == "__main__":
    asyncio.run(main())

3.2 TypeScript MCP Server开发

// 使用官方TypeScript SDK开发MCP Server

/*
安装: npm install @modelcontextprotocol/sdk
文档: https://modelcontextprotocol.io
*/

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";

// 创建MCP Server
const server = new Server(
  {
    name: "github-mcp",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// ===== 1. 定义工具 =====

server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "create_issue",
        description: "Create a GitHub issue",
        inputSchema: {
          type: "object",
          properties: {
            owner: {
              type: "string",
              description: "Repository owner",
            },
            repo: {
              type: "string",
              description: "Repository name",
            },
            title: {
              type: "string",
              description: "Issue title",
            },
            body: {
              type: "string",
              description: "Issue body",
            },
            labels: {
              type: "array",
              items: { type: "string" },
              description: "Issue labels",
            },
          },
          required: ["owner", "repo", "title"],
        },
      },
      {
        name: "create_pull_request",
        description: "Create a pull request",
        inputSchema: {
          type: "object",
          properties: {
            owner: { type: "string" },
            repo: { type: "string" },
            title: { type: "string" },
            body: { type: "string" },
            head: {
              type: "string",
              description: "Branch name with changes",
            },
            base: {
              type: "string",
              description: "Branch to merge into",
              default: "main",
            },
          },
          required: ["owner", "repo", "title", "head"],
        },
      },
      {
        name: "list_commits",
        description: "List commits in a repository",
        inputSchema: {
          type: "object",
          properties: {
            owner: { type: "string" },
            repo: { type: "string" },
            sha: {
              type: "string",
              description: "Branch or commit SHA",
              default: "main",
            },
            per_page: {
              type: "integer",
              default: 30,
            },
          },
          required: ["owner", "repo"],
        },
      },
    ],
  };
});

// ===== 2. 实现工具调用 =====

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  switch (name) {
    case "create_issue":
      return await createIssue(args as any);
    
    case "create_pull_request":
      return await createPullRequest(args as any);
    
    case "list_commits":
      return await listCommits(args as any);
    
    default:
      throw new Error(`Unknown tool: ${name}`);
  }
});

// ===== 3. 工具实现 =====

import { Octokit } from "octokit";

const octokit = new Octokit({
  auth: process.env.GITHUB_TOKEN,
});

async function createIssue(args: {
  owner: string;
  repo: string;
  title: string;
  body?: string;
  labels?: string[];
}) {
  try {
    const response = await octokit.rest.issues.create({
      owner: args.owner,
      repo: args.repo,
      title: args.title,
      body: args.body,
      labels: args.labels,
    });

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: true,
            issue_number: response.data.number,
            url: response.data.html_url,
          }, null, 2),
        },
      ],
    };
  } catch (error: any) {
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: false,
            error: error.message,
          }, null, 2),
        },
      ],
    };
  }
}

async function createPullRequest(args: {
  owner: string;
  repo: string;
  title: string;
  head: string;
  base?: string;
  body?: string;
}) {
  try {
    const response = await octokit.rest.pulls.create({
      owner: args.owner,
      repo: args.repo,
      title: args.title,
      head: args.head,
      base: args.base || "main",
      body: args.body,
    });

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: true,
            pr_number: response.data.number,
            url: response.data.html_url,
          }, null, 2),
        },
      ],
    };
  } catch (error: any) {
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: false,
            error: error.message,
          }, null, 2),
        },
      ],
    };
  }
}

async function listCommits(args: {
  owner: string;
  repo: string;
  sha?: string;
  per_page?: number;
}) {
  try {
    const response = await octokit.rest.repos.listCommits({
      owner: args.owner,
      repo: args.repo,
      sha: args.sha || "main",
      per_page: args.per_page || 30,
    });

    const commits = response.data.map((commit) => ({
      sha: commit.sha,
      message: commit.commit.message,
      author: commit.commit.author?.name,
      date: commit.commit.author?.date,
    }));

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(commits, null, 2),
        },
      ],
    };
  } catch (error: any) {
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            success: false,
            error: error.message,
          }, null, 2),
        },
      ],
    };
  }
}

// ===== 4. 启动服务器 =====

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("GitHub MCP server running on stdio");
}

main().catch((error) => {
  console.error("Fatal error:", error);
  process.exit(1);
});

4. 热门MCP工具实战

4.1 Chrome DevTools MCP

# Chrome DevTools MCP实战
# 41K+ Stars,最热门的浏览器自动化MCP

"""
功能:
• 浏览器导航、截图
• DOM操作、元素查找
• 网络请求拦截
• 性能分析
• JavaScript执行
"""

# 安装与配置
CONFIG = """
# claude_desktop_config.json
{
  "mcpServers": {
    "chrome-devtools": {
      "command": "npx",
      "args": ["-y", "@anthropic-ai/chrome-devtools-mcp"]
    }
  }
}
"""

# 使用示例 (在Claude Code中)
USAGE_EXAMPLES = """
# 示例1: 网页截图
User: 截取 https://example.com 的截图
Claude: [调用 chrome-devtools navigate + screenshot]

# 示例2: 表单自动填写
User: 在登录页面填写用户名和密码
Claude: [调用 chrome-devtools type]

# 示例3: 性能分析
User: 分析这个页面的加载性能
Claude: [调用 chrome-devtools performance]
"""

# Python调用MCP
import subprocess
import json

class ChromeDevToolsMCPClient:
    """Chrome DevTools MCP客户端"""
    
    def __init__(self):
        self.process = None
    
    async def start(self):
        """启动MCP Server"""
        self.process = await asyncio.create_subprocess_exec(
            "npx", "-y", "@anthropic-ai/chrome-devtools-mcp",
            stdin=asyncio.subprocess.PIPE,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE
        )
    
    async def call_tool(self, tool_name: str, arguments: dict) -> dict:
        """调用工具"""
        request = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "tools/call",
            "params": {
                "name": tool_name,
                "arguments": arguments
            }
        }
        
        self.process.stdin.write((json.dumps(request) + "\n").encode())
        await self.process.stdin.drain()
        
        response = await self.process.stdout.readline()
        return json.loads(response)
    
    async def navigate(self, url: str):
        """导航到URL"""
        return await self.call_tool("navigate", {"url": url})
    
    async def screenshot(self, selector: str = None):
        """截图"""
        return await self.call_tool("screenshot", {
            "selector": selector
        } if selector else {})
    
    async def click(self, selector: str):
        """点击元素"""
        return await self.call_tool("click", {"selector": selector})
    
    async def type_text(self, selector: str, text: str):
        """输入文本"""
        return await self.call_tool("type", {
            "selector": selector,
            "text": text
        })
    
    async def evaluate(self, script: str):
        """执行JavaScript"""
        return await self.call_tool("evaluate", {"script": script})


# 实战案例: 自动化测试
async def run_e2e_test():
    """端到端测试示例"""
    client = ChromeDevToolsMCPClient()
    await client.start()
    
    # 1. 打开登录页面
    await client.navigate("https://app.example.com/login")
    await asyncio.sleep(2)
    
    # 2. 填写表单
    await client.type_text("#username", "test@example.com")
    await client.type_text("#password", "test123")
    
    # 3. 点击登录
    await client.click("#login-button")
    await asyncio.sleep(3)
    
    # 4. 验证登录成功
    result = await client.evaluate("""
        document.querySelector('.user-avatar') !== null
    """)
    
    # 5. 截图
    screenshot = await client.screenshot()
    
    return {
        "test_passed": result.get("result", False),
        "screenshot": screenshot
    }

4.2 PostgreSQL MCP

# PostgreSQL MCP实战
# 28K+ Stars,数据库操作MCP

"""
功能:
• 执行SQL查询
• 查看Schema
• 生成迁移脚本
• 性能分析
"""

# 配置
CONFIG = """
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@anthropic-ai/postgres-mcp"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost/mydb"
      }
    }
  }
}
"""

# MCP工具定义
POSTGRES_TOOLS = {
    "query": {
        "description": "Execute SQL query",
        "params": ["sql"]
    },
    "list_tables": {
        "description": "List all tables",
        "params": []
    },
    "describe_table": {
        "description": "Show table schema",
        "params": ["table_name"]
    },
    "analyze_query": {
        "description": "EXPLAIN ANALYZE query",
        "params": ["sql"]
    }
}

# 使用示例
async def database_operations():
    """数据库操作示例"""
    
    # 1. 列出所有表
    tables = await mcp_call("postgres", "list_tables", {})
    print(f"Tables: {tables}")
    
    # 2. 查看表结构
    schema = await mcp_call("postgres", "describe_table", {
        "table_name": "users"
    })
    print(f"Schema: {schema}")
    
    # 3. 执行查询
    result = await mcp_call("postgres", "query", {
        "sql": "SELECT * FROM users WHERE created_at > NOW() - INTERVAL '7 days'"
    })
    print(f"Result: {result}")
    
    # 4. 性能分析
    analysis = await mcp_call("postgres", "analyze_query", {
        "sql": "SELECT * FROM orders WHERE user_id = 123"
    })
    print(f"Query plan: {analysis}")

5. MCP工具集成最佳实践

5.1 Claude Code配置

// claude_desktop_config.json 完整配置示例

{
  "mcpServers": {
    // 文件系统
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/home/user/projects"
      ]
    },
    
    // PostgreSQL数据库
    "postgres": {
      "command": "npx",
      "args": ["-y", "@anthropic-ai/postgres-mcp"],
      "env": {
        "DATABASE_URL": "postgresql://user:pass@localhost/mydb"
      }
    },
    
    // GitHub
    "github": {
      "command": "npx",
      "args": ["-y", "@anthropic-ai/github-mcp"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    
    // Chrome DevTools
    "chrome-devtools": {
      "command": "npx",
      "args": ["-y", "@anthropic-ai/chrome-devtools-mcp"]
    },
    
    // 自定义MCP
    "my-custom": {
      "command": "python",
      "args": ["/path/to/my_mcp_server.py"],
      "env": {
        "API_KEY": "${MY_API_KEY}"
      }
    }
  }
}

5.2 安全配置

# MCP安全配置

"""
安全最佳实践:
1. 使用环境变量存储敏感信息
2. 限制工具权限范围
3. 审计日志记录
4. 沙箱隔离执行
"""

# 1. 环境变量管理
import os
from dotenv import load_dotenv

load_dotenv()  # 加载 .env 文件

DATABASE_URL = os.getenv("DATABASE_URL")
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
API_KEY = os.getenv("MY_API_KEY")

# 2. 权限控制
class SecureMCPServer:
    """带权限控制的MCP Server"""
    
    def __init__(self):
        self.permissions = {
            "query_database": ["read"],
            "write_file": ["write"],
            "execute_command": ["execute"],
        }
        
        self.audit_log = []
    
    async def call_tool(self, name: str, arguments: dict, user: str):
        """带权限检查的工具调用"""
        
        # 检查权限
        required_permissions = self.permissions.get(name, [])
        if not self.check_permission(user, required_permissions):
            raise PermissionError(f"User {user} lacks permission for {name}")
        
        # 审计日志
        self.audit_log.append({
            "timestamp": datetime.now().isoformat(),
            "user": user,
            "tool": name,
            "arguments": arguments,
        })
        
        # 执行工具
        result = await self._execute_tool(name, arguments)
        
        return result
    
    def check_permission(self, user: str, permissions: list) -> bool:
        """检查用户权限"""
        user_permissions = self.get_user_permissions(user)
        return all(p in user_permissions for p in permissions)
    
    def get_audit_report(self) -> list:
        """获取审计报告"""
        return self.audit_log

# 3. 沙箱执行
import subprocess
import tempfile
import shutil

class SandboxExecutor:
    """沙箱执行环境"""
    
    def __init__(self):
        self.sandbox_dir = tempfile.mkdtemp()
    
    async def execute_script(self, script: str) -> dict:
        """在沙箱中执行脚本"""
        
        # 写入脚本文件
        script_path = os.path.join(self.sandbox_dir, "script.sh")
        with open(script_path, "w") as f:
            f.write(script)
        
        try:
            # 在沙箱中执行
            result = subprocess.run(
                ["bash", script_path],
                cwd=self.sandbox_dir,
                capture_output=True,
                text=True,
                timeout=30  # 30秒超时
            )
            
            return {
                "success": result.returncode == 0,
                "stdout": result.stdout,
                "stderr": result.stderr,
            }
        
        except subprocess.TimeoutExpired:
            return {
                "success": False,
                "error": "Execution timeout"
            }
        
        finally:
            # 清理沙箱
            shutil.rmtree(self.sandbox_dir)

6. MCP生态开发指南

6.1 发布到ClawHub

# mcp-package.yaml - ClawHub发布配置

name: my-awesome-mcp
version: 1.0.0
description: A powerful MCP server for XYZ operations
author: Your Name
license: MIT

# 工具列表
tools:
  - name: tool_one
    description: Does something awesome
    category: automation
    
  - name: tool_two
    description: Another great tool
    category: database

# 依赖
dependencies:
  - python >= 3.10
  - mcp >= 0.1.0

# 环境变量
env_vars:
  - name: API_KEY
    description: Your API key
    required: true

# 安装命令
install: |
  pip install my-awesome-mcp

# 配置示例
config_example: |
  {
    "mcpServers": {
      "my-awesome-mcp": {
        "command": "python",
        "args": ["-m", "my_awesome_mcp"],
        "env": {
          "API_KEY": "${API_KEY}"
        }
      }
    }
  }

6.2 版本管理

# MCP工具版本管理

"""
版本管理最佳实践:
1. 语义化版本号 (SemVer)
2. 向后兼容性保证
3. 变更日志
4. 自动化测试
"""

class VersionedMCPServer:
    """带版本管理的MCP Server"""
    
    VERSION = "1.2.0"
    
    def __init__(self):
        self.version_info = {
            "version": self.VERSION,
            "tools": {
                "tool_v1": self._deprecated_tool,
                "tool_v2": self._current_tool,
            }
        }
    
    @server.list_tools()
    async def list_tools(self):
        """列出工具(带版本标记)"""
        return [
            Tool(
                name="query",
                description="Execute database query (v2)",
                inputSchema={...},
                annotations={
                    "version": "2.0",
                    "deprecated": False,
                }
            ),
            Tool(
                name="query_v1",
                description="Execute database query (v1, deprecated)",
                inputSchema={...},
                annotations={
                    "version": "1.0",
                    "deprecated": True,
                    "replacement": "query",
                }
            )
        ]
    
    async def _current_tool(self, args):
        """当前版本工具实现"""
        pass
    
    async def _deprecated_tool(self, args):
        """已弃用工具(警告用户)"""
        print("WARNING: This tool is deprecated. Use 'query' instead.")
        # 转发到新版本
        return await self._current_tool(args)

7. 总结

MCP生态2026关键数据

MCP生态统计:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

工具数量: 11000+
热门工具: Chrome DevTools (41K), PostgreSQL (28K), GitHub (24K)
市场规模: ClawHub + SkillsMP + Skills.sh

核心优势:
✅ 标准化:统一协议,一次开发多平台使用
✅ 可组合:工具链灵活编排
✅ 开放:开源协议,社区驱动
✅ 安全:权限控制,审计日志

发展趋势:
→ 企业内部MCP快速增长
→ 行业垂直MCP(医疗、金融、法律)
→ 低代码MCP构建平台
→ MCP市场平台竞争加剧
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

开发者快速上手

MCP开发快速指南:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. 选择SDK:
   • Python: pip install mcp
   • TypeScript: npm install @modelcontextprotocol/sdk

2. 定义工具:
   @server.list_tools()
   @server.call_tool()

3. 启动服务器:
   stdio_server transport

4. 配置Host:
   claude_desktop_config.json

5. 测试验证:
   claude code ask "测试我的工具"

6. 发布分享:
   ClawHub.ai 或 GitHub
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐