如何用 go 搭建 MCP 服務

1. 什麼是 MCP?

MCP 是 “模型上下文協議(Model Context Protocol)” 的簡稱,用一句簡單通俗易懂的話描述:

是一種讓 AI 模型能夠無縫連接到外部工具和數據源的標準化方式。想象它就像 AI 的“萬能接口”,能讓 AI 像用 USB 線連接設備一樣,輕鬆調用其他程序或服務。

2. 官方 MCP 架構圖

3.MCP 原理圖

順便貼一下我用 mermaid 畫的 MCP 原理圖 mermaid:

sequenceDiagram
autonumber
actor 用戶
participant Client as 客戶端<br>(Cursor)
participant LLM as LLM<br>(Claude-3.7)
participant MCP as MCP服務
participant 遠程 as 遠程服務<br>(Web Api)
rect rgb(255, 255, 0)
	Note over Client,MCP:初始化階段
	Client->>MCP:註冊並啓動MCP服務
	MCP-->>Client:服務註冊成功
end
rect rgb(255, 255, 0)
	Note over 用戶,遠程:交互流程
	用戶->>Client:輸入內容
	Client->>LLM:將用戶輸入的內容提交給LLM
	Note over LLM:分析用戶內容,<br>並決定是否需要<br>調用MCP
	LLM-->>LLM: 
	rect rgb(155, 255, 155)
		alt 需要調用MCP
				LLM->>Client:請求客戶端調用特定MCP工具
				Client->>MCP:調用MCP服務,執行特定動作
				MCP->>遠程:調用遠程Api服務
				遠程-->>MCP:返回遠程結果
				MCP-->>Client:返回結果給客戶端
				Client->>LLM:將MCP返回結果或動作作爲上下文再次請求LLM	
		else 不需要調用MCP
				Note over LLM:直接返回大模型輸出結果
		end
	end
	LLM-->>Client:輸出內容給客戶端
	Client-->>用戶:顯示回答內容
end

4. 編譯 go MCP 服務

步驟 1:創建項目和 main.go

mkdir mcp-server
cd mcp-server
vim main.go
#在main.go中添加如下內容
package main

import (
    "context"
    "errors"
    "fmt"

    "github.com/mark3labs/mcp-go/mcp"
    "github.com/mark3labs/mcp-go/server"
)

func main() {
    // Create a new MCP server
    s := server.NewMCPServer(
        "Calculator Demo",
        "1.0.0",
        server.WithResourceCapabilities(true, true),
        server.WithLogging(),
        server.WithRecovery(),
    )

    // Add a calculator tool
    calculatorTool := mcp.NewTool("calculate",
        mcp.WithDescription("Perform basic arithmetic operations"),
        mcp.WithString("operation",
            mcp.Required(),
            mcp.Description("The operation to perform (add, subtract, multiply, divide)"),
            mcp.Enum("add", "subtract", "multiply", "divide"),
        ),
        mcp.WithNumber("x",
            mcp.Required(),
            mcp.Description("First number"),
        ),
        mcp.WithNumber("y",
            mcp.Required(),
            mcp.Description("Second number"),
        ),
    )

    // Add the calculator handler
    s.AddTool(calculatorTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
        op := request.Params.Arguments["operation"].(string)
        x := request.Params.Arguments["x"].(float64)
        y := request.Params.Arguments["y"].(float64)

        var result float64
        switch op {
        case "add":
            result = x + y
        case "subtract":
            result = x - y
        case "multiply":
            result = x * y
        case "divide":
            if y == 0 {
                return nil, errors.New("Cannot divide by zero")
            }
            result = x / y
        }

        return mcp.NewToolResultText(fmt.Sprintf("%.2f", result)), nil
    })

    // Start the server
    if err := server.ServeStdio(s); err != nil {
        fmt.Printf("Server error: %v\n", err)
    }
}

步驟 2:編譯

#初始化依賴包
go mod init
#加載依賴包
go mod tidy
#編譯
go build -o mcpServer main.go
#查看目錄文件
ls -l
#查看文件路徑path
pwd
#如下:

步驟 3:在 Cursor 中配置 MCP 命令

Command + Shift + J 打開 Cursor 配置命令,如下圖所示,在 json 配置中添加如下內容:
       

{
  "mcpServers": {
    "calculate": {
      "command": "/Users/xxx(你的項目路徑)/src/mcp-service/mcpServer"
    }
  }
}

其中 calculate 表示的是本地 MCP 工具的名稱,command是需要執行的命令路徑。

5. 在 Cursor 中調用 MCP 服務

使用MCP calculate工具,若 x = 120,y = 30 ,x + y 、x * y 、x /y 分別等於多少?

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/6j3q4LAOvCgUo54xE_Y5Vg