gomcp

package module
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2025 License: MIT Imports: 0 Imported by: 1

README

GoMCP - Go Model Context Protocol Library

Go Reference Go Report Card

GoMCP is a complete Go implementation of the Model Context Protocol (MCP), designed to facilitate seamless interaction between applications and Large Language Models (LLMs). The library supports all specification versions with automatic negotiation and provides a clean, idiomatic API for both clients and servers.

Table of Contents

Overview

The Model Context Protocol (MCP) standardizes communication between applications and LLMs, enabling:

  • Tool Calling: Execute actions and functions through LLMs
  • Resource Access: Provide structured data to LLMs
  • Prompt Rendering: Create reusable templates for LLM interactions
  • Sampling: Generate text from LLMs with control over parameters

GoMCP provides an idiomatic Go implementation that handles all the protocol details while offering a clean, developer-friendly API.

Key Features

  • Complete Protocol Implementation: Full support for all MCP specification versions
  • Automatic Version Negotiation: Seamless compatibility between clients and servers
  • Multiple Transport Options: Support for stdio, HTTP, WebSocket, and Server-Sent Events
  • Type-Safe API: Leverages Go's type system for safety and expressiveness
  • Server Process Management: Automatically start, manage, and stop external MCP servers
  • Server Configuration: Load server definitions from configuration files
  • Flexible Architecture: Modular design for easy extension and customization

Installation

go get github.com/localrivet/gomcp

Quickstart

Client Example
package main

import (
	"log"
	"github.com/localrivet/gomcp/client"
)

func main() {
	// Create a new client
	c, err := client.NewClient("my-client",
		client.WithProtocolVersion("2025-03-26"),
		client.WithProtocolNegotiation(true),
	)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer c.Close()

	// Call a tool on the MCP server
	result, err := c.CallTool("say_hello", map[string]interface{}{
		"name": "World",
	})
	if err != nil {
		log.Fatalf("Tool call failed: %v", err)
	}

	log.Printf("Result: %v", result)
}
Server Example
package main

import (
	"fmt"
	"log/slog"
	"os"
	"github.com/localrivet/gomcp/server"
)

func main() {
	// Create a logger
	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelInfo,
	}))

	// Create a new server
	s := server.NewServer("example-server",
		server.WithLogger(logger),
	).AsStdio()

	// Register a tool
	s.Tool("say_hello", "Greet someone", func(ctx *server.Context, args struct {
		Name string `json:"name"`
	}) (string, error) {
		return fmt.Sprintf("Hello, %s!", args.Name), nil
	})

	// Start the server
	s.Run()
}
Server Management Example
package main

import (
	"log"
	"github.com/localrivet/gomcp/client"
)

func main() {
	// Define server configuration
	config := client.ServerConfig{
		MCPServers: map[string]client.ServerDefinition{
			"task-master-ai": {
				Command: "npx",
				Args: []string{"-y", "--package=task-master-ai", "task-master-ai"},
				Env: map[string]string{
					"ANTHROPIC_API_KEY": "${ANTHROPIC_API_KEY}",
				},
			},
		},
	}

	// Create a client with automatic server management
	c, err := client.NewClient("my-client",
		client.WithServers(config, "task-master-ai"),
	)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer c.Close() // Automatically stops the server process

	// Call a tool on the managed server
	result, err := c.CallTool("add_task", map[string]interface{}{
		"prompt": "Create a login page with authentication",
	})
	if err != nil {
		log.Fatalf("Tool call failed: %v", err)
	}

	log.Printf("Task created: %v", result)
}

Core Concepts

Clients and Servers
  • client.Client: Interface for communicating with MCP servers
  • server.Server: Core component for implementing MCP servers
Tools

Tools allow you to expose functionality to LLMs:

// Register a tool with a struct for type-safe parameters
s.Tool("calculate", "Perform calculations", func(ctx *server.Context, args struct {
	Operation string `enum:"add,subtract,multiply,divide"` // Tag-based validation
	X         float64
	Y         float64
}) (string, error) {
	// Implementation...
})
Resources

Resources provide data to LLMs:

// Register a static resource
s.Resource("app/version", "Get application version",
	func(ctx *server.Context) (string, error) {
		return "1.0.0", nil
	})

// Register a resource with parameters
s.Resource("users/{id}", "Get user information",
	func(ctx *server.Context, args struct {
		ID string `path:"id"`
	}) (map[string]interface{}, error) {
		return map[string]interface{}{
			"id": args.ID,
			"name": "Example User",
		}, nil
	})
Prompts

Prompts define reusable templates for LLM interactions:

// Register a prompt template
s.Prompt("greeting", "Greet a user",
	func(ctx *server.Context, args struct {
		Name string
		Service string
	}) (string, error) {
		return fmt.Sprintf("Hello %s, welcome to %s!", args.Name, args.Service), nil
	})
Transports

GoMCP supports multiple transport layers:

  • stdio: For CLI tools and direct LLM integration
  • WebSocket: For web applications with bidirectional communication
  • Server-Sent Events (SSE): For web applications with a hybrid communication pattern:
    • Server-to-client messages use SSE for real-time streaming
    • Client-to-server messages use HTTP POST requests
    • The server provides a message endpoint URL via the SSE connection
    • Ideal for applications needing real-time updates with standard HTTP infrastructure
  • HTTP: For simple RESTful interfaces
  • Unix Socket: For high-performance interprocess communication
  • UDP: For low-overhead, high-throughput communication
  • MQTT: For publish/subscribe messaging in IoT applications
  • NATS: For cloud-native, high-performance messaging
  • gRPC: For service-to-service communication with strong typing
Server Management

GoMCP provides robust functionality for managing external MCP server processes:

// Load configuration from file
client, err := client.NewClient("my-client",
	client.WithServerConfig("mcpservers.json", "task-master-ai"),
)

// Or define configuration programmatically
config := client.ServerConfig{
	MCPServers: map[string]client.ServerDefinition{
		"memory-server": {
			Command: "npx",
			Args: []string{"-y", "@modelcontextprotocol/server-memory"},
			Env: map[string]string{"DEBUG": "true"},
		},
	},
}

client, err := client.NewClient("my-client",
	client.WithServers(config, "memory-server"),
)

The server management system:

  • Automatically starts the specified server process
  • Connects the client to the server
  • Manages environment variables and arguments
  • Properly terminates the server when the client is closed

For advanced use cases, you can use the ServerRegistry directly:

registry := client.NewServerRegistry()
if err := registry.LoadConfig("mcpservers.json"); err != nil {
	log.Fatalf("Failed to load configuration: %v", err)
}

// Get all available servers
serverNames, _ := registry.GetServerNames()

// Get a client for a specific server
memoryClient, _ := registry.GetClient("memory")

// Stop all servers when done
registry.StopAll()

Examples

The examples/ directory contains complete examples demonstrating various features:

  • examples/minimal/: Basic client and server examples
  • examples/sampling/: Examples of text generation via the sampling API
  • examples/server_config/: Server management and configuration examples
  • examples/server/: Various server implementation patterns

Documentation

  • GoDoc: API reference documentation
  • docs/: Additional documentation and guides
    • docs/examples/: Detailed feature guides
    • docs/getting-started/: Getting started guides
    • docs/api-reference/: Detailed API documentation

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

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

Documentation

Overview

Package gomcp provides a Go implementation of the Model Context Protocol (MCP).

Overview

The Model Context Protocol (MCP) is a standardized communication protocol designed to facilitate interaction between applications and Large Language Models (LLMs). This library provides a complete Go implementation of the protocol with support for all specification versions (2024-11-05, 2025-03-26, and draft) with automatic version detection and negotiation.

Core Features

- Full MCP protocol implementation - Client and server components - Multiple transport options (stdio, HTTP, WebSocket, Server-Sent Events) - Automatic protocol version negotiation - Comprehensive type safety - Support for all MCP operations: tools, resources, prompts, and sampling - Flexible configuration options - Process management for external MCP servers - Server configuration file support

Organization

The library is organized into the following main packages:

  • github.com/localrivet/gomcp/client: Client implementation for consuming MCP services
  • github.com/localrivet/gomcp/server: Server implementation for hosting MCP services
  • github.com/localrivet/gomcp/transport: Transport layer implementations
  • github.com/localrivet/gomcp/mcp: Core protocol definitions and version handling

Basic Usage

## Client Example

import "github.com/localrivet/gomcp/client"

// Create a new client
c, err := client.NewClient("my-client",
  client.WithProtocolVersion("2025-03-26"),
  client.WithProtocolNegotiation(true),
)
if err != nil {
  log.Fatalf("Failed to create client: %v", err)
}

// Call a tool on the MCP server
result, err := c.CallTool("say_hello", map[string]interface{}{
  "name": "World",
})

## Server Configuration Example

// Connect to an external MCP server defined in a config file
c, err := client.NewClient("",
  client.WithServerConfig("mcpservers.json", "task-master-ai"),
)
if err != nil {
  log.Fatalf("Failed to create client: %v", err)
}
defer c.Close() // Will also stop the server process

// The mcpservers.json file defines how to start and connect to the server:
// {
//   "mcpServers": {
//     "task-master-ai": {
//       "command": "npx",
//       "args": ["-y", "--package=task-master-ai", "task-master-ai"],
//       "env": { "ANTHROPIC_API_KEY": "${ANTHROPIC_API_KEY}" }
//     }
//   }
// }

## Server Example

import "github.com/localrivet/gomcp/server"

// Create a new server
s := server.NewServer("example-server",
  server.WithLogger(logger),
).AsStdio()

// Register a tool
s.Tool("say_hello", "Greet someone", func(ctx *server.Context, args struct {
  Name string `json:"name"`
}) (string, error) {
  return fmt.Sprintf("Hello, %s!", args.Name), nil
})

// Start the server
s.Run()

Process Management

GOMCP includes robust functionality for managing external MCP server processes:

  • Server configuration loading from JSON files
  • Automatic process management (start/stop) for external servers
  • Environment variable handling and substitution
  • Support for different types of servers (NPX-based, Docker, etc.)
  • Clean process termination on client close

For more information, see the docs/examples/server-config.md documentation.

Specification Compliance

This library implements the Model Context Protocol as defined at: https://github.com/microsoft/modelcontextprotocol

For detailed documentation, examples, and specifications, see: https://modelcontextprotocol.github.io/

For more examples, see the examples directory in this repository.

Versioning

gomcp follows semantic versioning. The current version is available through the Version constant.

Index

Constants

View Source
const Version = "0.1.0"

Version is the current version of the gomcp library

Variables

This section is empty.

Functions

This section is empty.

Types

This section is empty.

Directories

Path Synopsis
Package client provides the client-side implementation of the MCP protocol.
Package client provides the client-side implementation of the MCP protocol.
test
Package test provides test utilities for the client package.
Package test provides test utilities for the client package.
test/draft
Package draft provides test utilities specific to the draft protocol version.
Package draft provides test utilities specific to the draft protocol version.
mcp
Package mcp contains the core types and interfaces for the Model Context Protocol.
Package mcp contains the core types and interfaces for the Model Context Protocol.
draft
Package draft implements the latest draft version of the MCP specification.
Package draft implements the latest draft version of the MCP specification.
v20241105
Package v20241105 implements the 2024-11-05 version of the MCP specification.
Package v20241105 implements the 2024-11-05 version of the MCP specification.
v20250326
Package v20250326 implements the 2025-03-26 version of the MCP specification.
Package v20250326 implements the 2025-03-26 version of the MCP specification.
Package server provides the server-side implementation of the MCP protocol.
Package server provides the server-side implementation of the MCP protocol.
test
Package test provides utilities for testing the MCP implementation.
Package test provides utilities for testing the MCP implementation.
Package transport provides the transport layer implementations for the MCP protocol.
Package transport provides the transport layer implementations for the MCP protocol.
grpc
Package grpc provides a gRPC transport implementation for the MCP protocol.
Package grpc provides a gRPC transport implementation for the MCP protocol.
http
Package http provides an HTTP implementation of the MCP transport.
Package http provides an HTTP implementation of the MCP transport.
mqtt
Package mqtt provides a MQTT implementation of the MCP transport.
Package mqtt provides a MQTT implementation of the MCP transport.
nats
Package nats provides a NATS implementation of the MCP transport.
Package nats provides a NATS implementation of the MCP transport.
sse
Package sse provides a Server-Sent Events implementation of the MCP transport.
Package sse provides a Server-Sent Events implementation of the MCP transport.
stdio
Package stdio provides a standard I/O implementation of the MCP transport.
Package stdio provides a standard I/O implementation of the MCP transport.
udp
Package udp provides a UDP implementation of the MCP transport.
Package udp provides a UDP implementation of the MCP transport.
unix
Package unix provides a Unix Domain Socket implementation of the MCP transport.
Package unix provides a Unix Domain Socket implementation of the MCP transport.
ws
Package ws provides a WebSocket implementation of the MCP transport.
Package ws provides a WebSocket implementation of the MCP transport.
util
conversion
Package conversion provides utilities for converting between types.
Package conversion provides utilities for converting between types.
schema
Package schema provides utilities for generating JSON Schema from Go structs.
Package schema provides utilities for generating JSON Schema from Go structs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL