模型上下文协议允许应用程序以标准化的方式为LLMs提供上下文,将提供上下文的关注点与实际的LLM交互分离。这个Golang SDK实现了完整的MCP规范,使其易于:
注意: 此SDK会定期更新,以符合来自spec.modelcontextprotocol.io/latest的最新MCP规范。
go get github.com/FreePeak/golang-mcp-server-sdk
让我们创建一个简单的MCP服务器,它暴露一个回声工具:
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/FreePeak/golang-mcp-server-sdk/pkg/server"
"github.com/FreePeak/golang-mcp-server-sdk/pkg/tools"
)
func main() {
// 创建服务器
mcpServer := server.NewMCPServer("Echo Server Example", "1.0.0")
// 创建一个回声工具
echoTool := tools.NewTool("echo",
tools.WithDescription("回声返回输入的消息"),
tools.WithString("message",
tools.Description("要回声返回的消息"),
tools.Required(),
),
)
// 将工具添加到服务器并附带处理函数
ctx := context.Background()
err := mcpServer.AddTool(ctx, echoTool, handleEcho)
if err != nil {
log.Fatalf("添加工具时出错:%v", err)
}
// 启动服务器
fmt.Println("启动回声服务器...")
fmt.Println("通过标准输入发送JSON-RPC消息来与服务器进行交互。")
// 在标准输入输出上服务
if err := mcpServer.ServeStdio(); err != nil {
fmt.Fprintf(os.Stderr, "错误:%v\n", err)
os.Exit(1)
}
}
// 回声工具处理函数
func handleEcho(ctx context.Context, request server.ToolCallRequest) (interface{}, error) {
// 提取消息参数
message, ok := request.Parameters["message"].(string)
if !ok {
return nil, fmt.Errorf("缺少或无效的'message'参数")
}
// 返回MCP协议期望的回声响应格式
return map[string]interface{}{
"content": []map[string]interface{}{
{
"type": "text",
"text": message,
},
},
}, nil
}
模型上下文协议(MCP)是一个标准化协议,允许应用程序以安全高效的方式为LLMs提供上下文。它将提供上下文和工具的关注点与实际的LLM交互分离。MCP服务器可以:
MCP服务器是您与MCP协议的核心接口。它处理连接管理、协议合规性和消息路由:
// 创建一个新的MCP服务器
mcpServer := server.NewMCPServer("My App", "1.0.0")
工具让LLMs通过您的服务器采取行动。与资源不同,工具预期执行计算并具有副作用:
// 定义一个计算器工具
calculatorTool := tools.NewTool("calculator",
tools.WithDescription("执行基本算术运算"),
tools.WithString("operation",
tools.Description("要执行的操作(加、减、乘、除)"),
tools.Required(),
),
tools.WithNumber("a",
tools.Description("第一个数字"),
tools.Required(),
),
tools.WithNumber("b",
tools.Description("第二个数字"),
tools.Required(),
),
)
// 将工具添加到服务器并附带处理函数
mcpServer.AddTool(ctx, calculatorTool, handleCalculator)
资源是您向LLMs暴露数据的方式。它们类似于REST API中的GET端点——它们提供数据但不应执行显著计算或具有副作用:
// 创建一个资源(当前使用内部API)
resource := &domain.Resource{
URI: "sample://hello-world",
Name: "Hello World Resource",
Description: "用于演示目的的样本资源",
MIMEType: "text/plain",
}
// 注意:资源支持正在公共API中更新
提示是可重用模板,帮助LLMs有效地与您的服务器交互:
// 创建一个提示(当前使用内部API)
codeReviewPrompt := &domain.Prompt{
Name: "review-code",
Description: "代码审查提示",
Template: "请审查以下代码:\n\n{{.code}}",
Parameters: []domain.PromptParameter{
{
Name: "code",
Description: "要审查的代码",
Type: "string",
Required: true,
},
},
}
// 注意:提示支持正在公共API中更新
根据您的使用情况,Go中的MCP服务器可以连接到不同的传输方式:
对于命令行工具和直接集成:
// 启动一个标准输入输出服务器
if err := mcpServer.ServeStdio(); err != nil {
fmt.Fprintf(os.Stderr, "错误:%v\n", err)
os.Exit(1)
}
对于Web应用,您可以使用服务器发送事件(SSE)进行实时通信:
// 配置HTTP地址
mcpServer.SetAddress(":8080")
// 启动带有SSE支持的HTTP服务器
if err := mcpServer.ServeHTTP(); err != nil {
log.Fatalf("HTTP服务器错误:%v", err)
}
// 优雅关闭
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := mcpServer.Shutdown(ctx); err != nil {
log.Fatalf("服务器关闭错误:%v", err)
}
您还可以同时运行多个协议服务器:
// 配置服务器以同时支持HTTP和标准输入输出
mcpServer := server.NewMCPServer("Multi-Protocol Server", "1.0.0")
mcpServer.SetAddress(":8080")
mcpServer.AddTool(ctx, echoTool, handleEcho)
// 在goroutine中启动HTTP服务器
go func() {
if err := mcpServer.ServeHTTP(); err != nil {
log.Fatalf("HTTP服务器错误:%v", err)
}
}()
// 在主线程中启动标准输入输出服务器
if err := mcpServer.ServeStdio(); err != nil {
log.Fatalf("标准输入输出服务器错误:%v", err)
}
为了测试您的MCP服务器,您可以使用MCP Inspector或直接发送JSON-RPC消息:
# 使用标准输入测试回声工具
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"echo","parameters":{"message":"Hello, World!"}}}' | go run your_server.go
查看examples目录以获取完整的示例服务器:
在examples/echo_server.go中有一个简单的回声服务器示例:
# 运行示例
go run examples/echo_server.go
在examples/calculator/中有一个更高级的计算器示例,支持HTTP和标准输入输出两种模式:
# 在HTTP模式下运行
go run examples/calculator/main.go --mode http
# 在标准输入输出模式下运行
go run examples/calculator/main.go --mode stdio
SDK遵循干净架构原则组织:
golang-mcp-server-sdk/
├── pkg/ # 公共API(供用户使用)
│ ├── builder/ # 服务器构建的公共构建模式
│ ├── server/ # 公共服务器实现
│ ├── tools/ # 创建MCP工具的实用程序
│ └── types/ # 共享类型和接口
├── internal/ # 私有实现细节
├── examples/ # 示例代码片段和用例
└── cmd/ # 示例MCP服务器应用程序
pkg/目录包含了SDK的所有公开API,用户应与此交互。
欢迎贡献!请随时提交Pull Request。
本项目采用MIT许可证——详情见LICENSE文件。