Categorygithub.com/MegaGrindStone/go-mcp
modulepackage
0.5.0
Repository: https://github.com/megagrindstone/go-mcp.git
Documentation: pkg.go.dev

# README

go-mcp

Go Reference CI Go Report Card codecov

A Go implementation of the Model Context Protocol (MCP) - an open protocol that enables seamless integration between LLM applications and external data sources and tools.

⚠️ Warning: The main branch contains unreleased changes and may be unstable. We recommend using the latest tagged release for stability. This library follows semantic versioning - breaking changes may be introduced with minor version bumps (0.x.0) until v1.0.0 is released. After v1.0.0, the API will be stable and breaking changes will only occur in major version updates. We recommend pinning your dependency to a specific version and reviewing the changelog before upgrading.

Overview

This repository provides a Go library implementing the Model Context Protocol (MCP) following the official specification.

Features

Core Protocol

  • Complete MCP protocol implementation with JSON-RPC 2.0 messaging
  • Pluggable transport system supporting SSE and Standard IO
  • Session-based client-server communication
  • Comprehensive error handling and progress tracking

Server Features

  • Modular server implementation with optional capabilities
  • Support for prompts, resources, and tools
  • Real-time notifications and updates
  • Built-in logging system
  • Resource subscription management

Client Features

  • Flexible client configuration with optional capabilities
  • Automatic session management and health monitoring
  • Support for streaming and pagination
  • Progress tracking and cancellation support
  • Configurable timeouts and retry logic

Transport Options

  • Server-Sent Events (SSE) for web-based real-time updates
  • Standard IO for command-line tool integration

Installation

go get github.com/MegaGrindStone/go-mcp

Usage

Server Implementation

There are two main approaches to implementing an go-mcp server:

1. Basic Server

type MyMCPServer struct{}

func (MyMCPServer) Info() mcp.Info {
    return mcp.Info{
        Name:    "my-mcp-server",
        Version: "1.0",
    }
}

func (MyMCPServer) RequireRootsListClient() bool {
    return false
}

func (MyMCPServer) RequireSamplingClient() bool {
    return false
}

2. Choose Transport Layer

go-mcp supports two transport options:

Server-Sent Events (SSE)
sseSrv := mcp.NewSSEServer()
go mcp.Serve(ctx, MyMCPServer{}, sseSrv)

// Set up HTTP handlers
http.HandleFunc("/sse", sseSrv.HandleSSE())
http.HandleFunc("/message", sseSrv.HandleMessage())
http.ListenAndServe(":8080", nil)
Standard IO
stdIOSrv := mcp.NewStdIO(os.Stdin, os.Stdout)
go mcp.Serve(ctx, MyMCPServer{}, stdIOSrv)

Client Implementation

// Create client info
info := mcp.Info{
    Name:    "my-mcp-client",
    Version: "1.0",
}

// Choose transport layer - SSE or Standard IO
// Option 1: Server-Sent Events (SSE)
sseClient := mcp.NewSSEClient("http://localhost:8080/sse", http.DefaultClient)
cli := mcp.NewClient(info, sseClient)

// Option 2: Standard IO
srvReader, srvWriter := io.Pipe()
cliReader, cliWriter := io.Pipe()
cliIO := mcp.NewStdIO(cliReader, srvWriter)
srvIO := mcp.NewStdIO(srvReader, cliWriter)
cli := mcp.NewClient(info, cliIO)

// Connect client
if err := cli.Connect(); err != nil {
    log.Fatal(err)
}
defer cli.Close()

Making Requests

// List available tools
tools, err := cli.ListTools(ctx, mcp.ListToolsParams{})
if err != nil {
    log.Fatal(err)
}

// Call a tool
result, err := cli.CallTool(ctx, mcp.CallToolParams{
    Name: "echo",
    Arguments: map[string]any{
        "message": "Hello MCP!",
    },
})
if err != nil {
    log.Fatal(err)
}

Complete Examples

For complete working examples:

  • See example/everything/ for a comprehensive server and client implementation with all features
  • See example/filesystem/ for a focused example of file operations using Standard IO transport

These examples demonstrate:

  • Server and client lifecycle management
  • Transport layer setup
  • Error handling
  • Tool implementation
  • Resource management
  • Progress tracking
  • Logging integration

For more details, check the example directory in the repository.

Server Packages

The servers directory contains reference server implementations that mirror those found in the official modelcontextprotocol/servers repository.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

License

This project is licensed under the MIT License - see the LICENSE file for details.

# Packages

No description provided by the author
No description provided by the author

# Functions

NewClient creates a new Model Context Protocol (MCP) client with the specified configuration.
NewSSEClient creates an SSE client that connects to the specified connectURL.
NewSSEServer creates and initializes a new SSE server that listens for client connections at the specified messageURL.
NewStdIO creates a new StdIO instance configured with the provided reader and writer.
Serve starts a Model Context Protocol (MCP) server and manages its lifecycle.
WithClientPingInterval sets the ping interval for the client.
WithClientReadTimeout sets the read timeout for the client.
WithClientWriteTimeout sets the write timeout for the client.
WithInstructions sets the instructions for the server.
WithLogHandler sets the log handler for the server.
WithLogReceiver sets the log receiver for the client.
WithProgressListener sets the progress listener for the client.
WithPromptListUpdater sets the prompt list watcher for the server.
WithPromptListWatcher sets the prompt list watcher for the client.
WithPromptServer sets the prompt server for the server.
WithResourceListUpdater sets the resource list watcher for the server.
WithResourceListWatcher sets the resource list watcher for the client.
WithResourceServer sets the resource server for the server.
WithResourceSubscribedWatcher sets the resource subscribe watcher for the client.
WithResourceSubscriptionHandler sets the resource subscription handler for the server.
WithRootsListHandler sets the roots list handler for the client.
WithRootsListUpdater sets the roots list updater for the client.
WithRootsListWatcher sets the roots list watcher for the server.
WithSamplingHandler sets the sampling handler for the client.
WithServerPingInterval sets the ping interval for the server.
WithServerReadTimeout sets the read timeout for the server.
WithServerWriteTimeout sets the write timeout for the server.
WithToolListUpdater sets the tool list watcher for the server.
WithToolListWatcher sets the tool list watcher for the client.
WithToolServer sets the tool server for the server.

# Constants

CompletionRefPrompt is used in CompletionRef.Type for prompt argument completion.
CompletionRefResource is used in CompletionRef.Type for resource template argument completion.
ContentType represents the type of content in messages.
ContentType represents the type of content in messages.
ContentType represents the type of content in messages.
ContentType represents the type of content in messages.
JSONRPCVersion specifies the JSON-RPC protocol version used for communication.
LogLevel represents the severity level of log messages.
LogLevel represents the severity level of log messages.
LogLevel represents the severity level of log messages.
LogLevel represents the severity level of log messages.
LogLevel represents the severity level of log messages.
LogLevel represents the severity level of log messages.
LogLevel represents the severity level of log messages.
LogLevel represents the severity level of log messages.
MethodCompletionComplete is the method name for requesting completion suggestions.
MethodLoggingSetLevel is the method name for setting the minimum severity level for emitted log messages.
MethodPromptsGet is the method name for retrieving a specific prompt by identifier.
MethodPromptsList is the method name for retrieving a list of available prompts.
MethodResourcesList is the method name for listing available resources.
MethodResourcesRead is the method name for reading the content of a specific resource.
MethodResourcesSubscribe is the method name for subscribing to resource updates.
MethodResourcesTemplatesList is the method name for listing available resource templates.
MethodResourcesUnsubscribe is the method name for unsubscribing from resource updates.
MethodRootsList is the method name for retrieving a list of root resources.
MethodSamplingCreateMessage is the method name for creating a new sampling message.
MethodToolsCall is the method name for invoking a specific tool.
MethodToolsList is the method name for retrieving a list of available tools.
Role represents the role in a conversation (user or assistant).
Role represents the role in a conversation (user or assistant).

# Structs

Annotations represents the annotations for a message.
CallToolParams contains parameters for executing a specific tool.
CallToolResult represents the outcome of a tool invocation via CallTool.
Client implements a Model Context Protocol (MCP) client that enables communication between LLM applications and external data sources and tools.
ClientCapabilities represents client capabilities.
CompletesCompletionParams contains parameters for requesting completion suggestions.
CompletionArgument defines the structure for arguments passed in completion requests, containing the argument name and its corresponding value.
CompletionRef identifies what is being completed in a completion request.
CompletionResult contains the response data for a completion request, including possible completion values and whether more completions are available.
Content represents a message content with its type.
GetPromptParams contains parameters for retrieving a specific prompt.
GetPromptResult represents the result of a prompt request.
Info contains metadata about a server or client instance including its name and version.
JSONRPCError represents an error response in the JSON-RPC 2.0 protocol.
JSONRPCMessage represents a JSON-RPC 2.0 message used for communication in the MCP protocol.
ListPromptResult represents a paginated list of prompts returned by ListPrompts.
ListPromptsParams contains parameters for listing available prompts.
ListResourcesParams contains parameters for listing available resources.
ListResourcesResult represents a paginated list of resources returned by ListResources.
ListResourceTemplatesParams contains parameters for listing available resource templates.
ListResourceTemplatesResult represents the result of a list resource templates request.
ListToolsParams contains parameters for listing available tools.
ListToolsResult represents a paginated list of tools returned by ListTools.
LoggingCapability represents logging-specific capabilities.
LogParams represents the parameters for a log message.
ParamsMeta contains optional metadata that can be included with request parameters.
ProgressParams represents the progress status of a long-running operation.
Prompt defines a template for generating prompts with optional arguments.
PromptArgument defines a single argument that can be passed to a prompt.
PromptMessage represents a message in a prompt.
PromptsCapability represents prompts-specific capabilities.
ReadResourceParams contains parameters for retrieving a specific resource.
ReadResourceResult represents the result of a read resource request.
Resource represents a content resource in the system with associated metadata.
ResourceContents represents either text or blob resource contents.
ResourcesCapability represents resources-specific capabilities.
ResourceTemplate defines a template for generating resource URIs.
Root represents a root directory or file that the server can operate on.
RootList represents a collection of root resources in the system.
RootsCapability represents roots-specific capabilities.
SamplingCapability represents sampling-specific capabilities.
SamplingContent represents the content of a sampling message.
SamplingMessage represents a message in the sampling conversation history.
SamplingModelPreferences defines preferences for model selection and behavior.
SamplingParams defines the parameters for generating a sampled message.
SamplingResult represents the output of a sampling operation.
ServerCapabilities represents server capabilities.
SSEClient implements a Server-Sent Events (SSE) client that manages server connections and bidirectional message handling.
SSEServer implements a framework-agnostic Server-Sent Events (SSE) server for managing bidirectional client communication.
StdIO implements a standard input/output transport layer for MCP communication using JSON-RPC message encoding over stdin/stdout or similar io.Reader/io.Writer pairs.
SubscribeResourceParams contains parameters for subscribing to a resource.
Tool defines a callable tool with its input schema.
ToolsCapability represents tools-specific capabilities.
UnsubscribeResourceParams contains parameters for unsubscribing from a resource.

# Interfaces

ClientTransport provides the client-side communication layer in the MCP protocol.
LogHandler provides an interface for streaming log messages from the MCP server to connected clients.
LogReceiver provides an interface for receiving log messages from the server.
ProgressListener provides an interface for receiving progress updates on long-running operations.
PromptListUpdater provides an interface for monitoring changes to the available prompts list.
PromptListWatcher provides an interface for receiving notifications when the server's prompt list changes.
PromptServer defines the interface for managing prompts in the MCP protocol.
ResourceListUpdater provides an interface for monitoring changes to the available resources list.
ResourceListWatcher provides an interface for receiving notifications when the server's resource list changes.
ResourceServer defines the interface for managing resources in the MCP protocol.
ResourceSubscribedWatcher provides an interface for receiving notifications when a subscribed resource changes.
ResourceSubscriptionHandler defines the interface for handling subscription for resources.
RootsListHandler defines the interface for retrieving the list of root resources in the MCP protocol.
RootsListUpdater provides an interface for monitoring changes to the available roots list.
RootsListWatcher provides an interface for receiving notifications when the client's root list changes.
SamplingHandler provides an interface for generating AI model responses based on conversation history.
Server represents the main MCP server interface that users will implement.
ServerTransport provides the server-side communication layer in the MCP protocol.
Session represents a bidirectional communication channel between server and client.
ToolListUpdater provides an interface for monitoring changes to the available tools list.
ToolListWatcher provides an interface for receiving notifications when the server's tool list changes.
ToolServer defines the interface for managing tools in the MCP protocol.

# Type aliases

ClientOption is a function that configures a client.
ContentType represents the type of content in messages.
LogLevel represents the severity level of log messages.
MustString is a type that enforces string representation for fields that can be either string or integer in the protocol specification, such as request IDs and progress tokens.
ProgressReporter is a function type used to report progress updates for long-running operations.
RequestClientFunc is a function type that handles JSON-RPC message communication between client and server.
Role represents the role in a conversation (user or assistant).
ServerOption represents the options for the server.