tech-mcp-server-dev

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MCP Server Development

MCP服务器开发

Framework

框架

IRON LAW: Tools Must Be Self-Describing

Every MCP tool must have a clear name, description, and input schema
that allows the AI model to understand WHEN and HOW to use it without
any external documentation. If the model can't figure out when to call
your tool from its name and description alone, the tool is poorly designed.
铁律:工具必须具备自描述性

每个MCP工具都必须拥有清晰的名称、描述和输入Schema,让AI模型无需任何外部文档就能理解何时以及如何使用它。如果模型仅通过名称和描述无法判断何时调用你的工具,那这个工具的设计就是不合格的。

MCP Architecture

MCP架构

Claude Code / AI Agent
    ↓ (stdio JSON-RPC 2.0)
MCP Server (your code)
Your Data Source (DB, API, file system, etc.)
Claude Code / AI Agent
    ↓(标准输入输出JSON-RPC 2.0)
MCP服务器(你的代码)
你的数据源(数据库、API、文件系统等)

Protocol Basics

协议基础

ConceptWhat It Is
Transportstdio (stdin/stdout) — most common for local servers
ProtocolJSON-RPC 2.0
ToolsFunctions the model can call (read data, take actions)
ResourcesData the model can read (files, database records)
PromptsPre-built prompt templates the model can use
概念说明
传输方式stdio(标准输入/输出)——本地服务器最常用的方式
协议JSON-RPC 2.0
工具模型可以调用的函数(读取数据、执行操作)
资源模型可以读取的数据(文件、数据库记录等)
提示词模型可使用的预构建提示词模板

Tool Design Principles

工具设计原则

  1. Atomic operations: Each tool does ONE thing. "search_users" not "search_and_update_users"
  2. Clear naming: verb_noun format. "get_customer", "create_order", "search_products"
  3. Descriptive descriptions: Include WHEN to use, not just what it does
  4. Strict schemas: Define all parameters with types, descriptions, and required/optional
  5. Meaningful errors: Return error messages the model can understand and act on
  1. 原子化操作:每个工具只做一件事。比如用"search_users"而非"search_and_update_users"
  2. 清晰命名:采用动词_名词格式。例如"get_customer"、"create_order"、"search_products"
  3. 描述性说明:要包含使用场景,而不只是功能描述
  4. 严格的Schema:定义所有参数的类型、描述以及必填/可选属性
  5. 有意义的错误信息:返回模型能够理解并据此采取行动的错误消息

Tool Schema Example

工具Schema示例

json
{
  "name": "search_customers",
  "description": "Search for customers by name, email, or phone number. Use when the user asks to find or look up a specific customer.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": {
        "type": "string",
        "description": "Search term — can be customer name, email, or phone"
      },
      "limit": {
        "type": "number",
        "description": "Maximum results to return (default: 10)",
        "default": 10
      }
    },
    "required": ["query"]
  }
}
json
{
  "name": "search_customers",
  "description": "Search for customers by name, email, or phone number. Use when the user asks to find or look up a specific customer.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": {
        "type": "string",
        "description": "Search term — can be customer name, email, or phone"
      },
      "limit": {
        "type": "number",
        "description": "Maximum results to return (default: 10)",
        "default": 10
      }
    },
    "required": ["query"]
  }
}

Implementation Steps (Python/TypeScript)

实现步骤(Python/TypeScript)

Phase 1: Setup
  1. Choose SDK:
    @modelcontextprotocol/sdk
    (TypeScript) or
    mcp
    (Python)
  2. Define tools with schemas
  3. Implement tool handlers
  4. Test locally with
    mcp dev
    or
    claude mcp add
Phase 2: Data Connection 5. Connect to your data source (DB, API, etc.) 6. Implement authentication (env vars for secrets) 7. Add error handling for all data operations 8. Add logging for debugging
Phase 3: Integration 9. Configure in
.mcp.json
for Claude Code 10. Test with real queries 11. Add to project CLAUDE.md so Claude knows about available tools
阶段1:搭建环境
  1. 选择SDK:
    @modelcontextprotocol/sdk
    (TypeScript)或
    mcp
    (Python)
  2. 定义带Schema的工具
  3. 实现工具处理器
  4. 使用
    mcp dev
    claude mcp add
    进行本地测试
阶段2:数据连接 5. 连接到你的数据源(数据库、API等) 6. 实现身份验证(使用环境变量存储密钥) 7. 为所有数据操作添加错误处理 8. 添加日志用于调试
阶段3:集成 9. 在
.mcp.json
中为Claude Code配置服务器 10. 使用真实查询进行测试 11. 将服务器添加到项目的CLAUDE.md中,让Claude知晓可用工具

.mcp.json Configuration

.mcp.json配置

json
{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["path/to/server.js"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  }
}
json
{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["path/to/server.js"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  }
}

Error Handling

错误处理

Tool handler should:
1. Validate input (check required fields, types)
2. Try the operation
3. On success: return structured data (JSON)
4. On error: return { "error": "Human-readable message", "code": "ERROR_CODE" }
   - NOT stack traces or internal error details
   - The MODEL needs to understand the error to retry or inform the user
工具处理器应:
1. 验证输入(检查必填字段、类型)
2. 执行操作
3. 成功时:返回结构化数据(JSON格式)
4. 出错时:返回 { "error": "人类友好的可读消息", "code": "错误代码" }
   - 不要返回堆栈跟踪或内部错误细节
   - 模型需要理解错误信息才能重试或告知用户

Output Format

输出格式

markdown
undefined
markdown
undefined

MCP Server Spec: {Server Name}

MCP服务器规格:{服务器名称}

Purpose

用途

{What data/capability this server exposes}
{该服务器暴露的数据源/能力}

Tools

工具

ToolDescriptionParametersReturns
{name}{when to use}{params}{return type}
工具说明参数返回值
{名称}{使用场景}{参数}{返回类型}

Data Source

数据源

  • Type: {database / API / file system}
  • Connection: {how to connect}
  • Auth: {env vars needed}
  • 类型:{数据库 / API / 文件系统}
  • 连接方式:{如何连接}
  • 身份验证:{所需的环境变量}

.mcp.json

.mcp.json

json
{config}
json
{config}

Testing Plan

测试计划

  1. {test case for each tool}
undefined
  1. {每个工具的测试用例}
undefined

Gotchas

注意事项

  • Environment variables for secrets: NEVER hardcode API keys or database passwords. Use
    env
    in .mcp.json to pass secrets from environment variables.
  • Tool description quality: The model decides whether to use your tool based SOLELY on the name + description. A bad description means the tool never gets called (or gets called for wrong reasons).
  • Return data size: Don't return 10,000 rows. The model's context window is limited. Return summarized or paginated results. Default limit = 10-20 items.
  • Idempotent reads, confirmed writes: Read operations should be safe to call multiple times. Write operations (create, update, delete) should confirm with the user before execution.
  • Test with real model interactions: Unit tests aren't enough. The real test is whether Claude actually uses your tool correctly in conversation. Test with diverse prompts.
  • 使用环境变量存储密钥:绝对不要硬编码API密钥或数据库密码。使用.mcp.json中的
    env
    字段从环境变量传递密钥。
  • 工具描述质量:模型完全依据名称+描述来决定是否使用你的工具。糟糕的描述意味着工具永远不会被调用(或者被错误调用)。
  • 返回数据大小:不要返回10000行数据。模型的上下文窗口是有限的。返回汇总或分页的结果。默认限制为10-20条数据。
  • 幂等读取,确认后写入:读取操作应支持安全重复调用。写入操作(创建、更新、删除)在执行前应先征得用户确认。
  • 与真实模型交互测试:单元测试是不够的。真正的测试是Claude在对话中是否能正确使用你的工具。使用多样化的提示词进行测试。

References

参考资料

  • For MCP SDK documentation, see
    references/mcp-sdk.md
  • For advanced MCP patterns (resources, prompts), see
    references/mcp-advanced.md
  • 有关MCP SDK文档,请查看
    references/mcp-sdk.md
  • 有关高级MCP模式(资源、提示词),请查看
    references/mcp-advanced.md