Go-MCP
📖 Overview 📖 概述
Go-MCP is a powerful and easy-to-use Go client library designed for interacting with the Model Context Protocol (MCP). This SDK provides comprehensive API coverage, including core features such as resource management, configuration, monitoring, and automated operations.
Go-MCP 是一个功能强大且易于使用的 Go 客户端库,旨在与模型上下文协议 (MCP) 交互。该 SDK 提供了全面的 API 覆盖,包括资源管理、配置、监控和自动化作等核心功能。
MCP (Model Context Protocol) is a standardized protocol for AI model interaction that enables seamless communication between applications and AI models. In today’s rapidly evolving AI landscape, standardized communication protocols have become increasingly important, ensuring interoperability between different systems and components, reducing integration costs, and improving development efficiency. Go-MCP brings this capability to Go applications through clean, idiomatic APIs, enabling developers to easily integrate AI functionality into their Go projects.
MCP(Model Context Protocol)是一种用于 AI 模型交互的标准化协议,可实现应用程序和 AI 模型之间的无缝通信。在当今快速发展的 AI 环境中,标准化通信协议变得越来越重要,它确保了不同系统和组件之间的互作性,降低了集成成本,提高了开发效率。Go-MCP 通过干净、惯用的 API 将此功能引入 Go 应用程序,使开发人员能够轻松地将 AI 功能集成到他们的 Go 项目中。
Go language is known for its excellent performance, concise syntax, and powerful concurrency support, making it particularly suitable for building high-performance network services and system tools. Through Go-MCP, developers can fully leverage these advantages of Go while enjoying the standardization and interoperability benefits brought by the MCP protocol. Whether building edge AI applications, microservice architectures, or enterprise-level systems, Go-MCP provides reliable and efficient solutions.
Go 语言以其出色的性能、简洁的语法和强大的并发支持而著称,特别适合于构建高性能的网络服务和系统工具。通过 Go-MCP,开发者可以充分利用 Go 的这些优势,同时享受 MCP 协议带来的标准化和互通性优势。无论是构建边缘 AI 应用程序、微服务架构还是企业级系统,Go-MCP 都能提供可靠、高效的解决方案。
Core Features 核心功能
- Core Protocol Implementation: Go-MCP fully supports the MCP specification, ensuring seamless interaction with all compatible MCP services and clients. The SDK implements all core methods and notification mechanisms defined in the protocol, including initialization, tool invocation, resource management, prompt handling, and more.
核心协议实现 :Go-MCP 完全支持 MCP 规范,确保与所有兼容的 MCP 服务和客户端无缝交互。SDK 实现了协议中定义的所有核心方法和通知机制,包括初始化、工具调用、资源管理、提示处理等。 - Multiple Transport Methods: Supports SSE (Server-Sent Events) and stdio transport, adapting to different application scenarios and deployment environments. SSE transport is suitable for web-based applications, providing real-time server push capabilities; while stdio transport is suitable for inter-process communication and command-line tools, making MCP functionality easy to integrate into various systems.
多种传输方式 :支持 SSE(Server-Sent Events)和 stdio 传输,适应不同的应用场景和部署环境。SSE 传输适用于基于 Web 的应用程序,提供实时服务器推送功能;而 stdio transport 适用于进程间通信和命令行工具,使 MCP 功能易于集成到各种系统中。 - Rich Notification System: Comprehensive event handling mechanism supporting real-time updates and status change notifications. Through registering custom notification handlers, applications can respond in real-time to tool list changes, resource updates, prompt list changes, and other events, achieving dynamic and interactive user experiences.
丰富的通知系统 :全面的事件处理机制,支持实时更新和状态变更通知。通过注册自定义通知处理程序,应用程序可以实时响应工具列表更改、资源更新、提示列表更改和其他事件,从而实现动态和交互式的用户体验。 - Flexible Architecture: Easy to extend, supporting custom implementations and customization needs. Go-MCP’s modular design allows developers to extend or replace specific components according to their needs while maintaining compatibility with the core protocol.
灵活的架构 :易于扩展,支持自定义实施和自定义需求。Go-MCP 的模块化设计允许开发人员根据自己的需求扩展或替换特定组件,同时保持与核心协议的兼容性。 - Production Ready: Thoroughly tested and performance-optimized, suitable for high-demand production environments. The SDK adopts Go language best practices, including concurrency control, error handling, and resource management, ensuring stability and reliability under high load conditions.
生产就绪 :经过全面测试和性能优化,适用于高要求的生产环境。SDK 采用 Go 语言最佳实践,包括并发控制、错误处理和资源管理,确保在高负载情况下保持稳定可靠。 - Comprehensive Documentation and Examples: Provides comprehensive documentation and rich example code to help developers get started quickly and understand in depth. Whether beginners or experienced Go developers can easily master the SDK usage through documentation and examples.
全面的文档和示例 :提供全面的文档和丰富的示例代码,帮助开发人员快速上手并深入理解。无论是初学者还是经验丰富的 Go 开发人员,都可以通过文档和示例轻松掌握 SDK 的使用方法。
Why Choose Go-MCP and Its Future Prospects为什么选择 Go-MCP 及其未来前景
Go-MCP SDK has significant advantages in the current technical environment and has broad development prospects. Here are the core advantages:
Go-MCP SDK 在当前的技术环境中具有显著的优势,具有广阔的发展前景。以下是核心优势:
- Local Deployment Advantages: Go-MCP supports local AI application deployment, providing faster response times, better cost-effectiveness, stronger data control capabilities, and more flexible customization options. Go’s static compilation features make deployment extremely simple, without managing complex dependencies.
本地部署优势 :Go-MCP 支持本地 AI 应用部署,提供更快的响应时间、更好的成本效益、更强的数据控制能力以及更灵活的定制选项。Go 的静态编译功能使部署变得极其简单,而无需管理复杂的依赖项。 - Edge Computing Support: Particularly suitable for running AI models on resource-constrained edge devices, supporting real-time processing, low-bandwidth environments, offline operations, and data privacy protection. Go’s high performance and low memory footprint make it an ideal choice for edge computing.
边缘计算支持 :特别适合在资源受限的边缘设备上运行 AI 模型,支持实时处理、低带宽环境、离线作和数据隐私保护。Go 的高性能和低内存占用使其成为边缘计算的理想选择。 - Microservice Architecture Adaptation: Perfectly fits modern microservice and serverless architectures, supporting AI microservice encapsulation, event-driven processing, distributed AI systems, and hybrid cloud deployment. Go’s lightweight runtime and concurrency model are particularly suitable for handling large numbers of concurrent requests.
微服务架构适配 :完美适配现代微服务和 Serverless 架构,支持 AI 微服务封装、事件驱动处理、分布式 AI 系统和混合云部署。Go 的轻量级运行时和并发模型特别适合处理大量并发请求。 - Strong Ecosystem: Benefits from Go’s active community and enterprise support, providing rich libraries and frameworks, as well as excellent development toolchains. As the community grows, the SDK’s functionality and performance will continue to improve.
强大的生态系统 :受益于 Go 活跃的社区和企业支持,提供丰富的库和框架,以及出色的开发工具链。随着社区的发展,SDK 的功能和性能将不断改进。 - Data Security Protection: Supports local data processing, reducing data transmission requirements and lowering data leakage risks. Provides secure communication methods that can integrate with encryption and authentication mechanisms, meeting data sovereignty and regulatory compliance requirements.
数据安全防护 :支持本地数据处理,降低数据传输需求,降低数据泄露风险。提供可与加密和身份验证机制集成的安全通信方法,满足数据主权和法规合规性要求。 - Cross-Platform Compatibility: Supports all major operating systems and processor architectures, providing consistent behavior and simple deployment methods. Through static linking and cross-compilation support, ensures a unified experience across different platforms.
跨平台兼容性 :支持所有主流作系统和处理器架构,提供一致的行为和简单的部署方法。通过静态链接和交叉编译支持,确保跨不同平台的统一体验。
🚀 Installation 🚀 安装
Installing the Go-MCP SDK is very simple, just use Go’s standard package management tool go get
command:
安装 Go-MCP SDK 非常简单,只需使用 Go 的标准包管理工具 go get
命令即可:
go get github.com/ThinkInAIXYZ/go-mcp
This will download and install the SDK and all its dependencies. Go-MCP requires Go 1.18 or higher to ensure support for the latest language features and standard library.
这将下载并安装 SDK 及其所有依赖项。Go-MCP 需要 Go 1.18 或更高版本,以确保支持最新的语言功能和标准库。
🔍 Quick Start 🔍 快速开始
Client Implementation 客户端实施
Here’s a basic client implementation example showing how to create an MCP client, connect to a server, and perform basic operations:
下面是一个基本的客户端实现示例,演示如何创建 MCP 客户端、连接到服务器和执行基本作:
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/ThinkInAIXYZ/go-mcp/client"
"github.com/ThinkInAIXYZ/go-mcp/protocol"
"github.com/ThinkInAIXYZ/go-mcp/transport"
)
func main() {
// Create transport client (using SSE in this example)
transportClient, err := transport.NewSSEClientTransport("http://127.0.0.1:8080/sse")
if err != nil {
log.Fatalf("Failed to create transport client: %v", err)
}
// Create MCP client using transport
mcpClient, err := client.NewClient(transportClient, client.WithClientInfo(protocol.Implementation{
Name: "example MCP client",
Version: "1.0.0",
}))
if err != nil {
log.Fatalf("Failed to create MCP client: %v", err)
}
defer mcpClient.Close()
// List available tools
toolsResult, err := mcpClient.ListTools(context.Background())
if err != nil {
log.Fatalf("Failed to list tools: %v", err)
}
b, _ := json.Marshal(toolsResult.Tools)
fmt.Printf("Available tools: %+v\n", string(b))
// Call tool
callResult, err := mcpClient.CallTool(
context.Background(),
protocol.NewCallToolRequest("current time", map[string]interface{}{
"timezone": "UTC",
}))
if err != nil {
log.Fatalf("Failed to call tool: %v", err)
}
b, _ = json.Marshal(callResult)
fmt.Printf("Tool call result: %+v\n", string(b))
}
This example shows how to:
此示例说明如何:
- Create an SSE client transport
创建 SSE 客户端传输 - Initialize an MCP client and configure notification handlers
初始化 MCP 客户端并配置通知处理程序 - Get server capability information
获取服务器功能信息 - List available tools 列出可用工具
- Call a specific tool and handle results
调用特定工具并处理结果
Server Implementation 服务器实施
Here’s a basic server implementation example showing how to create an MCP server, register tool handlers, and handle client requests:
下面是一个基本的服务器实现示例,演示如何创建 MCP 服务器、注册工具处理程序和处理客户端请求:
package main
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/ThinkInAIXYZ/go-mcp/protocol"
"github.com/ThinkInAIXYZ/go-mcp/server"
"github.com/ThinkInAIXYZ/go-mcp/transport"
)
type currentTimeReq struct {
Timezone string \`json:"timezone" description:"current time timezone"\`
}
func main() {
// Create transport server (using SSE in this example)
transportServer, err := transport.NewSSEServerTransport("127.0.0.1:8080")
if err != nil {
log.Fatalf("Failed to create transport server: %v", err)
}
// Create MCP server using transport
mcpServer, err := server.NewServer(transportServer,
// Set server implementation information
server.WithServerInfo(protocol.Implementation{
Name: "Example MCP Server",
Version: "1.0.0",
}),
)
if err != nil {
log.Fatalf("Failed to create MCP server: %v", err)
}
tool, err := protocol.NewTool("current time", "Get current time with timezone, Asia/Shanghai is default", currentTimeReq{})
if err != nil {
log.Fatalf("Failed to create tool: %v", err)
return
}
// Register tool handler
mcpServer.RegisterTool(tool, func(request *protocol.CallToolRequest) (*protocol.CallToolResult, error) {
req := new(currentTimeReq)
if err := protocol.VerifyAndUnmarshal(request.RawArguments, &req); err != nil {
return nil, err
}
loc, err := time.LoadLocation(req.Timezone)
if err != nil {
return nil, fmt.Errorf("parse timezone with error: %v", err)
}
text := fmt.Sprintf(\`current time is %s\`, time.Now().In(loc))
return &protocol.CallToolResult{
Content: []protocol.Content{
protocol.TextContent{
Type: "text",
Text: text,
},
},
}, nil
})
if err = mcpServer.Run(); err != nil {
log.Fatalf("Failed to start MCP server: %v", err)
return
}
}
This example shows how to:
此示例说明如何:
- Create an SSE transport server
创建 SSE 传输服务器 - Initialize an MCP server and configure server information and capabilities
初始化 MCP 服务器并配置服务器信息和功能 - Register tool handlers 注册工具处理程序
- Start HTTP server to handle client connections
启动 HTTP 服务器以处理客户端连接
🏗️ Architecture Design 🏗️ 架构设计
The Go-MCP SDK adopts a clear layered architecture design, ensuring code modularity, extensibility, and maintainability. Through a deep understanding of this architecture, developers can better utilize all SDK features and even customize and extend according to their needs.
Go-MCP SDK 采用清晰的分层架构设计,保证了代码的模块化、可扩展性和可维护性。通过对这种架构的深入了解,开发者可以更好地利用 SDK 的所有功能,甚至可以根据自己的需求进行定制和扩展。
Three-Layer Architecture 三层架构
Go-MCP’s architecture can be abstracted into three main layers:
Go-MCP 的架构可以抽象为三个主要层:
- Transport Layer: Handles underlying communication, supporting different transport protocols
传输层 :处理底层通信,支持不同的传输协议 - Protocol Layer: Implements all MCP protocol functionality and data structures
协议层 :实现所有 MCP 协议功能和数据结构 - User Layer: Includes server and client implementations, providing user-facing APIs
用户层 :包括服务器和客户端实现,提供面向用户的 API
This layered design decouples layers from each other, allowing independent evolution and replacement while maintaining overall functionality consistency.
这种分层设计将层彼此解耦,允许独立演进和替换,同时保持整体功能的一致性。
Transport Layer 传输层
The transport layer handles underlying communication details, currently supporting two main transport methods:
传输层处理底层通信细节,目前支持两种主要的传输方法:
- HTTP SSE/POST: HTTP-based server-sent events and POST requests, suitable for network communication
HTTP SSE/POST :基于 HTTP 的服务器发送的事件和 POST 请求,适用于网络通信 - Stdio: Standard input/output stream-based communication, suitable for inter-process communication
标准 :基于输入/输出流的标准通信,适用于进程间通信
The transport layer abstracts through a unified interface, so upper-layer code doesn’t need to care about specific transport implementation details. This design allows easy addition of new transport methods, such as WebSocket, gRPC, etc., without affecting upper-layer code.
传输层通过统一的接口进行抽象,因此上层代码不需要关心特定的传输实现细节。这种设计允许轻松添加新的传输方法,例如 WebSocket、gRPC 等,而不会影响上层代码。
Protocol Layer 协议层
The protocol layer is the core of Go-MCP, containing all MCP protocol-related definitions, including:
协议层是 Go-MCP 的核心,包含了所有 MCP 协议相关的定义,包括:
- Data structure definitions
数据结构定义 - Request construction 请求施工
- Response parsing 响应解析
- Notification handling 通知处理
The protocol layer implements all functionality defined in the MCP specification, including but not limited to:
协议层实现了 MCP 规范中定义的所有功能,包括但不限于:
- Initialization (Initialize)
初始化 (Initialize) - Heartbeat detection (Ping)
心跳检测 (Ping) - Cancellation operations (Cancellation)
取消作 (Cancellation) - Progress notifications (Progress)
进度通知 (Progress) - Root resource management (Roots)
根资源管理 (Roots) - Sampling control (Sampling)
采样控制 (Sampling) - Prompt management (Prompts)
提示管理 (Prompts) - Resource management (Resources)
资源管理 (Resources) - Tool invocation (Tools) 工具调用 (Tools)
- Completion requests (Completion)
完成请求 (Completion) - Logging (Logging) 日志记录 (Logging)
- Pagination handling (Pagination)
分页处理 (Pagination)
The protocol layer is decoupled from the transport layer through the transport interface, allowing protocol implementation to be independent of specific transport methods.
协议层通过传输接口与传输层解耦,从而允许协议实现独立于特定的传输方法。
User Layer 用户层
The user layer includes server and client implementations, providing developer-friendly APIs:
用户层包括服务器和客户端实现,提供对开发人员友好的 API:
- Server Implementation: Handles requests from clients, provides resources and tools, sends notifications
服务器实施 :处理来自客户端的请求,提供资源和工具,发送通知 - Client Implementation: Connects to server, sends requests, handles responses and notifications
客户端实施 :连接到服务器、发送请求、处理响应和通知
The user layer’s design philosophy is to provide synchronous request-response patterns, even if the underlying implementation may be asynchronous. This design makes the API more intuitive and easier to use while maintaining efficient asynchronous processing capabilities.
用户层的设计理念是提供同步的请求-响应模式,即使底层实现可能是异步的。这种设计使 API 更加直观和易于使用,同时保持高效的异步处理能力。
Message Processing Flow 消息处理流程
In Go-MCP, messages can be abstracted into three types:
在 Go-MCP 中,消息可以抽象成三种类型:
- Request: Request messages sent from client to server
请求 :请求从客户端发送到服务器的消息 - Response: Response messages returned from server to client
响应 :从服务器返回到客户端的响应消息 - Notification: One-way notification messages that can be sent by server or client
通知 :可由服务器或客户端发送的单向通知消息
Both server and client have sending and receiving capabilities:
服务器和客户端都具有发送和接收功能:
- Sending Capability: Includes sending messages (requests, responses, notifications) and matching requests with responses
发送功能 :包括发送消息(请求、响应、通知)和将请求与响应匹配 - Receiving Capability: Includes routing messages (requests, responses, notifications) and asynchronous/synchronous processing
接收功能 :包括路由消息(请求、响应、通知)和异步/同步处理
Project Structure 项目结构
Go-MCP’s project structure clearly reflects its architectural design:
Go-MCP 的项目结构清楚地反映了它的架构设计:
go-mcp/
├── transport/ # Transport layer implementation
│ ├── sse_client.go # SSE client implementation
│ ├── sse_server.go # SSE server implementation
│ ├── stdio_client.go # Stdio client implementation
│ ├── stdio_server.go # Stdio server implementation
│ └── transport.go # Transport interface definition
├── protocol/ # Protocol layer implementation
│ ├── initialize.go # Initialization related
│ ├── ping.go # Heartbeat detection related
│ ├── cancellation.go # Cancellation operations related
│ ├── progress.go # Progress notifications related
│ ├── roots.go # Root resources related
│ ├── sampling.go # Sampling control related
│ ├── prompts.go # Prompt management related
│ ├── resources.go # Resource management related
│ ├── tools.go # Tool invocation related
│ ├── completion.go # Completion requests related
│ ├── logging.go # Logging related
│ ├── pagination.go # Pagination handling related
│ └── jsonrpc.go # JSON-RPC related
├── server/ # Server implementation
│ ├── server.go # Server core implementation
│ ├── call.go # Send messages to client
│ ├── handle.go # Handle messages from client
│ ├── send.go # Send message implementation
│ └── receive.go # Receive message implementation
├── client/ # Client implementation
│ ├── client.go # Client core implementation
│ ├── call.go # Send messages to server
│ ├── handle.go # Handle messages from server
│ ├── send.go # Send message implementation
│ └── receive.go # Receive message implementation
└── pkg/ # Common utility packages
├── errors.go # Error definitions
└── log.go # Log interface definitions
This structure makes code organization clear and easy for developers to understand and extend.
这种结构使代码组织清晰易懂,便于开发人员理解和扩展。
Design Principles 设计原则
Go-MCP follows these core design principles:
Go-MCP 遵循以下核心设计原则:
- Modularity: Components are decoupled through clear interfaces, allowing independent development and testing
模块化 :组件通过清晰的接口解耦,允许独立开发和测试 - Extensibility: Architecture design allows easy addition of new transport methods, protocol features, and user layer APIs
可扩展性 :架构设计允许轻松添加新的传输方法、协议功能和用户层 API - Usability: Despite potentially complex internal implementation, provides clean, intuitive APIs externally
可用性 :尽管内部实现可能很复杂,但对外部提供干净、直观的 API - High Performance: Leverages Go’s concurrency features to ensure efficient message processing
高性能 :利用 Go 的并发功能确保高效的消息处理 - Reliability: Comprehensive error handling and recovery mechanisms ensure system stability in various scenarios
可靠性 :完善的错误处理和恢复机制,确保系统在各种场景下的稳定性
Through this carefully designed architecture, Go-MCP provides developers with a powerful and flexible tool, enabling them to easily integrate the MCP protocol into their applications, whether simple command-line tools or complex distributed systems.
通过这种精心设计的架构,Go-MCP 为开发人员提供了一个强大而灵活的工具,使他们能够轻松地将 MCP 协议集成到他们的应用程序中,无论是简单的命令行工具还是复杂的分布式系统。
Star History Star 历史
🤝 Contributing 🤝 贡献
We welcome contributions to the Go-MCP project! Whether reporting issues, suggesting features, or submitting code improvements, your participation will help us make the SDK better.
我们欢迎为 Go-MCP 项目做出贡献!无论是报告问题、建议功能还是提交代码改进,您的参与都将有助于我们改进 SDK。
Contribution Guidelines 贡献准则
Please check CONTRIBUTING.md for detailed contribution process and guidelines. Here are the basic steps for contributing:
请查看 CONTRIBUTING.md 了解详细的贡献流程和指南。以下是贡献的基本步骤:
- Submit Issues: If you find a bug or have feature suggestions, create an issue on GitHub
提交问题 :如果您发现错误或有功能建议,请在 GitHub 上创建问题 - Discuss: Discuss issues or suggestions with maintainers and community to determine solutions
讨论 :与维护者和社区讨论问题或建议以确定解决方案 - Develop: Implement your changes, ensuring code meets project style and quality standards
开发 :实施您的更改,确保代码符合项目样式和质量标准 - Test: Add tests to verify your changes and ensure all existing tests pass
测试 :添加测试以验证您的更改并确保所有现有测试都通过 - Submit PR: Create a Pull Request describing your changes and issues addressed
提交 PR: 创建一个拉取请求,描述您的更改和解决的问题 - Review: Participate in code review process, making necessary adjustments based on feedback
审核 :参与代码审核过程,根据反馈进行必要的调整 - Merge: Once your PR is approved, it will be merged into the main branch
合并 :一旦你的 PR 被批准,它将被合并到 main 分支中
Code Style 代码样式
We follow standard Go code style and best practices:
我们遵循标准的 Go 代码风格和最佳实践:
- Use
gofmt
orgoimports
to format code
使用gofmt
或goimports
格式化代码 - Follow guidelines in Effective Go and Go Code Review Comments
遵循 有效的 Go 和 Go 代码审查注释中的 准则 - Add documentation comments for all exported functions, types, and variables
为所有导出的函数、类型和变量添加文档注释 - Write clear, concise code, avoiding unnecessary complexity
编写清晰、简洁的代码,避免不必要的复杂性 - Use meaningful variable and function names
使用有意义的变量和函数名称
📄 License 📄 许可证
This project is licensed under the MIT License. The MIT License is a permissive license that allows you to freely use, modify, distribute, and privatize the code, as long as you retain the original license and copyright notice.
本项目根据 MIT 许可证 获得许可。MIT 许可证是一种宽松的许可证,允许您自由使用、修改、分发和私有化代码,只要您保留原始许可证和版权声明即可。
📞 Contact 📞 联系
For questions, suggestions, or issues, please contact us through:
如有疑问、建议或问题,请通过以下方式与我们联系:
- GitHub Issues: Create an issue on the project repository
GitHub Issues :在 项目仓库 中创建 Issue - WeChat: Scan the QR code below to join our GO-MCP user group
微信 :扫描下方二维码加入我们的 GO-MCP 用户组
We welcome any form of feedback and contribution and are committed to building a friendly, inclusive community.
我们欢迎任何形式的反馈和贡献,并致力于建立一个友好、包容的社区。
✨ Contributors ✨ 贡献
Thank you for your contribution to Go-MCP!
感谢您对 Go-MCP 的贡献!