返回產品博客

使用 TypeScript 構建生產級 MCP 服務器:完整實戰指南

本文發佈於 2024年11月14日。產品當前能力參見產品能力。

使用 TypeScript 構建生產級 MCP 服務器:完整實戰指南

隨著 Claude 等 AI 助手的普及,開發者面臨著一個新的挑戰:如何使用自定義工具和集成來擴展 AI 的能力?

答案就在**模型上下文協議(MCP)**中。藉助現代 TypeScript 框架,構建 MCP 服務器從未如此簡單。無論你是想為 AI 添加數據庫查詢能力、集成第三方 API,還是創建專屬的業務工具,MCP 都能讓這一切變得輕而易舉。

什麼是模型上下文協議?

在深入實現之前,讓我們先了解 MCP 是什麼。

模型上下文協議是一種標準化的方式,使 AI 應用程序能夠與外部工具、資源和數據源進行交互。可以把它想像成 AI 模型和你的自定義功能之間的橋梁。

通過 MCP,AI 助手能夠:

  • 執行自定義工具 - 執行特定操作,如計算、API 調用或數據處理
  • 訪問動態資源 - 從數據庫、文件或外部服務獲取實時數據
  • 使用上下文提示 - 根據你的業務邏輯生成智能響應

為什麼選擇 TypeScript 開發 MCP 服務器?

TypeScript 為 MCP 服務器開發帶來了多個優勢:

  1. 類型安全 - 在編譯時而非運行時捕獲錯誤
  2. 智能提示支持 - 通過自動補全提供更好的開發體驗
  3. 可擴展性 - 更容易維護和重構大型代碼庫
  4. 現代 JavaScript 特性 - 利用 async/await、裝飾器等功能

入門實戰:創建你的第一個 MCP 服務器

現在讓我們動手實踐!我們將構建一個簡單但實用的計算器工具,讓 Claude 能夠執行數學運算。

第一步:安裝依賴

首先,使用 npm 安裝所需的包:

npm install @zhama/mcp-server

第二步:創建計算器工具

以下是如何使用裝飾器創建一個簡單的計算器工具。代碼非常直觀,即使是初學者也能輕鬆理解:

import { createMCPServer, BaseTool, Tool } from '@zhama/mcp-server';

@Tool({
  name: 'calculator',
  description: '执行基本算术运算',
  parameters: [
    { 
      name: 'operation', 
      type: 'string', 
      description: '运算类型:add(加)、subtract(减)、multiply(乘)或 divide(除)', 
      required: true 
    },
    { 
      name: 'a', 
      type: 'number', 
      description: '第一个数字', 
      required: true 
    },
    { 
      name: 'b', 
      type: 'number', 
      description: '第二个数字', 
      required: true 
    }
  ]
})
class CalculatorTool extends BaseTool {
  protected toolDefinition = {
    name: 'calculator',
    description: '执行基本算术运算',
    parameters: []
  };

  protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
    const { operation, a, b } = params as { 
      operation: string; 
      a: number; 
      b: number 
    };
    
    const operations = {
      add: () => a + b,
      subtract: () => a - b,
      multiply: () => a * b,
      divide: () => b !== 0 ? a / b : '错误:除数不能为零'
    };
    
    return { result: operations[operation]() };
  }
}

第三步:啟動服務器

最後一步,創建服務器實例並啟動它:

async function main() {
  const server = createMCPServer('calculator-server', '1.0.0')
    .description('为 AI 助手提供的强大计算器')
    .enableTools()
    .addTool(new CalculatorTool());

  await server.runStdio();
}

main().catch(console.error);

生產環境的高級特性

1. 資源管理

資源允許你的 AI 訪問動態內容。以下是一個獲取用戶數據的資源示例:

class UserDataResource extends BaseResource {
  protected resourceDefinition = {
    type: 'application/json' as const,
    description: '访问用户资料信息'
  };

  protected async executeInternal(userId: string): Promise<Resource> {
    const userData = await fetchUserFromDatabase(userId);
    
    return {
      id: `user-${userId}`,
      uri: `resource://users/${userId}`,
      name: `用户资料:${userData.name}`,
      type: 'application/json',
      content: JSON.stringify(userData)
    };
  }
}

2. 智能提示

創建上下文提示,幫助 AI 理解你的業務領域:

class DocumentAnalysisPrompt extends BasePrompt {
  protected promptDefinition = {
    type: 'text' as const,
    description: '生成文档分析指令'
  };

  protected async executeInternal(documentType: string): Promise<Prompt> {
    const instructions = generateAnalysisInstructions(documentType);
    
    return {
      id: `analysis-${documentType}`,
      name: `分析${documentType}`,
      type: 'text',
      content: instructions
    };
  }
}

3. 生產環境服務器配置

對於生產部署,配置日誌記錄、錯誤處理和多種功能:

const server = createMCPServer('production-server', '2.0.0')
  .description('生产级 MCP 服务器')
  .author('您的公司')
  .license('MIT')
  .enableTools({ listChanged: true })
  .enableResources({ subscribe: true, listChanged: true })
  .enablePrompts({ listChanged: true })
  .enableLogging('info')
  .addTool(new CalculatorTool())
  .addResource(new UserDataResource())
  .addPromptGenerator('analysis', async (type) => {
    return await generatePrompt(type);
  });

// 用于 Claude Desktop - 使用 STDIO
await server.runStdio();

// 用于 Web 应用 - 使用 SSE
await server.runSSE(3000);

與 Claude Desktop 集成

要在 Claude Desktop 中使用你的 MCP 服務器,需要將其添加到配置文件:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "calculator": {
      "command": "node",
      "args": ["/path/to/your/built/server.js", "--stdio"]
    }
  }
}

重啟 Claude Desktop 後,你的工具就可以被 AI 助手使用了!

MCP 服務器開發最佳實踐

1. 類型安全優先

始終為參數和返回值定義適當的 TypeScript 類型:

interface CalculationParams {
  operation: 'add' | 'subtract' | 'multiply' | 'divide';
  a: number;
  b: number;
}

interface CalculationResult {
  result: number;
  operation: string;
}

2. 錯誤處理

實現全面的錯誤處理:

protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
  try {
    // 验证输入
    if (!isValidOperation(params.operation)) {
      throw new Error('无效的运算类型');
    }
    
    // 执行逻辑
    return await performCalculation(params);
  } catch (error) {
    this.logger.error('计算失败', error);
    throw new Error(`计算失败:${error.message}`);
  }
}

3. 文檔編寫

清晰地記錄你的工具,讓 AI 理解何時以及如何使用它們:

@Tool({
  name: 'send_email',
  description: '向收件人发送电子邮件。当用户要求发送邮件或给某人发消息时使用此工具。',
  parameters: [
    { 
      name: 'to', 
      type: 'string', 
      description: '收件人的电子邮件地址', 
      required: true 
    },
    { 
      name: 'subject', 
      type: 'string', 
      description: '邮件主题', 
      required: true 
    },
    { 
      name: 'body', 
      type: 'string', 
      description: '邮件正文内容', 
      required: true 
    }
  ]
})

真實應用場景

1. 數據庫集成

創建允許 AI 安全查詢數據庫的工具:

@Tool({
  name: 'query_customer_data',
  description: '通过邮箱或 ID 搜索客户记录',
  parameters: [/* ... */]
})
class CustomerQueryTool extends BaseTool {
  // 实现时要注意 SQL 注入防护
}

2. API 集成

將 AI 連接到外部服務:

@Tool({
  name: 'check_weather',
  description: '获取指定位置的当前天气',
  parameters: [/* ... */]
})
class WeatherTool extends BaseTool {
  // 调用天气 API 的实现
}

3. 文件處理

使 AI 能夠處理文件:

@Tool({
  name: 'analyze_document',
  description: '从文档中提取和分析内容',
  parameters: [/* ... */]
})
class DocumentAnalyzerTool extends BaseTool {
  // 文档处理的实现
}

性能優化

異步操作

利用 TypeScript 的 async/await 實現最佳性能:

protected async executeInternal(params: Record<string, unknown>): Promise<unknown> {
  // 并行执行
  const [userData, preferences, history] = await Promise.all([
    fetchUserData(params.userId),
    fetchUserPreferences(params.userId),
    fetchUserHistory(params.userId)
  ]);
  
  return { userData, preferences, history };
}

緩存機制

為頻繁訪問的資源實現緩存:

private cache = new Map<string, CachedData>();

protected async executeInternal(key: string): Promise<unknown> {
  if (this.cache.has(key)) {
    return this.cache.get(key);
  }
  
  const data = await fetchExpensiveData(key);
  this.cache.set(key, data);
  return data;
}

測試你的 MCP 服務器

始終全面測試你的工具:

import { CalculatorTool } from './calculator';

describe('CalculatorTool', () => {
  it('应该正确地将两个数字相加', async () => {
    const tool = new CalculatorTool();
    const result = await tool.execute({
      operation: 'add',
      a: 5,
      b: 3
    });
    
    expect(result.result).toBe(8);
  });
});

部署注意事項

環境變量

使用環境變量進行配置:

const server = createMCPServer('my-server', '1.0.0')
  .enableLogging(process.env.LOG_LEVEL || 'info');

Docker 支持

容器化你的 MCP 服務器:

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
CMD ["node", "dist/server.js", "--stdio"]

總結

使用 TypeScript 構建 MCP 服務器為擴展 AI 能力開啟了無限可能。無論你是集成數據庫、外部 API,還是自定義業務邏輯,基於裝飾器的方法都使開發變得直觀且易於維護。

關鍵要點:

  • 從簡單開始 - 從基本工具開始,逐步增加複雜性
  • 類型安全很重要 - 利用 TypeScript 的類型系統提高可靠性
  • 關注用戶體驗 - 設計 AI 易於理解和使用的工具
  • 生產就緒 - 從一開始就實現日誌記錄、錯誤處理和監控

準備好構建自己的 MCP 服務器了嗎?可能性是無限的。從客戶服務自動化到數據分析工具,MCP 服務器是連接 AI 智能與你獨特業務需求的橋梁。

額外資源


有問題或想分享你的 MCP 服務器實現?加入我們的社區討論!

微信交流群二維碼 微信公眾號二維碼