mcp-server-creation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MCP Server Creation

MCP Server 创建

Description

描述

MCP Server Creation is the skill of building Model Context Protocol servers that expose tools, resources, and capabilities to AI agents through a standardized interface. MCP has emerged as the universal integration layer for AI agent tooling — a single protocol that lets any compliant agent (Claude Code, Cursor, Codex, and others) discover and invoke server-side tools without custom integration code. Building production-quality MCP servers on Cloudflare Workers enables global, low-latency tool access with zero infrastructure management.
This skill draws from the production MCP server powering the Buddy™ agent at googleadsagent.ai™, deployed on Cloudflare Workers in the
workers/buddy-agent/
directory. That server exposes Google Ads analysis tools, knowledge base search, entity memory management, and web search capabilities through MCP, making them available to any MCP-compatible client. The architecture handles authentication, rate limiting, and multi-tenant isolation at the edge.
The MCP specification defines three core primitives: tools (executable functions the agent can invoke), resources (read-only data the agent can access), and prompts (reusable prompt templates). A well-designed MCP server exposes a focused set of high-value tools with clear schemas, meaningful descriptions, and robust error handling. The transport layer supports both stdio (for local development) and SSE/HTTP (for remote deployment), with authentication integrated at the transport level.
MCP Server 创建是一项构建 Model Context Protocol 服务器的技能,它通过标准化接口向 AI Agent 暴露工具、资源和能力。MCP 已成为 AI Agent 工具生态的通用集成层——借助这一统一协议,任何符合规范的 Agent(Claude Code、Cursor、Codex 等)都可以发现并调用服务器端工具,无需编写自定义集成代码。在 Cloudflare Workers 上构建生产级 MCP Server,可实现全球范围内的低延迟工具访问,同时无需管理任何基础设施。
该 Skill 借鉴了为 googleadsagent.ai™ 的 Buddy™ Agent 提供支持的生产级 MCP Server。该 Server 部署在 Cloudflare Workers 的
workers/buddy-agent/
目录中。它通过 MCP 暴露 Google Ads 分析工具、知识库搜索、实体记忆管理和网络搜索能力,使这些能力可供任何兼容 MCP 的客户端使用。其架构在边缘节点处理身份验证、速率限制和多租户隔离。
MCP 规范定义了三种核心原语:tools(Agent 可调用的可执行函数)、resources(Agent 可访问的只读数据)和 prompts(可复用的提示词模板)。设计良好的 MCP Server 应暴露一组聚焦且高价值的工具,并提供清晰的 schema、有意义的描述和稳健的错误处理。传输层同时支持 stdio(用于本地开发)和 SSE/HTTP(用于远程部署),并在传输层集成身份验证。

Use When

适用场景

  • You need to expose custom tools to AI agents through a standardized protocol
  • Building integrations that work across Claude Code, Cursor, and other MCP clients
  • Deploying agent tools to Cloudflare Workers for global edge access
  • Creating a tool marketplace or shared tooling infrastructure for your organization
  • Migrating from proprietary tool interfaces to the open MCP standard
  • Your agent needs tools that require server-side secrets or API access
  • 你需要通过标准化协议向 AI Agent 暴露自定义工具
  • 构建可跨 Claude Code、Cursor 和其他 MCP 客户端运行的集成
  • 将 Agent 工具部署到 Cloudflare Workers,以获得全球边缘访问能力
  • 为你的组织创建工具市场或共享工具基础设施
  • 从专有工具接口迁移到开放的 MCP 标准
  • 你的 Agent 需要依赖服务器端 secrets 或 API 访问权限的工具

How It Works

工作原理

mermaid
graph TD
    A[AI Agent / MCP Client] -->|MCP Protocol| B[Transport Layer]
    B -->|stdio| C[Local Development]
    B -->|SSE/HTTP| D[Remote Server]
    D --> E[Cloudflare Worker]
    E --> F[Authentication]
    F --> G[Tool Router]
    G --> H[Tool: search_knowledge]
    G --> I[Tool: analyze_campaign]
    G --> J[Tool: get_metrics]
    H --> K[Knowledge Base]
    I --> L[Google Ads API]
    J --> L
    G --> M[Resource: config]
    G --> N[Resource: schema]
The MCP server sits between the AI agent client and the actual data sources or APIs. The transport layer handles protocol negotiation (stdio for local, SSE/HTTP for remote). For Cloudflare Workers deployment, incoming requests are authenticated (OAuth, API key, or JWT), then routed to the appropriate tool handler. Each tool handler implements the business logic — calling external APIs, querying databases, or performing computations — and returns structured results that the agent can reason over.
mermaid
graph TD
    A[AI Agent / MCP Client] -->|MCP Protocol| B[Transport Layer]
    B -->|stdio| C[Local Development]
    B -->|SSE/HTTP| D[Remote Server]
    D --> E[Cloudflare Worker]
    E --> F[Authentication]
    F --> G[Tool Router]
    G --> H[Tool: search_knowledge]
    G --> I[Tool: analyze_campaign]
    G --> J[Tool: get_metrics]
    H --> K[Knowledge Base]
    I --> L[Google Ads API]
    J --> L
    G --> M[Resource: config]
    G --> N[Resource: schema]
MCP Server 位于 AI Agent 客户端与实际数据源或 API 之间。传输层负责协议协商(本地使用 stdio,远程使用 SSE/HTTP)。在 Cloudflare Workers 上部署时,传入请求会先经过身份验证(OAuth、API key 或 JWT),随后被路由到相应的工具处理器。每个工具处理器负责实现业务逻辑——调用外部 API、查询数据库或执行计算——并返回可供 Agent 推理分析的结构化结果。

Implementation

实现

MCP Server on Cloudflare Workers:
typescript
import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

export class BuddyMCPServer extends McpAgent {
  server = new McpServer({
    name: "buddy-agent",
    version: "1.0.0",
  });

  async init() {
    this.server.tool(
      "search_knowledge",
      "Search the Google Ads knowledge base for patterns and best practices matching a query. Use BEFORE making recommendations.",
      { query: z.string(), category: z.enum(["bidding", "targeting", "creative", "budget", "general"]).optional(), maxResults: z.number().default(5) },
      async ({ query, category, maxResults }) => {
        const results = await this.searchKnowledgeBase(query, category, maxResults);
        return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] };
      }
    );

    this.server.tool(
      "analyze_campaign",
      "Analyze a Google Ads campaign's performance metrics and return structured insights with recommendations.",
      { campaignId: z.string(), dateRange: z.enum(["7d", "30d", "90d"]).default("30d"), metrics: z.array(z.string()).optional() },
      async ({ campaignId, dateRange, metrics }) => {
        const analysis = await this.analyzeCampaign(campaignId, dateRange, metrics);
        return { content: [{ type: "text", text: JSON.stringify(analysis, null, 2) }] };
      }
    );

    this.server.tool(
      "store_entity",
      "Persist an extracted entity (decision, metric, preference) to cross-session memory.",
      { userId: z.string(), entityType: z.enum(["decision", "metric", "preference", "fact"]), content: z.string(), importance: z.number().min(0).max(1).default(0.5) },
      async ({ userId, entityType, content, importance }) => {
        await this.persistEntity(userId, entityType, content, importance);
        return { content: [{ type: "text", text: `Entity stored: [${entityType}] ${content}` }] };
      }
    );
  }

  private async searchKnowledgeBase(query: string, category?: string, limit?: number) {
    const patterns = await this.env.KNOWLEDGE_KV.list({ prefix: category ? `pattern:${category}:` : "pattern:" });
    const results = [];
    for (const key of patterns.keys.slice(0, limit || 5)) {
      const pattern = await this.env.KNOWLEDGE_KV.get(key.name, "json");
      if (pattern && this.isRelevant(query, pattern)) {
        results.push(pattern);
      }
    }
    return results;
  }
}
Wrangler Configuration:
jsonc
// wrangler.jsonc
{
  "name": "buddy-mcp-server",
  "main": "src/index.ts",
  "compatibility_date": "2025-01-01",
  "compatibility_flags": ["nodejs_compat"],
  "kv_namespaces": [
    { "binding": "KNOWLEDGE_KV", "id": "your-kv-id" },
    { "binding": "MEMORY_KV", "id": "your-memory-kv-id" }
  ],
  "vars": {
    "ENVIRONMENT": "production"
  },
  "placement": { "mode": "smart" }
}
MCP Client Configuration (Claude Code):
json
{
  "mcpServers": {
    "buddy-agent": {
      "type": "sse",
      "url": "https://buddy-mcp.googleadsagent.ai/sse",
      "headers": {
        "Authorization": "Bearer ${BUDDY_API_KEY}"
      }
    }
  }
}
MCP Client Configuration (Cursor):
json
{
  "mcpServers": {
    "buddy-agent": {
      "url": "https://buddy-mcp.googleadsagent.ai/sse",
      "headers": {
        "Authorization": "Bearer ${BUDDY_API_KEY}"
      }
    }
  }
}
Local Development with stdio Transport:
typescript
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

const server = new McpServer({ name: "buddy-agent-dev", version: "1.0.0-dev" });

server.tool(
  "search_knowledge",
  "Search the local knowledge base for development and testing.",
  { query: z.string() },
  async ({ query }) => {
    const results = searchLocalKnowledge(query);
    return { content: [{ type: "text", text: JSON.stringify(results) }] };
  }
);

const transport = new StdioServerTransport();
await server.connect(transport);
基于 Cloudflare Workers 的 MCP Server:
typescript
import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

export class BuddyMCPServer extends McpAgent {
  server = new McpServer({
    name: "buddy-agent",
    version: "1.0.0",
  });

  async init() {
    this.server.tool(
      "search_knowledge",
      "Search the Google Ads knowledge base for patterns and best practices matching a query. Use BEFORE making recommendations.",
      { query: z.string(), category: z.enum(["bidding", "targeting", "creative", "budget", "general"]).optional(), maxResults: z.number().default(5) },
      async ({ query, category, maxResults }) => {
        const results = await this.searchKnowledgeBase(query, category, maxResults);
        return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] };
      }
    );

    this.server.tool(
      "analyze_campaign",
      "Analyze a Google Ads campaign's performance metrics and return structured insights with recommendations.",
      { campaignId: z.string(), dateRange: z.enum(["7d", "30d", "90d"]).default("30d"), metrics: z.array(z.string()).optional() },
      async ({ campaignId, dateRange, metrics }) => {
        const analysis = await this.analyzeCampaign(campaignId, dateRange, metrics);
        return { content: [{ type: "text", text: JSON.stringify(analysis, null, 2) }] };
      }
    );

    this.server.tool(
      "store_entity",
      "Persist an extracted entity (decision, metric, preference) to cross-session memory.",
      { userId: z.string(), entityType: z.enum(["decision", "metric", "preference", "fact"]), content: z.string(), importance: z.number().min(0).max(1).default(0.5) },
      async ({ userId, entityType, content, importance }) => {
        await this.persistEntity(userId, entityType, content, importance);
        return { content: [{ type: "text", text: `Entity stored: [${entityType}] ${content}` }] };
      }
    );
  }

  private async searchKnowledgeBase(query: string, category?: string, limit?: number) {
    const patterns = await this.env.KNOWLEDGE_KV.list({ prefix: category ? `pattern:${category}:` : "pattern:" });
    const results = [];
    for (const key of patterns.keys.slice(0, limit || 5)) {
      const pattern = await this.env.KNOWLEDGE_KV.get(key.name, "json");
      if (pattern && this.isRelevant(query, pattern)) {
        results.push(pattern);
      }
    }
    return results;
  }
}
Wrangler 配置:
jsonc
// wrangler.jsonc
{
  "name": "buddy-mcp-server",
  "main": "src/index.ts",
  "compatibility_date": "2025-01-01",
  "compatibility_flags": ["nodejs_compat"],
  "kv_namespaces": [
    { "binding": "KNOWLEDGE_KV", "id": "your-kv-id" },
    { "binding": "MEMORY_KV", "id": "your-memory-kv-id" }
  ],
  "vars": {
    "ENVIRONMENT": "production"
  },
  "placement": { "mode": "smart" }
}
MCP 客户端配置(Claude Code):
json
{
  "mcpServers": {
    "buddy-agent": {
      "type": "sse",
      "url": "https://buddy-mcp.googleadsagent.ai/sse",
      "headers": {
        "Authorization": "Bearer ${BUDDY_API_KEY}"
      }
    }
  }
}
MCP 客户端配置(Cursor):
json
{
  "mcpServers": {
    "buddy-agent": {
      "url": "https://buddy-mcp.googleadsagent.ai/sse",
      "headers": {
        "Authorization": "Bearer ${BUDDY_API_KEY}"
      }
    }
  }
}
使用 stdio 传输的本地开发:
typescript
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

const server = new McpServer({ name: "buddy-agent-dev", version: "1.0.0-dev" });

server.tool(
  "search_knowledge",
  "Search the local knowledge base for development and testing.",
  { query: z.string() },
  async ({ query }) => {
    const results = searchLocalKnowledge(query);
    return { content: [{ type: "text", text: JSON.stringify(results) }] };
  }
);

const transport = new StdioServerTransport();
await server.connect(transport);

Best Practices

最佳实践

  1. Write tool descriptions that explain when to use the tool — the AI agent selects tools based on descriptions; "Use BEFORE making recommendations" is actionable guidance the model can follow.
  2. Use Zod schemas with descriptive enums — constrained parameter types eliminate invalid inputs; enums are especially effective at guiding model parameter selection.
  3. Return structured JSON, not prose — structured results are easier for the model to reason over and consume fewer tokens than narrative responses.
  4. Implement authentication at the transport layer — never expose MCP servers without authentication; use OAuth, JWT, or API keys validated before tool routing.
  5. Keep tool count focused — 5-10 well-designed tools outperform 50 overlapping tools; models perform better with fewer, clearer choices.
  6. Test with multiple MCP clients — behavior can differ across Claude Code, Cursor, and other clients; test tool invocation on each target client.
  7. Deploy to the edge with Cloudflare Workers — edge deployment minimizes latency for geographically distributed users and provides built-in DDoS protection.
  8. Version your MCP server — as tools evolve, maintain backward compatibility or clearly version-bump to avoid breaking existing client configurations.
  1. 编写说明何时使用工具的工具描述——AI Agent 会根据描述选择工具;“在提出建议之前使用”这类指导是模型能够遵循的可执行说明。
  2. 使用带描述性枚举的 Zod schema——约束参数类型可以消除无效输入;枚举在引导模型选择参数时尤其有效。
  3. 返回结构化 JSON,而不是纯文本——结构化结果更便于模型推理和解析,并且比叙述性响应消耗更少的 token。
  4. 在传输层实现身份验证——绝不要暴露未配置身份验证的 MCP Server;应使用 OAuth、JWT 或 API key,并在工具路由前完成验证。
  5. 保持工具数量聚焦——5 至 10 个精心设计的工具优于 50 个功能重叠的工具;工具更少、更清晰时,模型表现更好。
  6. 使用多个 MCP 客户端进行测试——Claude Code、Cursor 和其他客户端的行为可能不同;应在每个目标客户端上测试工具调用。
  7. 部署到 Cloudflare Workers 边缘节点——边缘部署可降低地理分布用户的延迟,并提供内置的 DDoS 防护。
  8. 为 MCP Server 标注版本——随着工具演进,应保持向后兼容或明确提升版本号,以避免破坏现有客户端配置。

Platform Compatibility

平台兼容性

FeatureClaude CodeCursorCodexGemini CLI
MCP client support✅ Native✅ Native⚠️ Limited⚠️ Limited
stdio transport✅ Full✅ Full⚠️ Custom⚠️ Custom
SSE transport✅ Full✅ Full⚠️ Custom⚠️ Custom
Tool discovery✅ Automatic✅ Automatic⚠️ Manual⚠️ Manual
OAuth support✅ Full✅ Full⚠️ Custom⚠️ Custom
功能Claude CodeCursorCodexGemini CLI
MCP 客户端支持✅ 原生✅ 原生⚠️ 有限⚠️ 有限
stdio 传输✅ 完整支持✅ 完整支持⚠️ 自定义⚠️ 自定义
SSE 传输✅ 完整支持✅ 完整支持⚠️ 自定义⚠️ 自定义
工具发现✅ 自动✅ 自动⚠️ 手动⚠️ 手动
OAuth 支持✅ 完整支持✅ 完整支持⚠️ 自定义⚠️ 自定义

Related Skills

相关 Skill

  • Multi-Model Routing - MCP servers can integrate model routing logic into tool execution pipelines
  • Knowledge Base Injection - Knowledge search tools are exposed through MCP for agent-accessible domain expertise
  • Parallel Agent Orchestration - MCP tools enable standardized tool access for parallel subagent dispatch
  • Shopping Ads - Merchant Center integration via MCP enables automated product feed management
  • Multi-Model Routing - MCP Server 可以将模型路由逻辑集成到工具执行流水线中
  • Knowledge Base Injection - 知识搜索工具通过 MCP 暴露,为 Agent 提供可访问的领域专业知识
  • Parallel Agent Orchestration - MCP 工具为并行 subagent 分发提供标准化工具访问能力
  • Shopping Ads - 通过 MCP 集成 Merchant Center,可实现商品信息源的自动化管理

Keywords

关键词

mcp-server, model-context-protocol, cloudflare-workers, tool-definitions, resource-handlers, sse-transport, stdio-transport, authentication, edge-deployment, agent-skills

© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License
mcp-server, model-context-protocol, cloudflare-workers, tool-definitions, resource-handlers, sse-transport, stdio-transport, authentication, edge-deployment, agent-skills

© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License