mcp

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MCP: Build & Manage Protocol Servers

MCP:构建与管理协议服务器

Build MCP servers that integrate APIs, and execute tools from configured servers.
构建可集成API的MCP服务器,并从已配置的服务器中执行工具。

When to Use

适用场景

Building: Create MCP servers (Python/TypeScript), integrate APIs, design agent-centric tools, implement validation/error handling, create evaluations
Managing: Discover/execute tools via Gemini CLI, filter tools for tasks, manage multi-server configs
构建阶段:创建MCP服务器(Python/TypeScript)、集成API、设计以Agent为中心的工具、实现验证/错误处理、创建评估用例
管理阶段:通过Gemini CLI发现/执行工具、针对任务筛选工具、管理多服务器配置

Core Concepts

核心概念

MCP = standardized protocol for AI agents to access external tools/data.
Components: Tools (executable functions), Resources (read-only data), Prompts (templates) Transports: Stdio (local), HTTP (remote), SSE (real-time)
Load:
references/protocol-basics.md
for full protocol details

MCP = AI Agent访问外部工具/数据的标准化协议。
组件:工具(可执行函数)、资源(只读数据)、提示词(模板) 传输方式:Stdio(本地)、HTTP(远程)、SSE(实时)
参考:加载
references/protocol-basics.md
查看完整协议细节

Part 1: Building MCP Servers

第一部分:构建MCP服务器

Build high-quality MCP servers that enable LLMs to accomplish real-world tasks.
构建高质量MCP服务器,让大语言模型(LLM)能够完成实际业务任务。

Development Workflow

开发流程

Phase 1: Research & Planning
  1. Study agent-centric design principles (workflows over endpoints)
  2. Research target API documentation exhaustively
  3. Load framework documentation (Python SDK or TypeScript SDK)
  4. Plan tool selection, shared utilities, input/output design, error handling
Phase 2: Implementation
  1. Set up project structure (single file for Python, full structure for TypeScript)
  2. Implement core infrastructure (API clients, error handlers, formatters)
  3. Register tools with proper schemas and annotations
  4. Follow language-specific best practices
Phase 3: Testing & Quality
  1. Code quality review (DRY, composability, consistency)
  2. Run builds and syntax checks
  3. Use quality checklists
Phase 4: Evaluation
  1. Create 10 complex, realistic evaluation questions
  2. Questions must be read-only, independent, and verifiable
  3. Test LLM's ability to use your server effectively
Reference:
references/building-servers.md
- Load for complete development guide with:
  • Agent-centric design principles
  • Python (FastMCP) implementation guide with Pydantic models
  • TypeScript (MCP SDK) implementation guide with Zod schemas
  • Tool naming conventions, response formats, pagination patterns
  • Character limits, error handling, security best practices
  • Complete working examples and quality checklists
  • Evaluation creation and testing methodology
阶段1:调研与规划
  1. 学习以Agent为中心的设计原则(优先工作流而非端点)
  2. 深入调研目标API文档
  3. 查阅框架文档(Python SDK或TypeScript SDK)
  4. 规划工具选型、共享工具类、输入/输出设计、错误处理方案
阶段2:实现开发
  1. 搭建项目结构(Python用单文件,TypeScript用完整项目结构)
  2. 实现核心基础设施(API客户端、错误处理器、格式化工具)
  3. 注册带有正确Schema和注解的工具
  4. 遵循对应语言的最佳实践
阶段3:测试与质量保障
  1. 代码质量评审(遵循DRY原则、可组合性、一致性)
  2. 执行构建与语法检查
  3. 使用质量检查清单
阶段4:评估验证
  1. 创建10个复杂、贴近真实场景的评估问题
  2. 问题需为只读、独立且可验证
  3. 测试LLM有效使用你的服务器的能力
参考
references/building-servers.md
- 加载查看完整开发指南,包含:
  • 以Agent为中心的设计原则
  • 基于Pydantic模型的Python(FastMCP)实现指南
  • 基于Zod Schema的TypeScript(MCP SDK)实现指南
  • 工具命名规范、响应格式、分页模式
  • 字符限制、错误处理、安全最佳实践
  • 完整可运行示例与质量检查清单
  • 评估用例创建与测试方法

Key Best Practices

关键最佳实践

Tool Design:
  • Use service-prefixed names (
    slack_send_message
    , not
    send_message
    )
  • Support both JSON and Markdown response formats
  • Implement pagination with
    limit
    ,
    offset
    ,
    has_more
  • Set CHARACTER_LIMIT constant (typically 25,000)
  • Provide actionable error messages that guide agents
Code Quality:
  • Extract common functionality into reusable functions
  • Use async/await for all I/O operations
  • Type hints (Python) or strict TypeScript throughout
  • Comprehensive docstrings with explicit schemas
Reference:
references/best-practices.md
- Load for comprehensive guidelines

工具设计
  • 使用服务前缀命名(如
    slack_send_message
    ,而非
    send_message
  • 同时支持JSON和Markdown响应格式
  • 实现带有
    limit
    offset
    has_more
    的分页功能
  • 设置CHARACTER_LIMIT常量(通常为25,000)
  • 提供可指导Agent的可操作错误信息
代码质量
  • 将通用功能提取为可复用函数
  • 所有I/O操作使用async/await
  • 全程使用类型提示(Python)或严格TypeScript
  • 包含明确Schema的全面文档字符串
参考
references/best-practices.md
- 加载查看综合指南

Part 2: Using MCP Tools

第二部分:使用MCP工具

Execute and manage tools from configured MCP servers efficiently.
高效执行与管理来自已配置MCP服务器的工具。

Configuration

配置说明

MCP servers configured in
.claude/.mcp.json
:
json
{
  "mcpServers": {
    "server-name": {
      "command": "npx",
      "args": ["-y", "package-name"],
      "env": {"API_KEY": "${ENV_VAR}"}
    }
  }
}
Gemini CLI Integration: Create symlink for shared config:
bash
mkdir -p .gemini && ln -sf .claude/.mcp.json .gemini/settings.json
Reference:
references/using-tools.md
- Load for complete configuration and usage guide
MCP服务器配置于
.claude/.mcp.json
json
{
  "mcpServers": {
    "server-name": {
      "command": "npx",
      "args": ["-y", "package-name"],
      "env": {"API_KEY": "${ENV_VAR}"}
    }
  }
}
Gemini CLI集成:创建符号链接共享配置:
bash
mkdir -p .gemini && ln -sf .claude/.mcp.json .gemini/settings.json
参考
references/using-tools.md
- 加载查看完整配置与使用指南

Execution Methods (Priority Order)

执行方式(优先级排序)

1. Gemini CLI (Primary)
Automatic tool discovery and execution via natural language.
bash
undefined
1. Gemini CLI(首选)
通过自然语言自动发现并执行工具。
bash
undefined

CRITICAL: Use stdin piping, NOT -p flag (deprecated, skips MCP init)

重要:使用stdin管道,不要使用-p参数(已废弃,会跳过MCP初始化)

echo "Take a screenshot of https://example.com" | gemini -y -m gemini-2.5-flash

**Benefits**:
- Automatic tool discovery and selection
- Structured JSON responses (if `GEMINI.md` configured)
- Fastest execution
- No manual tool specification needed

**GEMINI.md Response Format**: Place in project root to enforce JSON-only responses:
```markdown
echo "为https://example.com截图" | gemini -y -m gemini-2.5-flash

**优势**:
- 自动工具发现与选择
- 结构化JSON响应(若配置`GEMINI.md`)
- 执行速度最快
- 无需手动指定工具

**GEMINI.md响应格式**:放置于项目根目录以强制仅返回JSON:
```markdown

Gemini CLI Instructions

Gemini CLI指令

Always respond in this exact JSON format: {"server":"name","tool":"name","success":true,"result":<data>,"error":null} Maximum 500 characters. No markdown, no explanations.

**2. Direct CLI Scripts (Secondary)**

Manual tool specification when you know exact server/tool needed:

```bash
npx tsx scripts/cli.ts call-tool memory create_entities '{"entities":[...]}'
3. mcp-manager Subagent (Fallback)
Delegate to subagent when Gemini unavailable or for complex multi-tool workflows.
Reference:
references/using-tools.md
- Load for:
  • Complete Gemini CLI guide with examples
  • Direct script usage and options
  • Subagent delegation patterns
  • Tool discovery and filtering strategies
  • Multi-server orchestration
  • Troubleshooting and debugging
始终以以下精确JSON格式响应: {"server":"name","tool":"name","success":true,"result":<data>,"error":null} 最大长度500字符。禁止使用Markdown,禁止添加解释。

**2. 直接CLI脚本(次选)**

当明确知道所需服务器/工具时,手动指定执行:

```bash
npx tsx scripts/cli.ts call-tool memory create_entities '{"entities":[...]}'
3. mcp-manager子Agent(备选)
当Gemini不可用或处理复杂多工具工作流时,委托给子Agent。
参考
references/using-tools.md
- 加载查看:
  • 完整Gemini CLI指南与示例
  • 直接脚本使用方法与选项
  • 子Agent委托模式
  • 工具发现与筛选策略
  • 多服务器编排
  • 故障排查与调试

Tool Discovery

工具发现

List available tools to understand capabilities:
bash
undefined
列出可用工具以了解功能:
bash
undefined

Saves to assets/tools.json for offline reference

保存到assets/tools.json供离线参考

npx tsx scripts/cli.ts list-tools
npx tsx scripts/cli.ts list-tools

List prompts and resources

列出提示词与资源

npx tsx scripts/cli.ts list-prompts npx tsx scripts/cli.ts list-resources

**Intelligent Selection**: LLM reads `assets/tools.json` directly for context-aware tool filtering (better than keyword matching).

---
npx tsx scripts/cli.ts list-prompts npx tsx scripts/cli.ts list-resources

**智能选择**:LLM直接读取`assets/tools.json`,实现基于上下文的工具筛选(比关键词匹配更精准)。

---

Quick Start Examples

快速开始示例

Building a Server

构建服务器

Python:
python
from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field

mcp = FastMCP("github_mcp")

class SearchInput(BaseModel):
    query: str = Field(..., min_length=2, max_length=200)
    limit: int = Field(default=20, ge=1, le=100)

@mcp.tool(name="github_search_repos", annotations={"readOnlyHint": True})
async def search_repos(params: SearchInput) -> str:
    # Implementation
    pass

if __name__ == "__main__":
    mcp.run()
TypeScript:
typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

const server = new McpServer({name: "github-mcp-server", version: "1.0.0"});

const SearchSchema = z.object({
  query: z.string().min(2).max(200),
  limit: z.number().int().min(1).max(100).default(20)
}).strict();

server.registerTool("github_search_repos", {
  description: "Search GitHub repositories",
  inputSchema: SearchSchema,
  annotations: {readOnlyHint: true}
}, async (params) => {
  // Implementation
});
Load
references/building-servers.md
for complete implementation guides.
Python
python
from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field

mcp = FastMCP("github_mcp")

class SearchInput(BaseModel):
    query: str = Field(..., min_length=2, max_length=200)
    limit: int = Field(default=20, ge=1, le=100)

@mcp.tool(name="github_search_repos", annotations={"readOnlyHint": True})
async def search_repos(params: SearchInput) -> str:
    # 实现代码
    pass

if __name__ == "__main__":
    mcp.run()
TypeScript
typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

const server = new McpServer({name: "github-mcp-server", version: "1.0.0"});

const SearchSchema = z.object({
  query: z.string().min(2).max(200),
  limit: z.number().int().min(1).max(100).default(20)
}).strict();

server.registerTool("github_search_repos", {
  description: "Search GitHub repositories",
  inputSchema: SearchSchema,
  annotations: {readOnlyHint: true}
}, async (params) => {
  // 实现代码
});
加载
references/building-servers.md
查看完整实现指南。

Using Tools

使用工具

Gemini CLI:
bash
undefined
Gemini CLI
bash
undefined

IMPORTANT: Use stdin piping, NOT -p flag

重要:使用stdin管道,不要使用-p参数

echo "Search GitHub for MCP servers and summarize top 3" | gemini -y -m gemini-2.5-flash

**Direct Script**:
```bash
npx tsx scripts/cli.ts call-tool github search_repos '{"query":"mcp","limit":3}'
Load
references/using-tools.md
for complete usage patterns.

echo "在GitHub上搜索MCP服务器并总结排名前三的项目" | gemini -y -m gemini-2.5-flash

**直接脚本**:
```bash
npx tsx scripts/cli.ts call-tool github search_repos '{"query":"mcp","limit":3}'
加载
references/using-tools.md
查看完整使用模式。

Reference Files

参考文件

Load these as needed during your work:
在工作中按需加载以下文件:

Core References

核心参考

  • references/building-servers.md
    - Complete MCP server development guide
    • Agent-centric design principles
    • Python (FastMCP) and TypeScript (MCP SDK) implementation
    • Tool patterns, response formats, pagination, error handling
    • Complete examples and quality checklists
    • Evaluation creation methodology
  • references/using-tools.md
    - Complete MCP tool execution guide
    • Gemini CLI integration and configuration
    • Direct script execution patterns
    • Subagent delegation strategies
    • Tool discovery and filtering
    • Multi-server orchestration
  • references/best-practices.md
    - Universal MCP guidelines
    • Server and tool naming conventions
    • Response format standards (JSON vs Markdown)
    • Pagination, character limits, truncation
    • Security and privacy considerations
    • Testing and compliance requirements
  • references/building-servers.md
    - 完整MCP服务器开发指南
    • 以Agent为中心的设计原则
    • Python(FastMCP)与TypeScript(MCP SDK)实现方案
    • 工具模式、响应格式、分页、错误处理
    • 完整示例与质量检查清单
    • 评估用例创建方法
  • references/using-tools.md
    - 完整MCP工具执行指南
    • Gemini CLI集成与配置
    • 直接脚本执行模式
    • 子Agent委托策略
    • 工具发现与筛选
    • 多服务器编排
  • references/best-practices.md
    - 通用MCP规范
    • 服务器与工具命名约定
    • 响应格式标准(JSON vs Markdown)
    • 分页、字符限制、截断规则
    • 安全与隐私注意事项
    • 测试与合规要求

Supporting References

辅助参考

  • references/protocol-basics.md
    - JSON-RPC protocol details
  • references/python-guide.md
    - Python/FastMCP specifics (Pydantic models, async patterns)
  • references/typescript-guide.md
    - TypeScript/Zod specifics (strict types, project structure)
  • references/evaluation-guide.md
    - Creating effective MCP server evaluations

  • references/protocol-basics.md
    - JSON-RPC协议细节
  • references/python-guide.md
    - Python/FastMCP专属内容(Pydantic模型、异步模式)
  • references/typescript-guide.md
    - TypeScript/Zod专属内容(严格类型、项目结构)
  • references/evaluation-guide.md
    - 创建有效的MCP服务器评估用例

Progressive Disclosure

渐进式披露

This SKILL.md provides high-level overview. Load reference files when:
Building Servers:
  • Starting implementation → Load
    references/building-servers.md
  • Need language-specific details → Load
    references/python-guide.md
    or
    references/typescript-guide.md
  • Creating evaluations → Load
    references/evaluation-guide.md
Using Tools:
  • Setting up Gemini CLI → Load
    references/using-tools.md
  • Debugging tool execution → Load
    references/using-tools.md
  • Multi-server configuration → Load
    references/using-tools.md
Best Practices:
  • Reviewing standards → Load
    references/best-practices.md
  • Security considerations → Load
    references/best-practices.md

本SKILL.md提供高层级概述。在以下场景加载对应参考文件:
构建服务器时
  • 开始实现 → 加载
    references/building-servers.md
  • 需要语言专属细节 → 加载
    references/python-guide.md
    references/typescript-guide.md
  • 创建评估用例 → 加载
    references/evaluation-guide.md
使用工具时
  • 配置Gemini CLI → 加载
    references/using-tools.md
  • 调试工具执行 → 加载
    references/using-tools.md
  • 多服务器配置 → 加载
    references/using-tools.md
遵循最佳实践时
  • 查阅标准规范 → 加载
    references/best-practices.md
  • 安全考量 → 加载
    references/best-practices.md

Integration Patterns

集成模式

Build + Use: Create MCP server, then test with Gemini CLI Multi-Server: Configure multiple servers, orchestrate via Gemini CLI Evaluation-Driven: Build server, create evaluations, iterate based on LLM feedback

构建+使用:创建MCP服务器,然后用Gemini CLI测试 多服务器:配置多个服务器,通过Gemini CLI编排 评估驱动:构建服务器、创建评估用例、基于LLM反馈迭代优化

Boundaries

边界说明

Will:
  • Guide MCP server development in Python or TypeScript
  • Provide tool execution strategies via Gemini CLI or scripts
  • Ensure best practices for agent-centric design
  • Help create effective evaluations
  • Configure multi-server setups
Will Not:
  • Run long-running server processes in main thread (use tmux or evaluation harness)
  • Skip input validation or error handling
  • Create tools without comprehensive documentation
  • Build servers without considering agent context limits
支持的操作
  • 指导Python或TypeScript的MCP服务器开发
  • 提供通过Gemini CLI或脚本执行工具的策略
  • 确保遵循以Agent为中心的设计最佳实践
  • 帮助创建有效的评估用例
  • 配置多服务器环境
不支持的操作
  • 在主线程中运行长时间运行的服务器进程(使用tmux或评估框架)
  • 跳过输入验证或错误处理
  • 创建无完整文档的工具
  • 构建服务器时不考虑Agent的上下文限制