server

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2025 License: MIT Imports: 21 Imported by: 1

README

GoMCP Server

The GoMCP server is a Go implementation of the Multimodal Chat Protocol (MCP), which enables communication between clients and AI systems.

Features

  • Supports multiple transport mechanisms:
    • Standard I/O (default)
    • WebSockets
    • Server-Sent Events (SSE)
    • HTTP
  • Implements the MCP protocol specification:
    • Draft version
    • v2024-11-05
    • v2025-03-26
  • Extensible design with the ability to register tools and resources
  • Supports JSON Schema for tool and resource arguments
  • Provides helper methods for executing tools and accessing resources

Quick Start

package main

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

func main() {
	// Create a new server
	srv := server.NewServer("my-server")

	// Register a tool
	srv.Tool("hello", "Says hello to someone", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
		name, _ := args["name"].(string)
		if name == "" {
			name = "world"
		}
		return "Hello, " + name + "!", nil
	})

	// Register a resource
	srv.Resource("/greeting/{name}", "A greeting resource", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
		name, _ := args["name"].(string)
		if name == "" {
			name = "world"
		}
		return "Hello, " + name + "!", nil
	})

	// Start the server using standard I/O (default transport)
	if err := srv.AsStdio().Serve(); err != nil {
		panic(err)
	}
}

Server Initialization

To create a new MCP server:

srv := server.NewServer("my-server")

Transport Options

The server supports multiple transport mechanisms. You can choose a transport using the following methods:

// Use Standard I/O (default)
srv.AsStdio().Serve()

// Use WebSockets
srv.AsWebsocket("localhost", 8080).Serve()

// Use Server-Sent Events (SSE)
srv.AsSSE("localhost", 8080).Serve()

// Use HTTP
srv.AsHTTP("localhost", 8080).Serve()

Tool Registration

Tools are functions that can be executed by clients. To register a tool:

srv.Tool("tool-name", "Tool description", handler)

There are several ways to define handlers:

1. Map Handler
srv.Tool("echo", "Echoes input", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
    message := args["message"].(string)
    return message, nil
})
2. Struct Handler
type EchoArgs struct {
    Message string `json:"message"`
}

srv.Tool("echo", "Echoes input", func(ctx *server.Context, args *EchoArgs) (interface{}, error) {
    return args.Message, nil
})
3. Composite Tools

You can create tools that call other tools internally:

srv.Tool("composite", "Calls multiple tools", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
    // Call the "echo" tool
    result, err := ctx.ExecuteTool("echo", map[string]interface{}{
        "message": "Hello from composite tool",
    })
    if err != nil {
        return nil, err
    }
    return result, nil
})
Tool Helper Methods

The Context type provides several helper methods for working with tools:

  • ExecuteTool: Executes a tool from within another tool handler
  • GetRegisteredTools: Returns a list of all registered tools
  • GetToolDetails: Returns detailed information about a specific tool

Resource Registration

Resources are data or services that can be accessed by clients using URIs. To register a resource:

srv.Resource("/path/to/resource", "Resource description", handler)
Resource Paths

Resources use URI templates to define paths, which can include path parameters:

// Simple resource with no parameters
srv.Resource("/hello", "Greeting resource", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
    return "Hello, world!", nil
})

// Resource with path parameters
srv.Resource("/users/{id}", "Get user by ID", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
    id := args["id"].(string)
    return "User: " + id, nil
})

// Resource with multiple path parameters
srv.Resource("/users/{userId}/posts/{postId}", "Get post by user and post ID", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
    userId := args["userId"].(string)
    postId := args["postId"].(string)
    return fmt.Sprintf("User: %s, Post: %s", userId, postId), nil
})

// Resource with wildcard path parameter (matches multiple path segments)
srv.Resource("/docs/{path*}", "Access documentation", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
    path := args["path"].(string)
    return "Documentation for: " + path, nil
})
Resource Handler Types

Similar to tools, there are several ways to define resource handlers:

1. Map Handler
srv.Resource("/hello", "Greeting resource", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
    name, _ := args["name"].(string)
    if name == "" {
        name = "world"
    }
    return "Hello, " + name + "!", nil
})
2. Struct Handler
type UserParams struct {
    ID string `json:"id"`
}

srv.Resource("/users/{id}", "Get user by ID", func(ctx *server.Context, args *UserParams) (interface{}, error) {
    return "User: " + args.ID, nil
})
Composite Resources

Resources can call other resources internally:

srv.Resource("/combined", "Combined resource", func(ctx *server.Context, args map[string]interface{}) (interface{}, error) {
    // Call another resource
    result, err := ctx.ExecuteResource("/hello")
    if err != nil {
        return nil, err
    }
    return "Combined: " + result.(string), nil
})
Resource Helper Methods

The Context type provides several helper methods for working with resources:

  • ExecuteResource: Executes a resource from within another resource handler
  • GetRegisteredResources: Returns a list of all registered resources
  • GetResourceDetails: Returns detailed information about a specific resource

Content Response Formatting

Both tool and resource responses are automatically formatted based on the MCP specification version being used:

  • For string responses, they are wrapped in a content object with type "text"
  • For map/struct responses with a "content" field, they are used as-is
  • For other types, they are converted to JSON and then wrapped as text content

For example:

// String response will be formatted as text content
return "Hello, world!", nil

// Structured response will be formatted as is
return map[string]interface{}{
    "content": []map[string]interface{}{
        {
            "type": "text",
            "text": "Hello, world!",
        },
    },
}, nil

// Image response will be formatted appropriately
return map[string]interface{}{
    "imageUrl": "https://example.com/image.jpg",
    "altText": "Example image",
}, nil

Error Handling

Both tool and resource handlers can return errors, which are automatically formatted as JSON-RPC error responses:

return nil, fmt.Errorf("something went wrong")

This will generate a response like:

{
  "jsonrpc": "2.0",
  "id": "request-id",
  "error": {
    "code": -32000,
    "message": "something went wrong"
  }
}

JSON Schema Support

The server automatically extracts JSON Schema from struct types used in tool and resource handlers:

type UserArgs struct {
    Name     string `json:"name" required:"true"`
    Age      int    `json:"age" minimum:"0"`
    Email    string `json:"email" format:"email"`
    IsActive bool   `json:"isActive"`
}

srv.Tool("create-user", "Creates a new user", func(ctx *server.Context, args *UserArgs) (interface{}, error) {
    // Implementation
})

The schema is extracted using struct tags and reflection, and is used to validate incoming requests and generate documentation.

Customizing Server Behavior

You can customize the server's behavior using various options:

srv := server.NewServer("my-server").
    WithLogger(customLogger).  // Set a custom logger
    WithMiddleware(middleware) // Add middleware for request/response processing

Documentation

Overview

Package server provides the server-side implementation of the MCP protocol.

Package server provides the server-side implementation of the MCP protocol.

Package server provides the server-side implementation of the MCP protocol.

Package server provides the server-side implementation of the MCP protocol.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractProtocolVersion added in v1.2.0

func ExtractProtocolVersion(params json.RawMessage) (string, error)

ExtractProtocolVersion extracts the protocol version from the initialize request

func FormatResourceResponse added in v1.2.0

func FormatResourceResponse(uri string, result interface{}, version string) map[string]interface{}

FormatResourceResponse formats a response according to MCP validation requirements. This ensures that text/blob content items have the required fields and format.

func HandleMessage added in v1.2.0

func HandleMessage(s *serverImpl, message []byte) ([]byte, error)

HandleMessage handles an incoming message from the transport. It parses the message, routes it to the appropriate handler, and returns the response.

func HandleMessageWithVersion added in v1.2.0

func HandleMessageWithVersion(srv Server, message []byte, version string) ([]byte, error)

HandleMessageWithVersion handles a JSON-RPC message with a forced MCP version This is primarily used for testing

func SimpleJSONResponse added in v1.2.0

func SimpleJSONResponse(data interface{}) map[string]interface{}

SimpleJSONResponse creates a JSON resource response

func SimpleTextResponse added in v1.2.0

func SimpleTextResponse(text string) map[string]interface{}

SimpleTextResponse creates a simple text response map

func SubstituteVariables added in v1.2.0

func SubstituteVariables(content string, variables map[string]interface{}) (string, error)

SubstituteVariables replaces variables in template content with values from variables map. Variables in the template should be in the format {{variable_name}}.

func ValidateContentForVersion added in v1.2.0

func ValidateContentForVersion(content SamplingContentHandler, version string) error

ValidateContentForVersion checks if a content handler is valid for the given protocol version

Types

type AudioResource added in v1.2.0

type AudioResource struct {
	// URL is the URL of the audio file. Required for all versions.
	URL string
	// Data is the base64-encoded audio data. Used in 2025-03-26 version.
	Data string
	// MimeType is the MIME type of the audio file. Required for all versions.
	MimeType string
	// AltText is an optional descriptive text for the audio
	AltText string
}

AudioResource represents an audio resource to be returned from a handler

func (AudioResource) ToResourceResponse added in v1.2.0

func (a AudioResource) ToResourceResponse() map[string]interface{}

ToResourceResponse converts the AudioResource to a protocol-specific representation

type AudioSamplingContent added in v1.2.0

type AudioSamplingContent struct {
	Data     string
	MimeType string
}

AudioSamplingContent creates an audio content struct for sampling messages

func (*AudioSamplingContent) ToMessageContent added in v1.2.0

func (a *AudioSamplingContent) ToMessageContent() SamplingMessageContent

ToMessageContent converts AudioSamplingContent to a SamplingMessageContent

func (*AudioSamplingContent) Validate added in v1.2.0

func (a *AudioSamplingContent) Validate() error

Validate ensures the audio content is valid

type ClientInfo added in v1.2.0

type ClientInfo struct {
	SamplingSupported bool
	SamplingCaps      SamplingCapabilities
	ProtocolVersion   string
}

ClientInfo represents information about a connected client

type ClientSession

type ClientSession struct {
	ID              SessionID         // Unique session identifier
	ClientInfo      ClientInfo        // Information about the client
	Created         time.Time         // When the session was created
	LastActive      time.Time         // Last time the session was active
	ProtocolVersion string            // Negotiated protocol version
	Metadata        map[string]string // Additional session metadata
}

ClientSession represents a session with a client

type ContentItem added in v1.2.0

type ContentItem struct {
	Type     string      `json:"type"`
	Text     string      `json:"text,omitempty"`
	ImageURL string      `json:"imageUrl,omitempty"`
	AltText  string      `json:"altText,omitempty"`
	URL      string      `json:"url,omitempty"`
	Title    string      `json:"title,omitempty"`
	Data     interface{} `json:"data,omitempty"`
	MimeType string      `json:"mimeType,omitempty"`
	Filename string      `json:"filename,omitempty"`
	Blob     string      `json:"blob,omitempty"` // Add blob support for MCP Inspector validation
}

ContentItem represents a single content item in a response.

func BlobContent added in v1.2.0

func BlobContent(blob string, mimeType string) ContentItem

BlobContent creates a new blob content item.

func FileContent added in v1.2.0

func FileContent(fileURL string, filename string, mimeType string) ContentItem

FileContent creates a content item of type "file"

func ImageContent added in v1.2.0

func ImageContent(imageURL string, altText string, optMimeType ...string) ContentItem

ImageContent creates a new image content item.

func JSONContent added in v1.2.0

func JSONContent(data interface{}) ContentItem

JSONContent creates a content item of type "json"

func LinkContent added in v1.2.0

func LinkContent(url, title string) ContentItem

LinkContent creates a new link content item.

func TextContent added in v1.2.0

func TextContent(text string) ContentItem

TextContent creates a new text content item.

type ContentType added in v1.2.0

type ContentType string

ContentType represents the type of content in a prompt message.

const (
	ContentTypeText     ContentType = "text"
	ContentTypeImage    ContentType = "image"
	ContentTypeAudio    ContentType = "audio"
	ContentTypeResource ContentType = "resource"
)

type Context added in v0.1.11

type Context struct {

	// The raw request bytes
	RequestBytes []byte

	// The parsed request
	Request *Request

	// The response to be sent back
	Response *Response

	// Logger for this request
	Logger *slog.Logger

	// Version of the MCP protocol being used
	Version string

	// Request ID for tracing
	RequestID string

	// Metadata for storing contextual information during request processing
	Metadata map[string]interface{}
	// contains filtered or unexported fields
}

Context represents the context for a server request.

func NewContext added in v0.1.11

func NewContext(ctx context.Context, requestBytes []byte, server *serverImpl) (*Context, error)

NewContext creates a new request context.

func (*Context) Deadline added in v1.2.0

func (c *Context) Deadline() (deadline interface{}, ok bool)

Deadline returns the time when this context will be canceled, if any.

func (*Context) Done added in v1.1.2

func (c *Context) Done() <-chan struct{}

Done returns a channel that's closed when this context is canceled.

func (*Context) Err added in v1.2.0

func (c *Context) Err() error

Err returns nil if Done is not yet closed, otherwise it returns the reason.

func (*Context) ExecuteResource added in v1.2.0

func (c *Context) ExecuteResource(resourcePath string) (interface{}, error)

ExecuteResource provides a convenient way to execute a resource from within another resource handler. This is useful for resource composition and internal resource calls.

func (*Context) ExecuteTool added in v1.2.0

func (c *Context) ExecuteTool(toolName string, args map[string]interface{}) (interface{}, error)

ExecuteTool provides a convenient way to execute a tool from within another tool handler. This is useful for tool composition and internal tool calls.

func (*Context) GetRegisteredResources added in v1.2.0

func (c *Context) GetRegisteredResources() ([]*Resource, error)

GetRegisteredResources returns a list of all resources registered with the server. This is useful for handlers that need to inspect or enumerate available resources.

func (*Context) GetRegisteredTools added in v1.2.0

func (c *Context) GetRegisteredTools() ([]*Tool, error)

GetRegisteredTools returns a list of all tools registered with the server. This is useful for tools that need to inspect or enumerate available tools.

func (*Context) GetResourceDetails added in v1.2.0

func (c *Context) GetResourceDetails(resourcePath string) (*Resource, error)

GetResourceDetails returns detailed information about a specific resource. This is useful for handlers that need to inspect the capabilities of other resources.

func (*Context) GetSamplingController added in v1.2.0

func (c *Context) GetSamplingController() (*SamplingController, error)

GetSamplingController provides access to the server's sampling controller.

func (*Context) GetToolDetails added in v1.2.0

func (c *Context) GetToolDetails(toolName string) (*Tool, error)

GetToolDetails returns detailed information about a specific tool. This is useful for tools that need to inspect the capabilities of other tools.

func (*Context) RequestSampling added in v1.2.0

func (c *Context) RequestSampling(messages []SamplingMessage, preferences SamplingModelPreferences,
	systemPrompt string, maxTokens int) (*SamplingResponse, error)

RequestSampling sends a sampling request using the context's session information. This is a convenience wrapper around the server's RequestSamplingFromContext method.

func (*Context) RequestSamplingWithPriority added in v1.2.0

func (c *Context) RequestSamplingWithPriority(messages []SamplingMessage, preferences SamplingModelPreferences,
	systemPrompt string, maxTokens int, priority int) (*SamplingResponse, error)

RequestSamplingWithPriority sends a sampling request with a specific priority level. The priority affects timeout and retry behavior according to the server's configuration.

func (*Context) ValidateSamplingRequest added in v1.2.0

func (c *Context) ValidateSamplingRequest(messages []SamplingMessage, maxTokens int) error

ValidateSamplingRequest validates that a sampling request is valid for the current protocol version and client capabilities.

func (*Context) Value added in v1.2.0

func (c *Context) Value(key interface{}) interface{}

Value returns the value associated with this context for key, or nil.

type FileResource added in v1.2.0

type FileResource struct {
	URL      string
	Filename string
	MimeType string
}

FileResource represents a file resource

func (FileResource) ToResourceResponse added in v1.2.0

func (fr FileResource) ToResourceResponse() map[string]interface{}

ToResourceResponse converts FileResource to ResourceResponse

type ImageResource added in v1.2.0

type ImageResource struct {
	URL      string
	AltText  string
	MimeType string
}

ImageResource represents an image resource

func (ImageResource) ToResourceResponse added in v1.2.0

func (ir ImageResource) ToResourceResponse() map[string]interface{}

ToResourceResponse converts ImageResource to ResourceResponse

type ImageSamplingContent added in v1.2.0

type ImageSamplingContent struct {
	Data     string
	MimeType string
}

ImageSamplingContent creates an image content struct for sampling messages

func (*ImageSamplingContent) ToMessageContent added in v1.2.0

func (i *ImageSamplingContent) ToMessageContent() SamplingMessageContent

ToMessageContent converts ImageSamplingContent to a SamplingMessageContent

func (*ImageSamplingContent) Validate added in v1.2.0

func (i *ImageSamplingContent) Validate() error

Validate ensures the image content is valid

type InvalidParametersError added in v1.2.0

type InvalidParametersError struct {
	Message string
}

InvalidParametersError represents an error with invalid parameters

func NewInvalidParametersError added in v1.2.0

func NewInvalidParametersError(message string) *InvalidParametersError

NewInvalidParametersError creates a new InvalidParametersError

func (*InvalidParametersError) Error added in v1.2.0

func (e *InvalidParametersError) Error() string

type JSONResource added in v1.2.0

type JSONResource struct {
	Data interface{}
}

JSONResource represents a JSON resource

func (JSONResource) ToResourceResponse added in v1.2.0

func (jr JSONResource) ToResourceResponse() map[string]interface{}

ToResourceResponse converts JSONResource to ResourceResponse

type LinkResource added in v1.2.0

type LinkResource struct {
	URL   string
	Title string
}

LinkResource represents a link resource

func (LinkResource) ToResourceResponse added in v1.2.0

func (lr LinkResource) ToResourceResponse() map[string]interface{}

ToResourceResponse converts LinkResource to ResourceResponse

type Option added in v1.2.0

type Option func(*serverImpl)

Option represents a server configuration option. Server options are used to customize the behavior and configuration of a server instance when it is created with NewServer.

func WithLogger added in v1.0.1

func WithLogger(logger *slog.Logger) Option

WithLogger sets the server's logger.

This option configures the structured logger used by the server for logging events, errors, and debug information.

Example:

jsonHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelDebug,
})
logger := slog.New(jsonHandler)

server := server.NewServer("my-service",
    server.WithLogger(logger),
)

func WithSamplingConfig added in v1.2.0

func WithSamplingConfig(config *SamplingConfig) Option

WithSamplingConfig returns a server option that sets the sampling configuration.

type Prompt added in v1.2.0

type Prompt struct {
	Name        string
	Description string
	Templates   []PromptTemplate
	Arguments   []PromptArgument
}

Prompt represents a prompt registered with the server.

type PromptArgument added in v1.2.0

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Required    bool   `json:"required"`
}

PromptArgument represents an argument for a prompt.

type PromptContent added in v1.2.0

type PromptContent struct {
	Type     ContentType            `json:"type"`
	Text     string                 `json:"text,omitempty"`
	Data     string                 `json:"data,omitempty"`
	MimeType string                 `json:"mimeType,omitempty"`
	Resource map[string]interface{} `json:"resource,omitempty"`
}

PromptContent represents the content of a prompt message.

type PromptTemplate added in v1.2.0

type PromptTemplate struct {
	Role    string
	Content string
	// For storing template variables like {{var}}
	Variables []string
}

PromptTemplate represents a template for a prompt with a role and content.

func Assistant added in v0.1.11

func Assistant(content string) PromptTemplate

Assistant creates an assistant prompt template.

func System added in v0.1.11

func System(content string) PromptTemplate

System creates a system prompt template.

func User added in v0.1.11

func User(content string) PromptTemplate

User creates a user prompt template.

type ProtocolSamplingConfig added in v1.2.0

type ProtocolSamplingConfig struct {
	MaxTokens             int
	SupportedContentTypes map[string]bool
	StreamingSupported    bool
}

ProtocolSamplingConfig defines protocol-specific sampling configuration.

type RPCError added in v1.2.0

type RPCError struct {
	Code    int         `json:"code"`    // Error code
	Message string      `json:"message"` // Error message
	Data    interface{} `json:"data,omitempty"`
}

RPCError represents a JSON-RPC 2.0 error object.

func (*RPCError) Error added in v1.2.0

func (e *RPCError) Error() string

Error returns the error message, implementing the error interface

type Request added in v1.2.0

type Request struct {
	// JSON-RPC 2.0 fields
	JSONRPC string          `json:"jsonrpc"`
	ID      interface{}     `json:"id,omitempty"`     // string or number or null
	Method  string          `json:"method"`           // The method to call
	Params  json.RawMessage `json:"params,omitempty"` // Parameters for the method call

	// Parsed params based on method type
	// These fields are populated after parsing
	ToolName     string
	ToolArgs     map[string]interface{}
	ResourcePath string
	PromptName   string
	PromptArgs   map[string]interface{}
}

Request represents an incoming JSON-RPC 2.0 request.

type RequestSamplingOptions added in v1.2.0

type RequestSamplingOptions struct {
	Timeout          time.Duration // Maximum time to wait for a response
	MaxRetries       int           // Maximum number of retry attempts on timeout
	RetryInterval    time.Duration // Time to wait between retries
	IgnoreCapability bool          // Whether to ignore client capability validation
	ForceSession     bool          // Whether to force using the specified session
}

RequestSamplingOptions defines options for sampling requests

func DefaultSamplingOptions added in v1.2.0

func DefaultSamplingOptions() RequestSamplingOptions

DefaultSamplingOptions returns the default options for sampling requests

type Resource added in v1.2.0

type Resource struct {
	Path        string
	Description string
	Handler     ResourceHandler
	Schema      interface{}
	Template    *wilduri.Template
	IsTemplate  bool // Whether this resource is a template with parameters
}

Resource represents a resource registered with the server.

type ResourceConverter added in v1.2.0

type ResourceConverter interface {
	ToResourceResponse() map[string]interface{}
}

ResourceConverter allows custom types to be converted to resource responses

type ResourceHandler added in v1.2.0

type ResourceHandler func(ctx *Context, args interface{}) (interface{}, error)

ResourceHandler is a function that handles resource requests.

func ConvertToResourceHandler added in v1.2.0

func ConvertToResourceHandler(handler interface{}) (ResourceHandler, bool)

ConvertToResourceHandler converts a function to a ResourceHandler if possible.

type ResourceResponse added in v1.2.0

type ResourceResponse struct {
	Content  []ContentItem          `json:"content"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
	IsError  bool                   `json:"isError,omitempty"`
}

ResourceResponse is a standard response for MCP resources. It ensures the response format follows the MCP protocol.

func NewResourceResponse added in v1.2.0

func NewResourceResponse(items ...ContentItem) ResourceResponse

NewResourceResponse creates a new resource response with the given content items.

func (ResourceResponse) AsError added in v1.2.0

func (r ResourceResponse) AsError() ResourceResponse

AsError marks the response as an error.

func (ResourceResponse) WithMetadata added in v1.2.0

func (r ResourceResponse) WithMetadata(metadata map[string]interface{}) ResourceResponse

WithMetadata adds metadata to the resource response.

type Response added in v1.2.0

type Response struct {
	// JSON-RPC 2.0 fields
	JSONRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id,omitempty"`     // Must match request ID
	Result  interface{} `json:"result,omitempty"` // Result data, null if error
	Error   *RPCError   `json:"error,omitempty"`  // Error data, null if success
}

Response represents an outgoing JSON-RPC 2.0 response.

type SamplingCapabilities added in v1.2.0

type SamplingCapabilities struct {
	Supported    bool
	TextSupport  bool
	ImageSupport bool
	AudioSupport bool
}

SamplingCapabilities defines what sampling features a client supports

func DetectClientCapabilities added in v1.2.0

func DetectClientCapabilities(protocolVersion string) SamplingCapabilities

DetectClientCapabilities infers client capabilities from the protocol version and any other available information

type SamplingConfig added in v1.2.0

type SamplingConfig struct {
	// Rate limiting settings
	MaxRequestsPerMinute  int  // Maximum number of sampling requests per minute
	MaxConcurrentRequests int  // Maximum number of concurrent sampling requests
	MaxTokensPerRequest   int  // Maximum tokens allowed per request
	PerClientRateLimit    bool // Whether to apply rate limits per client

	// Timeout settings
	DefaultTimeout time.Duration // Default timeout for sampling requests
	MaxTimeout     time.Duration // Maximum allowed timeout for sampling requests

	// Retry settings
	DefaultMaxRetries    int           // Default number of retries for failed requests
	DefaultRetryInterval time.Duration // Default interval between retries

	// Priority settings
	EnablePrioritization bool // Whether to enable request prioritization
	DefaultPriority      int  // Default priority for sampling requests (1-10, 10 being highest)

	// Resource allocation
	ResourceQuota map[string]int // Resource quotas for different content types

	// Error handling
	GracefulDegradation bool // Whether to enable graceful degradation on errors

	// Protocol-specific settings
	ProtocolDefaults map[string]*ProtocolSamplingConfig // Protocol-specific settings
}

SamplingConfig defines server-side configuration options for sampling operations.

func NewDefaultSamplingConfig added in v1.2.0

func NewDefaultSamplingConfig() *SamplingConfig

NewDefaultSamplingConfig creates a new sampling configuration with sensible defaults.

type SamplingContentHandler added in v1.2.0

type SamplingContentHandler interface {
	ToMessageContent() SamplingMessageContent
	Validate() error
}

SamplingContentHandler is the interface for all sampling content handlers

type SamplingController added in v1.2.0

type SamplingController struct {
	// contains filtered or unexported fields
}

SamplingController manages sampling operations with rate limiting and prioritization.

func NewSamplingController added in v1.2.0

func NewSamplingController(config *SamplingConfig, logger *slog.Logger) *SamplingController

NewSamplingController creates a new controller with the specified configuration.

func (*SamplingController) CanProcessRequest added in v1.2.0

func (sc *SamplingController) CanProcessRequest(sessionID SessionID) bool

CanProcessRequest checks if a sampling request can be processed based on rate limits.

func (*SamplingController) CompleteRequest added in v1.2.0

func (sc *SamplingController) CompleteRequest(sessionID SessionID)

CompleteRequest marks a request as completed, updating rate limiting counters.

func (*SamplingController) GetConcurrentRequestCount added in v1.2.0

func (sc *SamplingController) GetConcurrentRequestCount() int

GetConcurrentRequestCount returns the current number of concurrent requests.

func (*SamplingController) GetRequestOptions added in v1.2.0

func (sc *SamplingController) GetRequestOptions(priority int) RequestSamplingOptions

GetRequestOptions returns appropriate request options based on configuration.

func (*SamplingController) RecordRequest added in v1.2.0

func (sc *SamplingController) RecordRequest(sessionID SessionID)

RecordRequest records a sampling request for rate limiting purposes.

func (*SamplingController) Stop added in v1.2.0

func (sc *SamplingController) Stop()

Stop stops the sampling controller and cleans up resources.

func (*SamplingController) ValidateForProtocol added in v1.2.0

func (sc *SamplingController) ValidateForProtocol(protocol string, messages []SamplingMessage, maxTokens int) error

ValidateForProtocol validates sampling parameters against protocol constraints.

type SamplingCreateMessageParams added in v1.2.0

type SamplingCreateMessageParams struct {
	Messages         []SamplingMessage        `json:"messages"`
	ModelPreferences SamplingModelPreferences `json:"modelPreferences"`
	SystemPrompt     string                   `json:"systemPrompt,omitempty"`
	MaxTokens        int                      `json:"maxTokens,omitempty"`
}

SamplingCreateMessageParams represents the parameters for a sampling/createMessage request.

type SamplingMessage added in v1.2.0

type SamplingMessage struct {
	Role    string                 `json:"role"`
	Content SamplingMessageContent `json:"content"`
}

SamplingMessage represents a message in a sampling conversation.

func CreateAudioSamplingMessage added in v1.2.0

func CreateAudioSamplingMessage(role, audioData, mimeType string) SamplingMessage

CreateAudioSamplingMessage creates a sampling message with audio content.

func CreateImageSamplingMessage added in v1.2.0

func CreateImageSamplingMessage(role, imageData, mimeType string) SamplingMessage

CreateImageSamplingMessage creates a sampling message with image content.

func CreateSamplingMessage added in v1.2.0

func CreateSamplingMessage(role string, content SamplingContentHandler) (SamplingMessage, error)

CreateSamplingMessage creates a sampling message with the provided content handler

func CreateTextSamplingMessage added in v1.2.0

func CreateTextSamplingMessage(role, text string) SamplingMessage

CreateTextSamplingMessage creates a sampling message with text content.

type SamplingMessageContent added in v1.2.0

type SamplingMessageContent struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
}

SamplingMessageContent represents the content of a sampling message.

func (*SamplingMessageContent) IsValidForVersion added in v1.2.0

func (c *SamplingMessageContent) IsValidForVersion(version string) bool

IsValidForVersion checks if the content type is valid for the given protocol version

type SamplingModelHint added in v1.2.0

type SamplingModelHint struct {
	Name string `json:"name"`
}

SamplingModelHint represents a hint for model selection in sampling requests.

type SamplingModelPreferences added in v1.2.0

type SamplingModelPreferences struct {
	Hints                []SamplingModelHint `json:"hints,omitempty"`
	CostPriority         *float64            `json:"costPriority,omitempty"`
	SpeedPriority        *float64            `json:"speedPriority,omitempty"`
	IntelligencePriority *float64            `json:"intelligencePriority,omitempty"`
}

SamplingModelPreferences represents the model preferences for a sampling request.

type SamplingResponse added in v1.2.0

type SamplingResponse struct {
	Role       string                 `json:"role"`
	Content    SamplingMessageContent `json:"content"`
	Model      string                 `json:"model,omitempty"`
	StopReason string                 `json:"stopReason,omitempty"`
}

SamplingResponse represents the response to a sampling/createMessage request.

type Server

type Server interface {
	// Run starts the server and blocks until it exits.
	//
	// This method initializes the server, starts listening for connections,
	// and processes incoming requests. It blocks until the server encounters
	// an error or is explicitly stopped.
	//
	// Example:
	//  if err := server.Run(); err != nil {
	//      log.Fatalf("Server error: %v", err)
	//  }
	Run() error

	// Tool registers a tool with the server.
	//
	// The name parameter is the unique identifier for the tool. The description
	// parameter provides human-readable documentation. The handler parameter is
	// a function that implements the tool's logic.
	//
	// Tool handlers can have one of the following signatures:
	//  func(ctx *Context) (interface{}, error)
	//  func(ctx *Context, args T) (interface{}, error)
	//  func(ctx *Context) error
	//  func(ctx *Context, args T) error
	//
	// Where T is any struct type that can be unmarshaled from JSON. The struct
	// fields should use `json` tags to map to JSON property names.
	//
	// Example:
	//  server.Tool("add", "Add two numbers", func(ctx *server.Context, args struct {
	//      X float64 `json:"x" required:"true"`
	//      Y float64 `json:"y" required:"true"`
	//  }) (float64, error) {
	//      return args.X + args.Y, nil
	//  })
	Tool(name string, description string, handler interface{}) Server

	// WithAnnotations adds annotations to a tool.
	//
	// Annotations provide additional metadata about a tool, such as examples,
	// parameter descriptions, or usage notes.
	//
	// Example:
	//  server.Tool("greet", "Greet a user", greetHandler).
	//      WithAnnotations("greet", map[string]interface{}{
	//          "examples": []map[string]interface{}{
	//              {
	//                  "description": "Greet a user by name",
	//                  "args": map[string]interface{}{
	//                      "name": "Alice",
	//                  },
	//              },
	//          },
	//      })
	WithAnnotations(toolName string, annotations map[string]interface{}) Server

	// Resource registers a resource with the server.
	//
	// The path parameter defines the resource path, which can include path
	// parameters in the format {paramName}. The description parameter provides
	// human-readable documentation. The handler parameter is a function that
	// implements the resource's logic.
	//
	// Example:
	//  server.Resource("/users/{id}", "Get user information", func(ctx *server.Context, params struct {
	//      ID string `path:"id"`
	//  }) (interface{}, error) {
	//      return getUserById(params.ID)
	//  })
	Resource(path string, description string, handler interface{}) Server

	// Prompt registers a prompt with the server.
	//
	// The name parameter is the unique identifier for the prompt. The description
	// parameter provides human-readable documentation. The template parameters
	// define the prompt template and can be either a string or a function that
	// generates the template.
	//
	// Example:
	//  server.Prompt("greeting", "Greeting template",
	//      "Hello, {{name}}! Welcome to {{service}}.")
	Prompt(name string, description string, template ...interface{}) Server

	// Root sets the allowed root paths.
	//
	// Root paths are the entry points for resource navigation. At least one
	// root path must be defined for resources to be accessible.
	//
	// Example:
	//  server.Root("/api/v1", "/api/v2")
	Root(paths ...string) Server

	// AsStdio configures the server to use Standard I/O for communication.
	//
	// This is useful for child processes or integration with other MCP systems.
	// An optional logFile parameter can be provided to redirect stdio logs.
	//
	// Example:
	//  server.AsStdio("./mcp-server.log")
	AsStdio(logFile ...string) Server

	// AsWebsocket configures the server to use WebSocket for communication.
	//
	// The address parameter specifies the host and port to listen on.
	//
	// Example:
	//  server.AsWebsocket("localhost:8080")
	AsWebsocket(address string) Server

	// AsSSE configures the server to use Server-Sent Events for communication.
	//
	// The address parameter specifies the host and port to listen on.
	//
	// Example:
	//  server.AsSSE("localhost:8080")
	AsSSE(address string) Server

	// AsHTTP configures the server to use HTTP for communication.
	//
	// The address parameter specifies the host and port to listen on.
	//
	// Example:
	//  server.AsHTTP("localhost:8080")
	AsHTTP(address string) Server

	// GetServer returns the underlying server implementation.
	//
	// This is primarily used for advanced configuration or testing.
	GetServer() *serverImpl

	// GetRoots returns the list of registered root paths.
	GetRoots() []string

	// IsPathInRoots checks if a path is within any registered root.
	IsPathInRoots(path string) bool

	// WithSamplingConfig sets the sampling configuration for the server.
	//
	// Sampling configuration controls how sampling requests are handled,
	// including rate limits, caching, and other performance parameters.
	//
	// Example:
	//  config := server.NewSamplingConfig().WithRateLimit(10)
	//  server.WithSamplingConfig(config)
	WithSamplingConfig(config *SamplingConfig) Server

	// WithSamplingController sets a custom sampling controller for the server.
	//
	// This is an advanced method for applications that need fine-grained
	// control over sampling behavior.
	WithSamplingController(controller *SamplingController) Server

	// Logger returns the server's configured logger.
	//
	// This can be used to access the logger for custom logging needs.
	Logger() *slog.Logger
}

Server represents an MCP server with fluent configuration methods. It provides a builder-style API for configuring all aspects of an MCP server including tools, resources, prompts, and transport options.

func NewServer

func NewServer(name string, options ...Option) Server

NewServer creates a new MCP server with the given name and options.

The server is initialized with default settings that can be customized using the provided options. By default, the server uses stdio transport and default logging configuration.

The name parameter is a human-readable identifier for the server, used in logs and server information.

Example:

// Create a basic server with default settings
server := server.NewServer("my-service")

// Create a server with custom logger and sampling configuration
customLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
samplingConfig := server.NewSamplingConfig().WithRateLimit(100)

server := server.NewServer("my-service",
    server.WithLogger(customLogger),
    server.WithSamplingConfig(samplingConfig),
)

type SessionID added in v1.2.0

type SessionID string

SessionID is a unique identifier for a client session

type SessionManager added in v1.2.0

type SessionManager struct {
	// contains filtered or unexported fields
}

SessionManager manages client sessions

func NewSessionManager added in v1.2.0

func NewSessionManager() *SessionManager

NewSessionManager creates a new session manager

func (*SessionManager) CloseSession added in v1.2.0

func (sm *SessionManager) CloseSession(id SessionID) bool

CloseSession removes a session

func (*SessionManager) CreateSession added in v1.2.0

func (sm *SessionManager) CreateSession(clientInfo ClientInfo, protocolVersion string) *ClientSession

CreateSession creates a new client session

func (*SessionManager) GetSession added in v1.2.0

func (sm *SessionManager) GetSession(id SessionID) (*ClientSession, bool)

GetSession retrieves a session by ID

func (*SessionManager) UpdateClientCapabilities added in v1.2.0

func (sm *SessionManager) UpdateClientCapabilities(id SessionID, caps SamplingCapabilities) bool

UpdateClientCapabilities updates the capabilities of a client session based on protocol version and any other information available

func (*SessionManager) UpdateSession added in v1.2.0

func (sm *SessionManager) UpdateSession(id SessionID, update func(*ClientSession)) bool

UpdateSession updates an existing session

type TextResource added in v1.2.0

type TextResource struct {
	Text string
}

TextResource represents a simple text resource

func (TextResource) ToResourceResponse added in v1.2.0

func (tr TextResource) ToResourceResponse() map[string]interface{}

ToResourceResponse converts TextResource to ResourceResponse

type TextSamplingContent added in v1.2.0

type TextSamplingContent struct {
	Text string
}

TextSamplingContent creates a text content struct for sampling messages

func (*TextSamplingContent) ToMessageContent added in v1.2.0

func (t *TextSamplingContent) ToMessageContent() SamplingMessageContent

ToMessageContent converts TextSamplingContent to a SamplingMessageContent

func (*TextSamplingContent) Validate added in v1.2.0

func (t *TextSamplingContent) Validate() error

Validate ensures the text content is valid

type Tool added in v1.2.0

type Tool struct {
	Name        string
	Description string
	Handler     ToolHandler
	Schema      interface{}
	Annotations map[string]interface{} // Additional metadata about the tool
}

Tool represents a tool registered with the server.

type ToolHandler added in v1.2.0

type ToolHandler func(ctx *Context, args interface{}) (interface{}, error)

ToolHandler is a function that handles tool calls.

Directories

Path Synopsis
Package test provides utilities for testing the MCP implementation.
Package test provides utilities for testing the MCP implementation.

Jump to

Keyboard shortcuts

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