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.
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.
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.
-
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.
-
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.
-
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.
-
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.
-
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-MCP SDK has significant advantages in the current technical environment and has broad development prospects. Here are the core advantages:
-
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.
-
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.
-
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.
-
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.
-
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.
Installing the Go-MCP SDK is very simple, just use Go's standard package management tool go get
command:
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.
Here's a basic client implementation example showing how to create an MCP client, connect to a server, and perform basic operations:
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
- Initialize an MCP client and configure notification handlers
- Get server capability information
- List available tools
- Call a specific tool and handle results
Here's a basic server implementation example showing how to create an MCP server, register tool handlers, and handle client requests:
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
- Initialize an MCP server and configure server information and capabilities
- Register tool handlers
- Start HTTP server to handle client connections
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's architecture can be abstracted into three main layers:
- Transport Layer: Handles underlying communication, supporting different transport protocols
- Protocol Layer: Implements all MCP protocol functionality and data structures
- User Layer: Includes server and client implementations, providing user-facing APIs
This layered design decouples layers from each other, allowing independent evolution and replacement while maintaining overall functionality consistency.
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
- 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.
The protocol layer is the core of Go-MCP, containing all MCP protocol-related definitions, including:
- 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:
- Initialization (Initialize)
- Heartbeat detection (Ping)
- Cancellation operations (Cancellation)
- Progress notifications (Progress)
- Root resource management (Roots)
- Sampling control (Sampling)
- Prompt management (Prompts)
- Resource management (Resources)
- Tool invocation (Tools)
- Completion requests (Completion)
- Logging (Logging)
- Pagination handling (Pagination)
The protocol layer is decoupled from the transport layer through the transport interface, allowing protocol implementation to be independent of specific transport methods.
The user layer includes server and client implementations, providing developer-friendly APIs:
- 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.
In Go-MCP, messages can be abstracted into three types:
- 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
Go-MCP's project structure clearly reflects its architectural design:
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.
Go-MCP follows these core design principles:
- 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
- Usability: Despite potentially complex internal implementation, provides clean, intuitive APIs externally
- High Performance: Leverages Go's concurrency features to ensure efficient message processing
- 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.
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.
Please check CONTRIBUTING.md for detailed contribution process and guidelines. Here are the basic steps for contributing:
- Submit Issues: If you find a bug or have feature suggestions, create an issue on 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
- 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
We follow standard Go code style and best practices:
- Use
gofmt
orgoimports
to format code - Follow guidelines in Effective Go and Go Code Review Comments
- Add documentation comments for all exported functions, types, and variables
- Write clear, concise code, avoiding unnecessary complexity
- Use meaningful variable and function names
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.
For questions, suggestions, or issues, please contact us through:
- GitHub Issues: Create an issue on the project repository
- WeChat: Scan the QR code below to join our GO-MCP user group
We welcome any form of feedback and contribution and are committed to building a friendly, inclusive community.
Thank you for your contribution to Go-MCP!