MCP服务器示例

一个使用Go语言实现的Model Context Protocol (MCP)服务器示例,用于与AI助手(如Claude)集成,提供工具服务。

  • by WeiWeiWesley
  • Go
  • 本地部署
  • 更新于
在 GitHub 查看 WeiWeiWesley/mcp-server-example

使用说明

Golang MCP Server 範例

使用 Go 語言實作的 Model Context Protocol (MCP) server 範例,展示如何建立可與 AI 助手(如 Claude)整合的工具服務。

什麼是 MCP?

MCP (Model Context Protocol) 定義了 AI 與外部工具之間的標準通訊協議。

互動層級與角色

┌─────────────────────────────────────────────────┐
│                   使用者 (你)                    │
│              "請幫我計算 5 + 3"                  │
└─────────────────┬───────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────┐
│            AI 助手 (Claude Code)                │
│  • 理解使用者意圖                                │
│  • 決定需要使用哪個工具                          │
│  • 呼叫 MCP Server 的工具                       │
└─────────────────┬───────────────────────────────┘
                  │ MCP 協議
                  │ (JSON-RPC 2.0)
                  ▼
┌─────────────────────────────────────────────────┐
│          MCP Server (本範例實作)                │
│  • 提供工具清單                                  │
│  • 執行具體的工具邏輯                            │
│  • 返回執行結果                                  │
│                                                 │
│  可用工具:                                       │
│  • add - 加法計算                               │
│  • multiply - 乘法計算                          │
│  • greet - 產生問候訊息                         │
└─────────────────────────────────────────────────┘

角色說明:

  • 使用者:提出需求
  • AI 助手:理解需求,決定使用哪個工具(MCP Client)
  • MCP Server:提供並執行具體工具,返回結果

這個範例展示如何實作 MCP Server 端。

快速開始

1. 編譯

cd mcp-server-example
./build.sh

2. 整合到 Claude Code

claude mcp add golang-example /path/to/mcp-server-example/mcp-server

3. 測試

在 Claude Code 中:

請用 add 工具計算 15 + 27
請用 multiply 工具計算 6 × 8
請用 greet 工具跟我打招呼

程式架構

main.go                    # 核心實作(含詳細中文註解)
├── JSON-RPC 結構         # 基礎通訊協議
├── MCP 協議結構          # 初始化、能力聲明
├── Tool 工具系統         # 工具定義與執行
└── Server 主循環         # stdin/stdout 通訊

運作原理

MCP Server 透過 標準輸入/輸出 (stdin/stdout) 與客戶端通訊:

1. 客戶端發送: {"method":"initialize",...}
2. Server 回應: 支援的功能列表
3. 客戶端呼叫: {"method":"tools/list"}
4. Server 回應: [add, multiply, greet]
5. 客戶端呼叫: {"method":"tools/call","params":{...}}
6. Server 執行並返回結果

💡 關鍵: stdout 用於 JSON-RPC 通訊,stderr 用於日誌輸出

手動測試

啟動 server:

./mcp-server

發送請求(每行一個 JSON):

{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}
{"jsonrpc":"2.0","id":2,"method":"tools/list"}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add","arguments":{"a":5,"b":3}}}

擴充工具

在 main.go 中:

  1. 定義工具 (在 handleListTools):
{
    Name:        "subtract",
    Description: "Subtract two numbers",
    InputSchema: InputSchema{
        Type: "object",
        Properties: map[string]Property{
            "a": {Type: "number", Description: "被減數"},
            "b": {Type: "number", Description: "減數"},
        },
        Required: []string{"a", "b"},
    },
}
  1. 實作邏輯 (在 handleCallTool):
case "subtract":
    var args struct {
        A float64 `json:"a"`
        B float64 `json:"b"`
    }
    json.Unmarshal(callParams.Arguments, &args)
    result := CallToolResult{
        Content: []ContentItem{{
            Type: "text",
            Text: fmt.Sprintf("%.2f - %.2f = %.2f", args.A, args.B, args.A - args.B),
        }},
    }
  1. 重新編譯:
./build.sh

除錯技巧

查看 server 日誌:

./mcp-server 2> debug.log

檢查是否正確啟動:

claude mcp list
# 應該顯示: golang-example - ✓ Connected

檔案說明

  • main.go - Server 核心實作(含詳細中文註解)
  • build.sh - 編譯腳本
  • mcp.json - 基本配置範例
  • claude_desktop_config.json - Claude Desktop 配置範例
  • README.md - 完整文件
  • README_SIMPLE.md - 本檔案(簡潔版)

進階主題

  • Resources: 提供檔案、資料等資源給 AI 讀取
  • Prompts: 提供預設的提示模板
  • 動態工具: 根據情境動態改變可用工具

詳見 README.md 的完整說明。

參考資源


💡 提示: 閱讀 main.go 的中文註解,可以深入理解 MCP 的運作原理!