使用说明
MCP Go
什么是MCP?
MCP(模型上下文协议)是一种轻量级、灵活的协议,旨在实现人工智能模型和应用程序之间的高效通信。它为服务提供了一种标准化的方式来交换消息、工具和资源,同时保持高性能和可靠性。
关于此套餐
MCP Go是模型上下文协议的Go实现,为AI通信提供了一个强大的框架:
- 客户端-服务器体系结构:完成客户端和服务器组件的实施
- 运输灵活性:通过标准I/O、WebSockets或HTTP无缝通信
- 并行设计:使用Go的goroutines和频道从头开始构建
- 类型安全API:在整个代码库中进行强键入,以防止运行时错误
- 模块化组件:基于处理程序的可扩展性和可维护性设计模式
- 会话管理:具有适当生命周期处理的持久连接
用法
共同模式
所有MCP Go实现都遵循类似的模式:
package main
import (
"github.com/OkutaniDaichi0106/mcp-go/mcp"
)
func main() {
server := mcp.NewServer()
// Tool registration
mcp.HandleToolFunc(&mcp.ToolDefinition{
Name: "tool_name",
Description: "Tool description",
InputSchema: mcp.InputSchema(`{ "type": "object", ... }`),
}, func(w mcp.ContentsWriter, name string, args map[string]any) {
// Tool implementation
// ...
w.WriteContents(contents)
})
// Resource registration
mcp.HandleResourceFunc(&mcp.ResourceDefinition{
URI: "resource_uri",
MimeType: "resource_mime_type",
Name: "resource_name",
Description: "Resource description",
}, func(w mcp.ContentsWriter, uri string) {
// Resource implementation
// ...
w.WriteContents(contents)
})
// Prompt registration
mcp.HandlePromptFunc(&mcp.PromptDefinition{
Name: "prompt_name",
Description: "Prompt description",
InputSchema: mcp.InputSchema(`{ "type": "object", ... }`),
}, func(w mcp.PromptWriter, name string, args map[string]any) {
// Prompt implementation
// ...
w.WriteContents(contents)
})
transport, err := ... // Create transport
// Configure transport and accept -> get session
session, err := server.Accept(transport)
defer session.Close()
// ...
}
package main
import (
"github.com/OkutaniDaichi0106/mcp-go/mcp"
)
func main() {
// Sample registration
mcp.HandleSampleFunc(&mcp.SampleDefinition{
Name: "sample_name",
Description: "Sample description",
}, func(w mcp.ContentsWriter, name string, args map[string]any) {
// Sample implementation
// ...
w.WriteContents(contents)
})
// Root registration
mcp.HandleRoot(&mcp.RootDefinition{
URI: "root_uri",
Name: "Root name",
})
// Create client
client := mcp.NewClient()
transport, err := ... // Create transport
// Configure transport and dial -> get session
session, err := client.Dial(transport)
defer session.Close()
// ...
}
运输选项
MCP Go支持多种传输方法,代码更改最少:
定制运输
对于自定义运输,请使用 Accept 和 Dial 使用适当的传输对象的方法。
// Server
sess, err := server.Accept(t)
// Client
sess, err := client.Dial(t)
标准I/O
对于标准I/O,请使用 AcceptStdio 和 DialStdio 方法。
// Server
sess, err := server.AcceptStdio()
// Client
sess, err := client.DialStdio("command", "arg1", "arg2")
超文本传输协议
使用HTTP,您可以使用 AcceptHTTP 和 DialHTTP 方法。
// Server
http.HandleFunc("/mcp", func(w http.ResponseWriter, r *http.Request) {
sess, err := server.AcceptHTTP(w, r)
})
// Client
sess, err := client.DialHTTP("http://localhost:8080/mcp", nil)
规范符合性
MCP Go实现了 模型上下文协议规范v2025-03-26,这是截至本次发布的最新版本的协议。
安装
go get github.com/OkutaniDaichi0106/mcp-go
文档
有关API详细文档和高级使用示例,请参阅我们的 GoDoc.
许可证
此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。