J'Blog

5 课 · 开发

语义检索

基于 Chroma 向量库,与 Workspace 知识库分离。用自然语言描述你想查的内容。 非管理员每人每天可检索 5 次(消耗站点 AI 配额)。

构建 MCP 服务器

原文:构建 MCP Server

一句话

构建MCP服务器以连接Claude/IDE与外部工具,提供工具、资源和提示功能。

什么时候翻这页

当你需要创建自己的MCP服务器,将外部服务或数据源集成到Claude或支持MCP的客户端时。

核心概念

  • MCP服务器提供三种主要能力:
    • Resources:可被客户端读取的类文件数据(如API响应或文件内容)
    • Tools:可被LLM调用的函数(需用户批准)
    • Prompts:帮助用户完成特定任务的预编写模板
  • 本教程主要关注工具的实现
  • 服务器可通过STDIO或HTTP协议与客户端通信

怎么做

  1. 环境准备

    • Python: 安装Python 3.10+和MCP SDK 1.2.0+
    • TypeScript: 安装Node.js 16+和TypeScript
    • Java: 使用Spring AI MCP自动配置和启动器
    • Rust: 使用MCP SDK
    • Go: 使用MCP Go SDK
  2. 实现工具

    • 导入必要的包和设置服务器实例
    • 创建辅助函数处理API请求和数据格式化
    • 实现工具执行逻辑
    • 注册工具到服务器
  3. 运行服务器

    • Python: 使用mcp.run(transport="stdio")
    • TypeScript: 使用StdioServerTransport
    • Java: 使用@SpringBootApplication@McpServer
    • Rust: 使用#[tool_router]#[tool_handler]
    • Go: 使用mcp.NewServermcp.Run
  4. 连接到Claude for Desktop

    • 配置claude_desktop_config.json文件
    • 添加mcpServers部分,指定服务器命令和参数
    • 重启Claude for Desktop

命令 / 配置速查

Python环境设置:

curl -LsSf https://astral.sh/uv/install.sh | sh  # macOS/Linux
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"  # Windows
uv init weather
cd weather
uv venv
source .venv/bin/activate  # macOS/Linux
.venv\Scripts\activate  # Windows
uv add "mcp[cli]" httpx

TypeScript项目设置:

mkdir weather
cd weather
npm init -y
npm install @modelcontextprotocol/sdk zod@3
npm install -D @types/node typescript

Claude for Desktop配置:

{
  "mcpServers": {
    "weather": {
      "command": "uv",
      "args": [
        "--directory",
        "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather",
        "run",
        "weather.py"
      ]
    }
  }
}

与 Claude Code / Hello-Agents 的联系

  • 与Claude Code手册中的MCP章节相关,但更专注于服务器端实现
  • 与Hello-Agents第10章(Agent技能)相关,因为MCP服务器可以作为Agent技能的基础

初学者易错点

  • STDIO服务器日志记录:不要使用print()console.log(),它们会写入stdout并破坏JSON-RPC消息
    • Python: 使用print(..., file=sys.stderr)logging模块
    • TypeScript: 使用console.error()
    • Go: 使用log.Println()fmt.Fprintln(os.Stderr, ...)
  • 路径问题:在配置文件中使用绝对路径,而非相对路径
  • 重启问题:必须完全退出并重新启动Claude for Desktop才能应用配置更改

相关词条

官方原文:https://modelcontextprotocol.io/docs/develop/build-server