# MCP 服务器开发协议

* [MCP 协议文档](https://github.com/modelcontextprotocol/mcp)
* [MCP SDK 文档](https://github.com/modelcontextprotocol/sdk-js)
* [MCP 服务器示例](https://github.com/modelcontextprotocol/servers)

#### 其他资源 <a href="#additional-resources" id="additional-resources"></a>

```
if (this.requestsThisMinute >= 5) {
  console.error("[Rate Limit] Rate limit reached. Waiting for next minute...");
  return new Promise<void>((resolve) => {
    const remainingMs = 60 * 1000 - (Date.now() % (60 * 1000));
    setTimeout(resolve, remainingMs + 100); // Add 100ms buffer
  });
}
```

* 实施适当的速率限制
* 添加智能缓存
* 提供优雅降级
* 添加有关速率限制的透明错误

**解决方案** ：

**挑战** ：大多数 API 都有速率限制，这可能会导致失败。

**API 速率限制**

* 使用可用端点实现回退
* 在必要时创建模拟功能
* 转换 API 数据以满足您的需求

**解决方案** ：

**挑战** ：API 可能无法提供您需要的所有功能。

**缺少或有限的 API 功能**

```
// Authenticate using API key from environment
const API_KEY = process.env.ALPHAVANTAGE_API_KEY;
if (!API_KEY) {
  console.error("[Error] Missing ALPHAVANTAGE_API_KEY environment variable");
  process.exit(1);
}

// Initialize API client
const apiClient = new AlphaAdvantageClient({
  apiKey: API_KEY
});
```

复制

* 对于 API 密钥，请使用 MCP 配置中的环境变量
* 对于 OAuth，创建单独的脚本来获取刷新令牌
* 安全存储敏感令牌

**解决方案** ：

**挑战** ：API 通常具有不同的身份验证方法。

**API 身份验证的复杂性**

#### 常见挑战和解决方案 <a href="#common-challenges-and-solutions" id="common-challenges-and-solutions"></a>

资源使您的 MCP 服务器更加了解上下文，使 Cline-胜算云增强版无需您复制/粘贴即可访问特定信息。更多信息，请参阅[官方文档 ](https://modelcontextprotocol.io/docs/concepts/resources)。

```
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  if (request.params.uri === "file:///project/readme.md") {
    const content = await fs.promises.readFile("/path/to/readme.md", "utf-8");
    return {
      contents: [{
        uri: request.params.uri,
        mimeType: "text/markdown",
        text: content
      }]
    };
  }
  
  throw new Error("Resource not found");
});
```

1. **实现读取处理程序**来传递内容：

```
server.setRequestHandler(ListResourcesRequestSchema, async () => {
  return {
    resources: [
      {
        uri: "file:///project/readme.md",
        name: "Project README",
        mimeType: "text/markdown"
      }
    ]
  };
});
```

1. **定义您的服务器将公开的资源** ：

**向您的 MCP 服务器添加资源**

资源允许您的 MCP 服务器无需执行代码即可向Cline-胜算云增强版公开数据。它们非常适合提供 Cline-胜算云增强版在对话过程中可以引用的上下文信息，例如文件、API 响应或数据库记录。

#### MCP 资源 <a href="#mcp-resources" id="mcp-resources"></a>

```
try {
  switch (request.params.name) {
    case "get_stock_overview": {
      // Implementation...
    }
    
    // Other cases...
    
    default:
      throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`);
  }
} catch (error) {
  console.error(`[Error] Tool execution failed: ${error instanceof Error ? error.message : String(error)}`);
  
  if (error instanceof McpError) {
    throw error;
  }
  
  return {
    content: [{
      type: "text",
      text: `Error: ${error instanceof Error ? error.message : String(error)}`
    }],
    isError: true
  };
}
```

实施强大的错误处理以保持良好的用户体验：

**优雅的错误处理**

```
// Default cache TTL in seconds
const DEFAULT_CACHE_TTL = {
  STOCK_OVERVIEW: 60 * 60, // 1 hour
  TECHNICAL_ANALYSIS: 60 * 30, // 30 minutes
  FUNDAMENTAL_ANALYSIS: 60 * 60 * 24, // 24 hours
  EARNINGS_REPORT: 60 * 60 * 24, // 24 hours
  NEWS: 60 * 15, // 15 minutes
};

// Check cache first
const cachedData = this.cache.get<T>(cacheKey);
if (cachedData) {
  console.error(`[Cache] Using cached data for: ${cacheKey}`);
  return cachedData;
}

// Cache successful responses
this.cache.set(cacheKey, response.data, cacheTTL);
```

减少 API 调用并提高性能：

**智能缓存**

```
export interface AlphaAdvantageConfig {
  apiKey: string;
  cacheTTL?: Partial<typeof DEFAULT_CACHE_TTL>;
  baseURL?: string;
}

/**
 * Validate that a stock symbol is provided and looks valid
 */
function validateSymbol(symbol: unknown): asserts symbol is string {
  if (typeof symbol !== "string" || symbol.trim() === "") {
    throw new McpError(ErrorCode.InvalidParams, "A valid stock symbol is required");
  }
  
  // Basic symbol validation (letters, numbers, dots)
  const symbolRegex = /^[A-Za-z0-9.]+$/;
  if (!symbolRegex.test(symbol)) {
    throw new McpError(ErrorCode.InvalidParams, `Invalid stock symbol: ${symbol}`);
  }
}
```

类型定义可以防止错误并提高可维护性：

**强类型**

```
// Start-up logging
console.error('[Setup] Initializing AlphaAdvantage MCP server...');

// API request logging 
console.error(`[API] Getting stock overview for ${symbol}`);

// Error handling with context
console.error(`[Error] Tool execution failed: ${error.message}`);

// Cache operations
console.error(`[Cache] Using cached data for: ${cacheKey}`);
```

有效的日志记录对于调试 MCP 服务器至关重要：

**综合测井**

#### 核心实施最佳实践 <a href="#core-implementation-best-practices" id="core-implementation-best-practices"></a>

1. **规划 API 限制** ：从一开始就了解并围绕 API 速率限制进行设计
2. **策略性缓存** ：识别高价值缓存机会以提高性能
3. **可读性格式** ：投资良好的数据格式以改善用户体验
4. **测试每条路径** ：完成之前单独测试所有工具
5. **处理 API 复杂性** ：对于需要多次调用的 API，设计具有更简单范围的工具

AlphaAdvantage 的实施给我们带来了几个重要的教训：

**经验教训**

1. **API 速率限制** ：
   * **挑战** ：免费套餐每分钟仅限 5 次通话
   * **解决方案** ：实施排队、强制速率限制并添加全面缓存
2. **数据格式** ：
   * **挑战** ：原始 API 数据不够用户友好
   * **解决方案** ：创建格式化实用程序，以一致地显示财务数据
3. **超时问题** ：
   * **挑战** ：进行多次 API 调用的复杂工具可能会超时
   * **解决方案** ：建议将复杂的工具分解成更小的部分，优化缓存

在开发过程中，我们遇到了几个挑战：

**挑战与解决方案**

* **get\_stock\_overview** ：检索 AAPL 股票概览信息

  复制

  ```
  # AAPL (Apple Inc) - $241.84 ↑+1.91%

  **Sector:** TECHNOLOGY
  **Industry:** ELECTRONIC COMPUTERS
  **Market Cap:** 3.63T
  **P/E Ratio:** 38.26
  ...
  ```
* **get\_technical\_analysis** ：获取价格行为和 RSI 数据

  复制

  ```
  # Technical Analysis: AAPL

  ## Daily Price Action

  Current Price: $241.84 (↑$4.54, +1.91%)

  ### Recent Daily Prices

  | Date | Open | High | Low | Close | Volume |
  |------|------|------|-----|-------|--------|
  | 2025-02-28 | $236.95 | $242.09 | $230.20 | $241.84 | 56.83M |
  ...
  ```
* **get\_earnings\_report** ：检索 MSFT 收益历史记录和格式化报告

  复制

  ```
  # Earnings Report: MSFT (Microsoft Corporation)

  **Sector:** TECHNOLOGY
  **Industry:** SERVICES-PREPACKAGED SOFTWARE
  **Current EPS:** $12.43

  ## Recent Quarterly Earnings

  | Quarter | Date | EPS Estimate | EPS Actual | Surprise % |
  |---------|------|-------------|------------|------------|
  | 2024-12-31 | 2025-01-29 | $3.11 | $3.23 | ↑4.01% |
  ...
  ```

1. 然后我们分别测试了每个工具：

```
{
  "mcpServers": {
    "alphaadvantage-mcp": {
      "command": "node",
      "args": [
        "/path/to/alphaadvantage-mcp/build/index.js"
      ],
      "env": {
        "ALPHAVANTAGE_API_KEY": "YOUR_API_KEY"
      },
      "disabled": false,
      "autoApprove": []
    }
  }
}
```

1. 首先，我们在设置中配置 MCP 服务器：

这个关键阶段涉及系统地测试每个工具：

**测试阶段**

* 输入验证
* 具有错误处理的 API 客户端调用
* Markdown 格式的响应
* 综合日志记录

每个工具的处理程序包括：

```
server.setRequestHandler(ListToolsRequestSchema, async () => {
  console.error("[Setup] Listing available tools");
  
  return {
    tools: [
      {
        name: "get_stock_overview",
        description: "Get basic company info and current quote for a stock symbol",
        inputSchema: {
          type: "object",
          properties: {
            symbol: {
              type: "string",
              description: "Stock symbol (e.g., 'AAPL')"
            },
            market: {
              type: "string",
              description: "Optional market (e.g., 'US')",
              default: "US"
            }
          },
          required: ["symbol"]
        }
      },
      // Additional tools defined here...
    ]
  };
});
```

我们定义了五种具有清晰界面的工具：

**工具实现**

```
/**
 * Format company overview into markdown
 */
export function formatStockOverview(overviewData: any, quoteData: any): string {
  // Extract data
  const overview = overviewData;
  const quote = quoteData["Global Quote"];
  
  // Calculate price change
  const currentPrice = parseFloat(quote["05. price"] || "0");
  const priceChange = parseFloat(quote["09. change"] || "0");
  const changePercent = parseFloat(quote["10. change percent"]?.replace("%", "") || "0");
  
  // Format markdown
  let markdown = `# ${overview.Symbol} (${overview.Name}) - ${formatCurrency(currentPrice)} ${addTrendIndicator(priceChange)}${changePercent > 0 ? '+' : ''}${changePercent.toFixed(2)}%\n\n`;
  
  // Add more details...
  
  return markdown;
}
```

我们实现了格式化程序来美观地显示财务数据：

**Markdown 格式**

```
/**
 * Manage rate limiting based on free tier (5 calls per minute)
 */
private async enforceRateLimit() {
  if (this.requestsThisMinute >= 5) {
    console.error("[Rate Limit] Rate limit reached. Waiting for next minute...");
    return new Promise<void>((resolve) => {
      const remainingMs = 60 * 1000 - (Date.now() % (60 * 1000));
      setTimeout(resolve, remainingMs + 100); // Add 100ms buffer
    });
  }
  
  this.requestsThisMinute++;
  return Promise.resolve();
}
```

关键实施细节：

* **速率限制** ：强制执行每分钟 5 个请求的限制
* **缓存** ：通过策略缓存减少 API 调用
* **错误处理** ：强大的错误检测和报告
* **类型接口** ：清除所有数据的 TypeScript 类型

API 客户端实现包括：

**API 客户端实现**

```
src/
  ├── api/
  │   └── alphaAdvantageClient.ts  # API client with rate limiting & caching
  ├── formatters/
  │   └── markdownFormatter.ts     # Output formatters for clean markdown
  └── index.ts                     # Main MCP server implementation
```

接下来，我们构建了以下项目：

```
npx @modelcontextprotocol/create-server alphaadvantage-mcp
cd alphaadvantage-mcp
npm install axios node-cache
```

我们首先启动了这个项目：

<figure><img src="https://docs.cline.bot/~gitbook/image?url=https%3A%2F%2F3321249260-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Ff8Oh1Lcy6yWYq1caYESV%252Fuploads%252FZMEeCFXac5ijuBz5WhQE%252Fbuilding-mcp-plugin.gif%3Falt%3Dmedia%26token%3Ddb8410da-7af1-4201-b97e-418b617e7c1c&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=909d5f98&#x26;sv=2" alt=""><figcaption></figcaption></figure>

**执行**

1. **定义问题** ：用户需要通过他们的人工智能助手直接访问财务数据、股票分析和市场洞察
2. **选择的 API** ：用于金融市场数据的 AlphaAdvantage API
   * 标准 API 密钥认证
   * 每分钟 5 个请求的速率限制（免费套餐）
   * 不同财务数据类型的各种端点
3. **设计所需的工具** ：
   * 股票概览信息（当前价格、公司详情）
   * 利用指标进行技术分析（RSI、MACD 等）
   * 基本面分析（财务报表、比率）
   * 收益报告数据
   * 新闻和情绪分析
4. **计划数据格式** ：
   * 干净、格式良好的 Markdown 输出
   * 结构化数据表
   * 趋势的视觉指标（↑/↓）
   * 财务数字的正确格式

在规划阶段，我们：

![](https://docs.cline.bot/~gitbook/image?url=https%3A%2F%2F3321249260-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Ff8Oh1Lcy6yWYq1caYESV%252Fuploads%252FD8titDIv3ttw3PzMIR8P%252Fplanning-phase.gif%3Falt%3Dmedia%26token%3D8bc8ae34-f922-4c07-82ad-82e5eb3a3979\&width=768\&dpr=4\&quality=100\&sign=f5f2bae8\&sv=2)

**规划阶段**

让我们了解一下我们的 AlphaAdvantage MCP 服务器的开发过程，它提供股票数据分析和报告功能。

#### 案例研究：AlphaAdvantage 股票分析服务器 <a href="#case-study-alphaadvantage-stock-analysis-server" id="case-study-alphaadvantage-stock-analysis-server"></a>

* 设置项目结构
* 编写实现代码
* 配置设置
* 彻底测试每个组件
* 完成文档

规划完成后，Cline 帮助实施服务器：

**行动模式**

* 定义问题范围
* 选择合适的 API
* 规划身份验证方法
* 设计工具界面
* 确定数据格式

在此协作阶段，您将与 Cline 合作设计您的 MCP 服务器：

**计划模式**

#### 理解两种模式 <a href="#understanding-the-two-modes" id="understanding-the-two-modes"></a>

提供全面的 API 详细信息（端点、身份验证、数据结构）显著提高了 Cline 实现有效 MCP 服务器的能力。

```
Here's the API documentation for the service:
[Paste API documentation here]
```

帮助 Cline 构建您的 MCP 服务器的最有效方法之一是在开始时分享官方 API 文档：

**4.尽早提供 API 文档**

准备就绪后，使用聊天底部的开关切换到 ACT MODE 开始实施。

* 讨论问题范围
* 审查 API 文档
* 规划身份验证方法
* 设计工具界面

Cline 将自动以计划模式启动，指导您完成规划过程：

**3. 按照协议进行工作**

```
I want to build an MCP server for the AlphaAdvantage financial API.
It should allow me to get real-time stock data, perform technical 
analysis, and retrieve company financial information.
```

例如：

* MCP 服务器的用途
* 您想要集成哪个 API 或服务
* 您需要的任何特定工具或功能

在与 Cline-胜算云增强版聊天的开头，清晰地描述你想要构建的内容。具体来说：

**2. 用清晰的描述开始聊天**

首先，使用上述协议将 `.clinerules` 文件添加到 MCP 工作目录的根目录。此文件用于配置 Cline 在该文件夹中工作时使用 MCP 开发协议。

**1. 创建一个 `.clinerules` 文件（🚨重要）**

创建 MCP 服务器只需几个简单的步骤即可开始：

#### 入门 <a href="#getting-started" id="getting-started"></a>

1. 在实施之前，先从**计划模式**开始设计您的服务器
2. 在 **ACT 模式**下强制执行正确的实施模式
3. 要求在完成之前测试所有工具
4. 指导您完成整个开发生命周期

当此 `.clinerules` 文件存在于您的工作目录中时，Cline 将：

````
# MCP Server Development Protocol

⚠️ CRITICAL: DO NOT USE attempt_completion BEFORE TESTING ⚠️

## Step 1: Planning (PLAN MODE)
- What problem does this tool solve?
- What API/service will it use?
- What are the authentication requirements?
  □ Standard API key
  □ OAuth (requires separate setup script)
  □ Other credentials

## Step 2: Implementation (ACT MODE)
1. Bootstrap
   - For web services, JavaScript integration, or Node.js environments:
     ```bash
     npx @modelcontextprotocol/create-server my-server
     cd my-server
     npm install
     ```
   - For data science, ML workflows, or Python environments:
     ```bash
     pip install mcp
     # Or with uv (recommended)
     uv add "mcp[cli]"
     ```

2. Core Implementation
   - Use MCP SDK
   - Implement comprehensive logging
     - TypeScript (for web/JS projects):
       ```typescript
       console.error('[Setup] Initializing server...');
       console.error('[API] Request to endpoint:', endpoint);
       console.error('[Error] Failed with:', error);
       ```
     - Python (for data science/ML projects):
       ```python
       import logging
       logging.error('[Setup] Initializing server...')
       logging.error(f'[API] Request to endpoint: {endpoint}')
       logging.error(f'[Error] Failed with: {str(error)}')
       ```
   - Add type definitions
   - Handle errors with context
   - Implement rate limiting if needed

3. Configuration
   - Get credentials from user if needed
   - Add to MCP settings:
     - For TypeScript projects:
       ```json
       {
         "mcpServers": {
           "my-server": {
             "command": "node",
             "args": ["path/to/build/index.js"],
             "env": {
               "API_KEY": "key"
             },
             "disabled": false,
             "autoApprove": []
           }
         }
       }
       ```
     - For Python projects:
       ```bash
       # Directly with command line
       mcp install server.py -v API_KEY=key
       
       # Or in settings.json
       {
         "mcpServers": {
           "my-server": {
             "command": "python",
             "args": ["server.py"],
             "env": {
               "API_KEY": "key"
             },
             "disabled": false,
             "autoApprove": []
           }
         }
       }
       ```

## Step 3: Testing (BLOCKER ⛔️)

<thinking>
BEFORE using attempt_completion, I MUST verify:
□ Have I tested EVERY tool?
□ Have I confirmed success from the user for each test?
□ Have I documented the test results?

If ANY answer is "no", I MUST NOT use attempt_completion.
</thinking>

1. Test Each Tool (REQUIRED)
   □ Test each tool with valid inputs
   □ Verify output format is correct
   ⚠️ DO NOT PROCEED UNTIL ALL TOOLS TESTED

## Step 4: Completion
❗ STOP AND VERIFY:
□ Every tool has been tested with valid inputs
□ Output format is correct for each tool

Only after ALL tools have been tested can attempt_completion be used.

## Key Requirements
- ✓ Must use MCP SDK
- ✓ Must have comprehensive logging
- ✓ Must test each tool individually
- ✓ Must handle errors gracefully
- ⛔️ NEVER skip testing before completion
````

这是完整的 MCP 服务器开发协议，应放在您的 `.clinerules` 文件中：

* 配置 Cline-胜算云增强版的行为并实施最佳实践
* 将 Cline-胜算云增强版切换为专门的 MCP 开发模式
* 提供构建服务器的分步协议
* 实施安全措施，例如防止过早完成
* 指导您完成规划、实施和测试阶段

`.clinerules` 文件是一种特殊的配置，Cline 在其所在目录中工作时会自动读取它。这些文件：

**使用 `.clinerules` 文件**

高效 MCP 服务器开发的核心在于遵循结构化协议。该协议通过位于 MCP 工作目录**根目录** (/Users/your-name/Documents/Cline/MCP) 的 `.clinerules` 文件实现。

#### 开发协议 <a href="#the-development-protocol" id="the-development-protocol"></a>

没有 MCP，AI 助手虽然功能强大，但却显得孤立。有了 MCP，它们就能与几乎任何数字系统进行交互。

* 访问外部 API 和服务
* 检索实时数据
* 控制应用程序和本地系统
* 执行超出文本提示所能实现的操作

模型上下文协议 (MCP) 服务器扩展了 Cline 等 AI 助手的功能，使其能够：

#### 什么是 MCP 服务器？ <a href="#what-are-mcp-servers" id="what-are-mcp-servers"></a>

> 🚀 **搭建并与全世界分享您的 MCP 服务器。** 创建好 MCP 服务器后，请将其提交至 [Cline MCP 市场](https://github.com/cline/mcp-marketplace)让成千上万的开发人员可以发现它并一键安装它。

该协议旨在简化使用 Cline-胜算云增强版构建 MCP 服务器的开发过程。

[<br>](https://docs.cline.bot/custom-model-configs/aws-bedrock)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://modelmesh.gitbook.io/cline-zhong-wen-ban-docs/mcp-fu-wu-qi-kai-fa-xie-yi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
