使用说明
GoMCP-模型上下文协议Go库
一个功能强大、类型安全的Go库,用于构建MCP(模型上下文协议)服务器,支持多种传输和企业功能。
特性
- 多个传输:stdio、服务器发送事件(SSE)和流式HTTP
- 基于函数的处理程序:将常规Go函数注册为工具、资源和提示
- 类型安全:从Go函数签名自动生成JSON模式
- 验证:使用内置参数验证
validator/v10 - 简易API:针对不同用例的简单和高级API
- 企业就绪:身份验证、安全、缓存和监控(计划中)
快速开始
package main
import (
"context"
"log"
"github.com/dhirajsb/gomcp"
)
func main() {
// Quick API - simplest way to get started
err := gomcp.Quick().
Tool("add", Add).
Tool("search", SearchFiles).
Resource("status", GetStatus).
Prompt("greeting", GreetingPrompt).
Run() // Starts with stdio transport
log.Fatal(err)
}
func Add(ctx context.Context, a, b int) (int, error) {
return a + b, nil
}
func SearchFiles(ctx context.Context, query, directory string) ([]string, error) {
// Implementation
return []string{"file1.go", "file2.go"}, nil
}
func GetStatus(ctx context.Context) (string, error) {
return "Server is running", nil
}
func GreetingPrompt(ctx context.Context, name string) (string, error) {
return fmt.Sprintf("Hello %s! How can I help you today?", name), nil
}
高级用法
带验证的结构化参数
type SearchParams struct {
Query string `json:"query" validate:"required,min=1"`
Directory string `json:"directory,omitempty" validate:"omitempty,dir"`
MaxFiles int `json:"maxFiles,omitempty" validate:"omitempty,min=1,max=1000"`
FileTypes []string `json:"fileTypes,omitempty" validate:"dive,oneof=go js ts py"`
Recursive bool `json:"recursive,omitempty"`
}
type SearchResult struct {
Files []string `json:"files"`
Count int `json:"count"`
Truncated bool `json:"truncated"`
}
func AdvancedSearch(ctx context.Context, params SearchParams) (SearchResult, error) {
// Automatic validation of params based on struct tags
// Implementation
return SearchResult{}, nil
}
// Register with server
server.RegisterTool("advanced_search", AdvancedSearch)
多个传输
// Stdio transport (default for Claude Desktop)
server.Start(gomcp.Stdio())
// Server-Sent Events
server.Start(gomcp.SSE("localhost", 8080))
// Streamable HTTP (recommended for web)
server.Start(gomcp.StreamableHTTP("localhost", 8080))
完整服务器设置
package main
import (
"context"
"log"
"github.com/dhirajsb/gomcp"
)
func main() {
server := gomcp.NewServer()
// Register tools
server.RegisterTool("calculate", Calculate)
server.RegisterTool("search_files", SearchFiles)
// Register resources
server.RegisterResource("system_info", GetSystemInfo)
server.RegisterResource("file_content", GetFileContent)
// Register prompts
server.RegisterPrompt("code_review", CodeReviewPrompt)
server.RegisterPrompt("documentation", DocumentationPrompt)
// Start with HTTP transport
log.Fatal(server.Start(gomcp.StreamableHTTP("localhost", 8080)))
}
运输支持
标准运输
非常适合本地开发和Claude Desktop集成:
server.Start(gomcp.Stdio())
服务器发送事件(SSE)
对于传统web部署:
server.Start(gomcp.SSE("localhost", 8080))
流式HTTP
建议用于现代web部署:
server.Start(gomcp.StreamableHTTP("localhost", 8080))
例子
这 examples/ 目录包含完整的工作示例:
examples/simple/:基本功能注册examples/typed/:带验证的结构化参数examples/http/:带web界面的HTTP服务器
运行示例:
# Simple example with stdio
go run examples/simple/main.go
# Typed parameters example
go run examples/typed/main.go
# HTTP server example
go run examples/http/main.go
api参考
快速API
gomcp.Quick().
Tool("name", function). // Register tool
Resource("name", function). // Register resource
Prompt("name", function). // Register prompt
Run() // Start with stdio
// Or specify transport
gomcp.Quick().Tool("add", Add).RunHTTP("localhost", 8080)
API全文
server := gomcp.NewServer()
server.RegisterTool("name", function)
server.RegisterResource("name", function)
server.RegisterPrompt("name", function)
server.Start(transport)
交通建设者
gomcp.Stdio() // Stdio transport
gomcp.SSE("host", port) // SSE transport
gomcp.StreamableHTTP("host", port) // HTTP transport
函数签名
库支持各种函数签名:
工具
// Simple parameters
func Add(ctx context.Context, a, b int) (int, error)
// Struct parameters with validation
func Search(ctx context.Context, params SearchParams) (SearchResult, error)
// Multiple return values
func GetFileInfo(ctx context.Context, path string) (FileInfo, error)
资源
// String resource
func GetConfig(ctx context.Context) (string, error)
// Structured resource
func GetStatus(ctx context.Context) (ServerStatus, error)
// Parameterized resource
func GetFile(ctx context.Context, path string) (string, error)
鼓励
// Simple prompt
func Greeting(ctx context.Context, name string) (string, error)
// Structured prompt with multiple messages
func CodeReview(ctx context.Context, params ReviewParams) (PromptResult, error)
验证
使用结构体标签进行自动参数验证:
type Params struct {
Name string `json:"name" validate:"required,min=1,max=100"`
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"min=0,max=120"`
Tags []string `json:"tags" validate:"dive,min=1"`
}
支持的验证标签:
required-字段为必填项min=N,max=N-最小/最大值或长度email,url,uuid-格式验证oneof=a b c-必须是指定值之一dive-验证数组/切片元素
协议遵从
此库实现了模型上下文协议规范:
- JSON-RPC 2.0:完全符合JSON-RPC消息格式
- 标准方法:
initialize,tools/list,tools/call,resources/list,resources/read,prompts/list,prompts/get - 能力:适当的能力协商和特征检测
- 错误处理:标准错误代码和消息
贡献
- 分叉存储库
- 创建要素分支
- 进行更改
- 添加测试
- 提交拉取请求
许可证
MIT许可证-有关详细信息,请参阅许可证文件。
路线图
- [x] 核心MCP协议实现
- [x] 多种传输支持(stdio、SSE、HTTP)
- [x] 基于函数的处理程序
- [x] 类型安全和验证
- []身份验证和授权
- []中间件支持
- []缓存和性能优化
- []全面的日志记录和指标
- []WebSocket传输
- []客户端实现