
前面我们介绍了如何使用buf加上proto-gen-go-mcp工具实现mcp-server代码的生成,并且介绍了最基础的一种本地实现代码的方式。本节介绍下剩余两种方式的同时,也介绍下如何手撸生成mcp-server代码。首先我们定义下我们的proto文件:example.proto
syntax = "proto3";
package example;
option go_package="example.v1";
// 定义一个简单的消息
message Person {
string name = 1;
int32 id = 2;
string email = 3;
}
然后定义service的proto:example_service.proto
syntax = "proto3";
package example;
import "example.proto";
import "google/api/annotations.proto";
option go_package="example.service.v1";
service ExampleService {
rpc GetPerson (PersonRequest) returns (PersonResponse){
option (google.api.http) = {
get: "/api/v1/GetPerson"
};
};
}
message PersonRequest {
string name = 1;
}
message PersonResponse {
Person person = 1;
}接着我们生成代码
protoc --go_out=. --connect-go_out=. --go-mcp_out=. example.proto
protoc -I. -I/third/ --go_out=. --go-grpc_out=. --connect-go_out=. --go-mcp_out=. example_service.proto生成的代码和前一篇类似,这里就不详细介绍了,本质上只是把buf的自动化过程给手动实现了一遍。
接着实现STDIO版本的server
package main
import (
"context"
"errors"
"fmt"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
example "learn/langchain/protoc_gen_mcp/exp1/server"
)
func main() {
s := server.NewMCPServer(
"mcp-person",
"1.0.0",
)
// 注册服务
example.RegisterExampleService(s, &example.Server{})
addTool(s)
// 启动服务器
fmt.Println("Starting server...")
if err := server.ServeStdio(s); err != nil {
fmt.Println("Failed to serve:", err)
}
}
func addTool(s *server.MCPServer) {
calculatorTool := mcp.NewTool("calculate",
mcp.WithDescription("执行基本的算术运算"),
mcp.WithString("operation",
mcp.Required(),
mcp.Description("要执行的算术运算类型"),
mcp.Enum("add", "subtract", "multiply", "divide"), // 保持英文
),
mcp.WithNumber("x",
mcp.Required(),
mcp.Description("第一个数字"),
),
mcp.WithNumber("y",
mcp.Required(),
mcp.Description("第二个数字"),
),
)
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("不允许除以零")
}
result = x / y
}
return mcp.FormatNumberResult(result), nil
})
}可以看到,这里可以支持添加我们生成的MCP 代码也同时支持老的手动实现MCP server tool的方式。
本文分享自 golang算法架构leetcode技术php 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!