GoMCP - Go Model Context Protocol Library

gomcp provides a Go implementation of the Model Context Protocol (MCP), enabling communication between language models/agents and external tools or resources via a standardized protocol.
This library facilitates building MCP clients (applications that consume tools/resources) and MCP servers (applications that provide tools/resources). Communication primarily occurs over standard input/output using newline-delimited JSON messages conforming to the JSON-RPC 2.0 specification, although other transports (like SSE, WebSocket, TCP) are supported. The library supports negotiation between different MCP specification versions.
Current Status: Compliant with MCP Specification v2025-03-26 and v2024-11-05
The core library implements the features defined in the MCP Specification versions 2025-03-26 and 2024-11-05:
- Transport Agnostic Core: Server (
server/) and Client (client/) logic is separated from the transport layer.
- Protocol Version Negotiation: Client and Server negotiate the protocol version during initialization, supporting both
2025-03-26 and 2024-11-05.
- Transports: Implementations for Stdio (
transport/stdio/), SSE (transport/sse/), and WebSocket (transport/websocket/) are provided.
- Protocol Structures: Defines Go structs for all specified MCP methods, notifications, and content types (
protocol/).
- Initialization: Full client/server initialization sequence, including capability exchange.
- Tooling:
tools/list, tools/call methods and handlers.
- Resources:
resources/list, resources/read, resources/subscribe, resources/unsubscribe methods and handlers.
- Prompts:
prompts/list, prompts/get methods and handlers.
- Logging:
logging/set_level method and notifications/message infrastructure.
- Sampling:
sampling/create_message method.
- Roots:
roots/list method and client-side root management.
- Ping:
ping method.
- Cancellation:
$/cancelled notification handling with context.Context integration.
- Progress:
$/progress notification infrastructure and _meta.progressToken support.
- Notifications: Dynamic triggering for
list_changed (tools, resources, prompts, roots) and resources/changed notifications based on library actions and subscriptions.
(Note: While the library provides the mechanisms, the specific logic within server-side handlers like handleReadResource, handleGetPrompt, handleLoggingSetLevel, and triggering NotifyResourceUpdated is application-dependent.)
Installation
go get github.com/localrivet/gomcp
Basic Usage
The core logic resides in the server, client, and protocol packages.
(Note: The usage examples below are simplified. See the examples/ directory for more complete implementations.)
Implementing an MCP Server (using Stdio)
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/localrivet/gomcp/protocol"
"github.com/localrivet/gomcp/server"
"github.com/localrivet/gomcp/util/schema"
)
// Define arguments struct for the add tool
type AddArgs struct {
Num1 int `json:"num1" description:"The first number to add"`
Num2 int `json:"num2" description:"The second number to add"`
// Optional fields use pointers
Comment *string `json:"comment,omitempty" description:"An optional comment"`
}
// Handler for the add tool using schema.HandleArgs
func addToolHandler(ctx context.Context, progressToken *protocol.ProgressToken, arguments any) (content []protocol.Content, isError bool) {
// Use schema.HandleArgs for easy argument parsing and validation
args, errContent, isErr := schema.HandleArgs[AddArgs](arguments)
if isErr {
log.Printf("Error handling add args: %v", errContent)
return errContent, true // Return the error content generated by HandleArgs
}
log.Printf("Executing add tool with args: %+v", args)
sum := args.Num1 + args.Num2
resultText := fmt.Sprintf("The sum of %d and %d is %d.", args.Num1, args.Num2)
if args.Comment != nil {
resultText += fmt.Sprintf(" Comment: %s", *args.Comment)
}
// Return the result as text content
return []protocol.Content{protocol.TextContent{Type: "text", Text: resultText}}, false
}
func main() {
// Configure logger (optional, defaults to stderr)
log.SetOutput(os.Stderr)
log.SetFlags(log.Ltime | log.Lshortfile)
log.Println("Starting Simple MCP Server...")
// Create the core server instance
srv := server.NewServer("MySimpleServer", server.ServerOptions{
// Logger: provide custom logger if needed
})
// Define the 'add' tool using schema helper for input schema generation
addTool := protocol.Tool{
Name: "add",
Description: "Adds two numbers together.",
InputSchema: schema.FromStruct(AddArgs{}), // Generate schema from struct
}
// Register the tool with its handler
err := srv.RegisterTool(addTool, addToolHandler)
if err != nil {
log.Fatalf("Failed to register 'add' tool: %v", err)
}
// Start the server using the built-in stdio handler.
// This blocks until the server exits (e.g., EOF on stdin or error).
log.Println("Server setup complete. Listening on stdio...")
if err := server.ServeStdio(srv); err != nil {
log.Fatalf("Server exited with error: %v", err)
}
log.Println("Server shutdown complete.")
}
Implementing an MCP Client (using Stdio)
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/localrivet/gomcp/client"
"github.com/localrivet/gomcp/protocol"
)
func main() {
// Configure logger (optional, defaults to stderr)
log.SetOutput(os.Stderr)
log.SetFlags(log.Ltime | log.Lshortfile)
log.Println("Starting Simple MCP Client...")
// Create a client configured for stdio communication
// NewStdioClient handles the transport setup internally.
clt, err := client.NewStdioClient("MySimpleClient", client.ClientOptions{
// Logger: provide custom logger if needed
})
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
// Set a timeout for the connection and operations
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Connect and perform initialization handshake
log.Println("Connecting to server via stdio...")
err = clt.Connect(ctx)
if err != nil {
log.Fatalf("Client failed to connect: %v", err)
}
defer clt.Close() // Ensure connection resources are cleaned up
serverInfo := clt.ServerInfo()
log.Printf("Connected to server: %s (Version: %s)", serverInfo.Name, serverInfo.Version)
// Example: List available tools
log.Println("\n--- Listing Tools ---")
listParams := protocol.ListToolsRequestParams{}
toolsResult, err := clt.ListTools(ctx, listParams)
if err != nil {
log.Printf("Error listing tools: %v", err)
} else {
log.Printf("Available tools (%d):", len(toolsResult.Tools))
for _, tool := range toolsResult.Tools {
log.Printf(" - %s: %s", tool.Name, tool.Description)
}
}
// Example: Call the 'add' tool (assuming server has it registered)
log.Println("\n--- Calling 'add' Tool ---")
addArgs := map[string]interface{}{
"num1": 15,
"num2": 27,
"comment": "Example call",
}
callParams := protocol.CallToolParams{
Name: "add",
Arguments: addArgs,
}
callResult, err := clt.CallTool(ctx, callParams, nil) // No progress token needed
if err != nil {
log.Printf("Error calling tool 'add': %v", err)
} else {
log.Printf("Tool 'add' call successful (IsError=%v):", callResult.IsError)
for i, content := range callResult.Content {
// Log content (could be text, json, image, etc.)
log.Printf(" Content[%d]: Type=%s", i, content.ContentType())
if textContent, ok := content.(protocol.TextContent); ok {
log.Printf(" Text: %s", textContent.Text)
}
// Add checks for other content types if needed
}
}
log.Println("\nClient finished.")
}
Examples
The examples/ directory contains various client/server pairs demonstrating specific features and transports. Each example is a self-contained Go module.
Running Examples:
Most examples follow a similar pattern. To run an example:
- Navigate to the example's directory (e.g.,
cd examples/basic/server).
- Run the server using
go run ..
- In another terminal, navigate to the corresponding client directory (e.g.,
cd examples/basic/client).
- Run the client using
go run ..
Example Categories:
examples/basic/: Demonstrates simple stdio communication.
examples/http/: Shows integration with various Go HTTP frameworks/routers (Chi, Echo, Fiber, Gin, Go-Zero, Gorilla/Mux, HttpRouter, Beego, Iris, Net/HTTP) using the SSE transport. Run the server from examples/http/<framework>/server/ and use a generic SSE client (like the one in examples/cmd/gomcp-client configured for SSE) or a browser-based client.
examples/websocket/: Demonstrates the WebSocket transport. Run the server from examples/websocket/server/ and use a generic WebSocket client (like examples/cmd/gomcp-client configured for WebSocket).
examples/configuration/: Shows how to load server configuration from JSON, YAML, or TOML files. Run the specific server (e.g., cd examples/configuration/json/server && go run .) which loads the corresponding config file (e.g., examples/configuration/json/config.json).
examples/auth/: Demonstrates simple API key authentication (stdio).
examples/billing/: Builds on the auth example, simulating billing/tracking (stdio).
examples/rate-limit/: Builds on the auth example, adding simple global rate limiting (stdio).
examples/kitchen-sink/: A comprehensive server example combining multiple features (stdio).
examples/cmd/: Contains generic command-line client and server implementations that can be configured for different transports.
(Check the specific README within each example directory for more detailed instructions if available.)
Documentation
More detailed documentation can be found in the GitHub Pages site (powered by the /docs directory).
Go package documentation is available via:
- pkg.go.dev
- Running
godoc -http=:6060 locally and navigating to github.com/localrivet/gomcp.
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
License
This project is licensed under the MIT License.