mcpserver协议
一个Protobuf编译器插件,它根据Protobuf服务定义生成用于服务MCP(模型代码协议)工具的Go代码。
概述
该工具自动生成必要的Go代码,以使用工具工具创建MCP服务器,这些工具可供Claude等AI助手使用,所有这些都从原型定义开始。它使您能够:
- 使用协议缓冲区定义您的工具
- 自动生成必要的MCP服务器代码
- 仅实现服务方法的业务逻辑
安装
克隆此存储库并安装插件:
go install github.com/wricardo/protoc-gen-mcpserver@latest或者从源代码构建:
git clone https://github.com/wricardo/protoc-gen-mcpserver.git
cd protoc-gen-mcpserver
go install确保 protoc-gen-mcpserver 在你的路径。
用法
1.在.proto文件中定义您的服务
创建一个协议缓冲区文件,定义您的服务和消息类型:
syntax = "proto3";
package yourpackage;
option go_package = "yourmodule/yourpackage;yourpackage";
service YourService {
rpc YourMethod(YourRequest) returns (YourResponse);
}
message YourRequest {
string parameter1 = 1;
string parameter2 = 2;
}
message YourResponse {
string result = 1;
}2.配置buf.gen.yaml
使用 缓冲 从protobuf定义生成代码。创建一个 buf.gen.yaml 文件:
version: v2
managed:
enabled: true
plugins:
- name: go
out: ./
opt: paths=source_relative
- name: mcpserver
out: ./
opt: paths=source_relative3.生成代码
运行代码生成:
buf generate这将创建:
- 标准Go Protobuf代码
- 额外
.mcpserver.goMCP服务器集成文件
4.实施您的服务
创建一个实现生成代码中定义的接口的结构体:
package main
import (
"context"
"log"
. "yourmodule/yourpackage"
)
type YourServiceImpl struct {}
func (s *YourServiceImpl) YourMethod(ctx context.Context, req YourRequest) (*YourResponse, error) {
// Implement your business logic here
return &YourResponse{
Result: "Processed: " + req.Parameter1 + " " + req.Parameter2,
}, nil
}
func main() {
// Use the generated ServeStdio function to start the MCP server
err := ServeStdio("your-mcp-tool", "1.0.0", &YourServiceImpl{})
if err != nil {
log.Fatal(err)
}
}5.构建并运行MCP服务器
构建您的实现:
go build -o your-mcp-tool您的工具现在可以由MCP兼容的客户端执行。
运作原理
插件生成:
- 服务的接口定义
- 注册功能可将您的方法添加为MCP工具
- 通过stdio为MCP协议提供服务的辅助功能
gRPC服务中的每个方法都成为MCP工具,请求字段自动映射到工具参数。
示例
查看附带的示例,查看完整的工作实现:
cd example
buf generate
cd example-mcp
go build -o example-mcp
./example-mcp