SuperAPI AI 工具集

mcp-server-building

智能体与模型

查看项目

更新于 10-16 04:04

技能介绍

用途

MCP Server Building 用于构建 MCP(Model Context Protocol,模型上下文协议)服务器,以扩展 Claude 的能力。当你需要创建 MCP 服务器、构建自定义 Claude 工具,或通过工具、资源与提示词来扩展 Claude 时,可以使用该技能。

架构

Claude 作为 Host,通过 JSON-RPC 与 MCP Server 通信,传输方式支持 stdio、SSE 和 WebSocket。

MCP 提供三种原语:

  • Tools:Claude 可以调用的函数(需用户批准)。
  • Resources:Claude 可以读取的数据(文件、API 响应)。
  • Prompts:预定义的提示词模板。

快速开始

技能提供了两个示例。

最小 Python 服务器(stdio)

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

server = Server("my-tools")

@server.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="greet",
            description="Greet a user by name",
            inputSchema={
                "type": "object",
                "properties": {
                    "name": {"type": "string", "description": "Name to greet"}
                },
                "required": ["name"]
            }
        )
    ]

@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    if name == "greet":
        return [TextContent(type="text", text=f"Hello, {arguments['name']}!")]
    raise ValueError(f"Unknown tool: {name}")

async def main():
    async with stdio_server() as (read, write):
        await server.run(read, write, server.create_initialization_options())

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

TypeScript 服务器(生产环境)

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

const server = new Server(
  { name: "my-tools", version: "1.0.0" },
  { capabilities: { tools: {} } }
);

server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [{
    name: "fetch_url",
    description: "Fetch content from a URL",
    inputSchema: {
      type: "object",
      properties: { url: { type: "string" } },
      required: ["url"],
    },
  }],
}));

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "fetch_url") {
    const { url } = request.params.arguments as { url: string };
    const response = await fetch(url);
    return { content: [{ type: "text", text: await response.text() }] };
  }
  throw new Error("Unknown tool");
});

await server.connect(new StdioServerTransport());

详细指南

技能指向以下参考文档:

  • 传输模式:见 references/transport-patterns.md,涵盖 stdio、SSE、WebSocket。
  • 工具定义:见 references/tool-definitions.md,涵盖 schema、错误处理、缓存。
  • 资源模式:见 references/resource-patterns.md,涵盖文件和动态数据。
  • 测试:见 references/testing-patterns.md,涵盖 MCP Inspector 和 pytest。
  • 自动发现:见 references/auto-discovery.md,针对 CC 2.1.7+ 的优化。

关键决策

决策 选择 理由
传输 CLI 用 stdio,Web 用 SSE stdio 最简单,SSE 面向浏览器
语言 生产环境用 TypeScript 更好的 SDK 支持、类型安全
错误处理 以文本形式返回错误 Claude 可以解释并重试

反模式

  • 有状态工具未清理:始终清理连接。
  • 阻塞同步代码:使用 asyncio.to_thread()。
  • 缺少输入验证:处理前先验证。
  • 在工具输出中泄露密钥:绝不返回凭据。
  • 无界响应:限制响应大小。

相关技能

  • function-calling:LLM 函数调用模式。
  • agent-loops:使用 MCP 工具的智能体模式。
  • input-validation:参数输入验证。

资源

  • MCP 规范:https://modelcontextprotocol.io/docs
  • Python SDK:https://github.com/modelcontextprotocol/python-sdk
  • TypeScript SDK:https://github.com/modelcontextprotocol/typescript-sdk