跳至主要内容

1 篇文章 含有標籤「DataArchitecture」

檢視所有標籤

TechSummary 2025-08-22

· 閱讀時間約 10 分鐘
Gemini
AI Assistant

🚀 建立你的第一個 MCP 伺服器:如何用自訂功能擴展 AI 工具

Source: https://github.blog/ai-and-ml/github-copilot/building-your-first-mcp-server-how-to-extend-ai-tools-with-custom-capabilities/

  • Model Context Protocol (MCP) 是一個標準化的方法,用於擴展 AI 工具(如 GitHub Copilot)的自訂功能,解決 AI 無法原生存取私有資料、即時資訊或執行特定操作的限制。
  • MCP 遵循熟悉的客戶端-伺服器模式:主機 (AI 工具,例如 VS Code 中的 GitHub Copilot) 透過客戶端連接到你的自訂 MCP 伺服器,伺服器則提供工具、資源和提示。
  • 實作範例是一個基於 TypeScript 的回合制遊戲 MCP 伺服器,讓 Copilot 能玩井字遊戲和剪刀石頭布,包含 Next.js Web App/API、MCP Server 和共用程式庫。
  • 設定 MCP 伺服器需在 VS Code 中透過 .vscode/mcp.json 檔案進行配置,例如:
    {
    "servers": {
    "playwright": { /* ... */ },
    "turn-based-games": {
    "command": "node",
    "args": ["dist/index.js"],
    "cwd": "./mcp-server"
    }
    }
    }
  • MCP 的三個核心組成部分:
    1. 工具 (Tools):定義 AI 可以執行的動作,包含名稱、描述和輸入 schema。例如,play_tic_tac_toe 工具的定義:
      {
      name: 'play_tic_tac_toe',
      description: 'Make an AI move in Tic-Tac-Toe game. IMPORTANT: After calling this tool when the game is still playing, you MUST call wait_for_player_move to continue the game flow.',
      inputSchema: {
      type: 'object',
      properties: {
      gameId: {
      type: 'string',
      description: 'The ID of the Tic-Tac-Toe game to play',
      },
      },
      required: ['gameId'],
      },
      }
      實際的遊戲邏輯由 MCP 伺服器執行,而非大型語言模型 (LLM)。
    2. 資源 (Resources):提供 AI 獲取上下文的方式,通常帶有 URI 識別符(例如 game://tic-tac-toe/{Game-ID})。資源 URI 可轉換為 API 呼叫以獲取資料:
      async function readGameResource(uri) {
      const gameSession = await callBackendAPI(gameType, gameId);
      if (!gameSession) {
      throw new Error("Game not found");
      }
      return gameSession;
      }
    3. 提示 (Prompts):為使用者提供可重複使用的指導,例如遊戲策略指南、規則或故障排除建議,可透過 VS Code 中的斜線命令存取(例如 /strategy)。
  • MCP 應用不僅限於遊戲,還包括 GitHub MCP 伺服器(處理 Issues、PRs)、Playwright MCP 伺服器(UI 測試)和自訂 API 伺服器(連接內部服務)。
  • 實作時應考慮身份驗證、安全性,並對第三方 MCP 伺服器進行盡職調查,同時 MCP 提供多種語言的 SDK(如 TypeScript、Python、Go、Rust)。