server

package
v1.6.4 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2025 License: MIT Imports: 31 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
  • MCP Session Architecture: Comprehensive session management with transport-aware data extraction
  • Automated Root Fetching: Automatic workspace root discovery following MCP protocol

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"`
}

## Session Management

GoMCP v1.5.5+ includes comprehensive session management through the MCP Session Architecture:

### Accessing Session Data

```go
srv.Tool("analyze_workspace", "Analyze workspace with session context", func(ctx *server.Context, args struct {
    AnalysisType string `json:"analysis_type"`
}) (interface{}, error) {
    // Access session environment (from transport)
    env := ctx.Session.Env()
    apiKey := env["OPENAI_API_KEY"]
    
    // Access workspace roots (from init + automated roots/list)
    roots := ctx.Session.Roots()
    
    // Access client capabilities
    caps := ctx.Session.Capabilities()
    
    return map[string]interface{}{
        "workspace_roots": roots,
        "has_api_key": apiKey != "",
        "supports_sampling": caps.Sampling.Supported,
        "supports_audio": caps.Audio.Supported,
        "analysis_type": args.AnalysisType,
    }, nil
})
Session Data Sources

Session data is automatically extracted from transport layers:

  • stdio: Environment from process environment variables
  • HTTP: Environment from request headers (X-Env-* pattern)
  • WebSocket: Environment from connection headers
  • SSE: Environment from initial request headers
Automated Root Discovery

The server automatically:

  1. Extracts workspace roots from clientInfo.roots during initialization
  2. Detects if client supports roots capability
  3. Sends roots/list requests after notifications/initialized
  4. Processes responses and updates session context
  5. Makes roots available via ctx.Session.Roots()
Backward Compatibility

All existing context methods continue to work:

// Legacy methods (still supported)
roots := ctx.GetRoots()
primaryRoot := ctx.GetPrimaryRoot()
inWorkspace := ctx.InRoots("/path/to/file")

// New session methods
sessionRoots := ctx.Session.Roots()
env := ctx.Session.Env()
caps := ctx.Session.Capabilities()

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. It offers a comprehensive API for building and running MCP servers that can register tools, resources, and prompt templates for client interaction.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultGRPCServerOptions added in v1.2.1

func DefaultGRPCServerOptions() []grpc.Option

DefaultGRPCServerOptions returns a set of default options for gRPC server.

func ExtractProtocolVersion added in v1.2.0

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

ExtractProtocolVersion extracts the protocol version from the initialize request params. It attempts to parse the protocolVersion field from JSON-RPC params, handling different data types and formats that clients might send.

Parameters:

  • params: The raw JSON params from an initialize request

Returns:

  • The extracted protocol version as a string, or empty string if not found
  • An error if the params cannot be parsed

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. Supports both single JSON-RPC messages and batch messages (arrays) as required by the MCP specification.

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 and allows processing messages with a specific protocol version regardless of what was negotiated during initialization. It provides a simplified subset of method handlers compared to the main HandleMessage function.

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 all {{variable}} patterns in the content string with their corresponding values from the variables map. If a variable is missing, the placeholder is left unchanged.

func TestEnsureContentsArray added in v1.5.0

func TestEnsureContentsArray(response map[string]interface{}, uri string) map[string]interface{}

TestEnsureContentsArray exposes ensureContentsArray for testing

func TestEnsureValidContentItems added in v1.5.0

func TestEnsureValidContentItems(items []interface{}) []interface{}

TestEnsureValidContentItems exposes ensureValidContentItems for testing

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. This function combines content validation with protocol version compatibility checking to ensure that messages conform to both content-specific rules and protocol constraints.

Parameters:

  • content: The content handler to validate
  • version: The protocol version to check against

Returns:

  • nil if the content is valid for the protocol version
  • An error describing the validation failure otherwise

func WithGRPCKeepAlive added in v1.2.1

func WithGRPCKeepAlive(time, timeout time.Duration) grpc.Option

WithGRPCKeepAlive configures keepalive parameters for the gRPC transport.

func WithGRPCMaxMessageSize added in v1.2.1

func WithGRPCMaxMessageSize(size int) grpc.Option

WithGRPCMaxMessageSize sets the maximum message size for the gRPC transport.

func WithGRPCTLS added in v1.2.1

func WithGRPCTLS(certFile, keyFile, caFile string) grpc.Option

WithGRPCTLS configures TLS for the gRPC transport.

func WithGRPCTimeout added in v1.2.1

func WithGRPCTimeout(timeout time.Duration) grpc.Option

WithGRPCTimeout sets the connection timeout for the gRPC transport.

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. This implementation of SamplingContentHandler manages audio content for sampling conversations, storing the audio data and its MIME type.

func (*AudioSamplingContent) ToMessageContent added in v1.2.0

func (a *AudioSamplingContent) ToMessageContent() SamplingMessageContent

ToMessageContent converts AudioSamplingContent to a SamplingMessageContent. This method implements the SamplingContentHandler interface for audio content, transforming the internal representation into the standardized message content format.

Returns:

  • A SamplingMessageContent object configured for audio content

func (*AudioSamplingContent) Validate added in v1.2.0

func (a *AudioSamplingContent) Validate() error

Validate ensures the audio content is valid. This method checks that the audio content meets the necessary requirements, including non-empty data and MIME type.

Returns:

  • nil if the content is valid
  • An error explaining the validation failure otherwise

type CancelledNotificationParams added in v1.2.2

type CancelledNotificationParams struct {
	RequestID string `json:"requestId"`        // ID of the request being cancelled
	Reason    string `json:"reason,omitempty"` // Optional reason for cancellation
}

CancelledNotificationParams contains parameters for a cancelled notification

type CapabilityCache added in v1.5.1

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

CapabilityCache manages the caching and change tracking of server capabilities

func NewCapabilityCache added in v1.5.1

func NewCapabilityCache() *CapabilityCache

NewCapabilityCache creates a new capability cache

func (*CapabilityCache) GetPendingNotifications added in v1.5.1

func (c *CapabilityCache) GetPendingNotifications() [][]byte

GetPendingNotifications returns and clears all pending notifications

func (*CapabilityCache) MarkPromptsChanged added in v1.5.1

func (c *CapabilityCache) MarkPromptsChanged()

MarkPromptsChanged marks that prompts have changed and should trigger a notification

func (*CapabilityCache) MarkResourcesChanged added in v1.5.1

func (c *CapabilityCache) MarkResourcesChanged()

MarkResourcesChanged marks that resources have changed and should trigger a notification

func (*CapabilityCache) MarkToolsChanged added in v1.5.1

func (c *CapabilityCache) MarkToolsChanged()

MarkToolsChanged marks that tools have changed and should trigger a notification

func (*CapabilityCache) QueueNotification added in v1.5.1

func (c *CapabilityCache) QueueNotification(notification []byte)

QueueNotification adds a notification to be sent after client initialization

func (*CapabilityCache) ResetChangeFlags added in v1.5.1

func (c *CapabilityCache) ResetChangeFlags()

ResetChangeFlags resets all change tracking flags

type ClientInfo added in v1.2.0

type ClientInfo struct {
	SamplingSupported bool
	SamplingCaps      SamplingCapabilities
	ProtocolVersion   string
	Env               map[string]string // Environment variables from the client session
	Roots             []string          // Workspace root paths from the client session

}

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
	ResourceSubscriptions []string          // List of resource URIs this session is subscribed to
}

ClientSession represents a session with a client. It encapsulates all client-specific information including capabilities, negotiated protocol version, and session metadata needed for managing the client connection lifecycle.

func (*ClientSession) Capabilities added in v1.5.5

func (s *ClientSession) Capabilities() SamplingCapabilities

Capabilities returns the sampling capabilities from the client session

func (*ClientSession) Env added in v1.5.5

func (s *ClientSession) Env() map[string]string

Env returns the environment variables from the client session

func (*ClientSession) Roots added in v1.5.5

func (s *ClientSession) Roots() []string

Roots returns the workspace roots from the client session

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"`
	MimeType string      `json:"mimeType,omitempty"`
	Data     interface{} `json:"data,omitempty"`
	Filename string      `json:"filename,omitempty"`
}

ContentItem represents a single content item in tool/prompt responses

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. This function creates a properly formatted image content item for inclusion in MCP responses.

Parameters:

  • imageURL: The URL where the image can be accessed
  • altText: Accessibility description of the image content
  • optMimeType: Optional MIME type of the image (e.g., "image/png")

Returns:

  • A ContentItem of type "image" properly formatted for the MCP protocol

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. This function creates a properly formatted link content item for inclusion in MCP responses.

Parameters:

  • url: The target URL of the link
  • title: The display text or title for the link

Returns:

  • A ContentItem of type "link" properly formatted for the MCP protocol

func NewFileContent added in v1.6.2

func NewFileContent(mimeType string, data interface{}, filename string) ContentItem

NewFileContent creates a new file content item

func NewImageContent added in v1.6.2

func NewImageContent(imageURL, altText string) ContentItem

NewImageContent creates a new image content item

func NewLinkContent added in v1.6.2

func NewLinkContent(url, title string) ContentItem

NewLinkContent creates a new link content item

func NewTextContent added in v1.6.2

func NewTextContent(text string) ContentItem

NewTextContent creates a new text content item

func TextContent added in v1.2.0

func TextContent(text string) ContentItem

TextContent creates a new text content item. This function creates a properly formatted text content item for inclusion in MCP responses, handling edge cases like empty text to ensure protocol compliance.

Parameters:

  • text: The text content to include in the response

Returns:

  • A ContentItem of type "text" properly formatted for the MCP protocol

type ContentType added in v1.2.0

type ContentType string

ContentType represents the type of content in a prompt

const (
	// ContentTypeImage is used for image content, which requires an imageUrl
	ContentTypeImage ContentType = "image"

	// ContentTypeAudio is used for audio content, which requires audio data
	ContentTypeAudio ContentType = "audio"

	// ContentTypeResource is used for referencing resources by URI
	ContentTypeResource ContentType = "resource"
)

Content type constants define the supported content types for prompts.

const ContentTypeText ContentType = "text"

ContentTypeText is used for plain text content

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

	// Progress token for long-running operations (if present)
	ProgressToken string

	// Metadata for storing contextual information during request processing
	Metadata map[string]interface{}

	// this is a session id that is used to track the session
	Session *ClientSession
	// contains filtered or unexported fields
}

Context represents the execution context for a server request. It encapsulates all request-specific information including request data, response data, server reference, and metadata for tracking the request. Context objects are created for each incoming client request and provide access to server functionality through convenience methods.

func NewContext added in v0.1.11

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

NewContext creates a new request context for processing an incoming request. It parses the request bytes, initializes response structures, and extracts method-specific parameters based on the request method. This function is called for each incoming message to create a self-contained context for request processing.

Parameters:

  • ctx: Standard Go context for cancellation and timeouts
  • requestBytes: Raw JSON-RPC request bytes
  • server: Reference to the server implementation

Returns:

  • A new Context object ready for request processing
  • An error if request parsing fails

func (*Context) CancelRequest added in v1.2.2

func (c *Context) CancelRequest(reason string) error

CancelRequest sends a cancellation notification for this context's request This is typically used when a client wants to cancel an in-progress request it made to the server

func (*Context) CheckCancellation added in v1.2.2

func (c *Context) CheckCancellation() error

CheckCancellation checks if the context is cancelled and returns an error if it is This is useful for places in the code where periodic cancellation checks are needed

func (*Context) CompleteProgress added in v1.5.0

func (c *Context) CompleteProgress(finalMessage string) error

CompleteProgress marks the progress as complete and deactivates the progress token This should be called when a long-running operation finishes

func (*Context) CreateProgressReporter added in v1.5.0

func (c *Context) CreateProgressReporter(total *float64, initialMessage string) *mcp.ProgressReporter

CreateProgressReporter creates a new ProgressReporter for this context's request This provides a user-friendly API for progress reporting with automatic token management

func (*Context) CreateProgressToken added in v1.5.0

func (c *Context) CreateProgressToken() string

CreateProgressToken creates a new progress token for this request This should be called at the beginning of long-running operations to enable progress tracking

func (*Context) CreateSimpleProgressReporter added in v1.5.0

func (c *Context) CreateSimpleProgressReporter(total *float64) *mcp.ProgressReporter

CreateSimpleProgressReporter creates a basic ProgressReporter with minimal configuration

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. This method implements part of the standard Go context.Context interface.

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. This method implements part of the standard Go context.Context interface, allowing the Context to be used with functions expecting a cancellable context.

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. This method implements part of the standard Go context.Context interface.

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, allowing one resource to build upon another or reuse existing resource handlers. The method handles path matching, parameter extraction, and result formatting.

Parameters:

  • resourcePath: The path of the resource to execute

Returns:

  • The result of the resource execution
  • An error if the resource cannot be found or execution fails

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 when one tool needs to invoke another as part of its implementation. The method handles parameter validation and result formatting automatically.

Parameters:

  • toolName: The name of the tool to execute
  • args: A map of argument values to pass to the tool

Returns:

  • The result of the tool execution
  • An error if the tool cannot be found or execution fails

func (*Context) GetPrimaryRoot added in v1.5.3

func (c *Context) GetPrimaryRoot() string

GetPrimaryRoot returns the first registered root path, if any

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, such as implementing a custom resources/list endpoint or providing resource discovery functionality.

Returns:

  • A slice of Resource objects containing all registered resources
  • An error if the server reference is not available

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, such as implementing a custom tools/list endpoint or providing tool discovery functionality.

Returns:

  • A slice of Tool objects containing all registered tools
  • An error if the server reference is not available

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, validate resource availability, or provide detailed resource information to clients. The method supports both exact path matching and template pattern matching.

Parameters:

  • resourcePath: The path of the resource to retrieve details for

Returns:

  • A Resource object containing the resource's metadata and handler
  • An error if the resource doesn't exist or the server reference is not available

func (*Context) GetRoots added in v1.5.3

func (c *Context) GetRoots() []string

GetRoots returns all registered root paths from the server

func (*Context) GetSamplingController added in v1.2.0

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

GetSamplingController provides access to the server's sampling controller. The sampling controller manages rate limiting, request tracking, and other aspects of the server's sampling behavior. This method is used by sampling-related functions to access the controller for validation and configuration.

Returns:

  • A pointer to the server's SamplingController
  • An error if the server reference is not available or the controller is not initialized

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, validate tool availability before executing, or provide detailed tool information to clients.

Parameters:

  • toolName: The name of the tool to retrieve details for

Returns:

  • A Tool object containing the tool's metadata and handler
  • An error if the tool doesn't exist or the server reference is not available

func (*Context) GetValidatedArgs added in v1.5.0

func (c *Context) GetValidatedArgs(targetType reflect.Type) (interface{}, error)

GetValidatedArgs validates and converts request arguments to the expected type. This is a convenience method that combines argument validation and type conversion in a single call, returning the converted arguments ready for use by handlers.

The targetType parameter should be the reflect.Type of the expected argument struct. The method returns the converted arguments as interface{} or an error if validation fails.

Example:

argType := reflect.TypeOf((*MyArgsStruct)(nil))
args, err := ctx.GetValidatedArgs(argType)
if err != nil {
    return nil, err
}
myArgs := args.(*MyArgsStruct)

func (*Context) HasProgressToken added in v1.5.0

func (c *Context) HasProgressToken() bool

HasProgressToken returns true if this context has an active progress token

func (*Context) InRoots added in v1.5.3

func (c *Context) InRoots(path string) bool

InRoots checks if a path is within any registered root

func (*Context) IsCancelled added in v1.2.2

func (c *Context) IsCancelled() bool

IsCancelled checks if the request associated with this context has been cancelled

func (*Context) RegisterForCancellation added in v1.2.2

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

RegisterForCancellation registers this context's request to be cancellable Returns a channel that will be closed if the request is cancelled

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, which automatically uses the current context's session, protocol version, and other metadata when making the sampling request.

Parameters:

  • messages: A slice of SamplingMessage objects representing the conversation
  • preferences: Model preferences for the sampling request
  • systemPrompt: Optional system prompt to help guide the model's behavior
  • maxTokens: Maximum number of tokens to generate in the response

Returns:

  • A SamplingResponse containing the model's generated content
  • An error if the sampling request fails or the server is not available

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. Higher priority levels typically get more generous timeout and retry settings, while lower priority requests might have shorter timeouts and fewer retries.

Parameters:

  • messages: A slice of SamplingMessage objects representing the conversation
  • preferences: Model preferences for the sampling request
  • systemPrompt: Optional system prompt to help guide the model's behavior
  • maxTokens: Maximum number of tokens to generate in the response
  • priority: Priority level that determines timeout and retry behavior

Returns:

  • A SamplingResponse containing the model's generated content
  • An error if the sampling request fails, times out, or the server is not available

func (*Context) SendProgress added in v1.1.2

func (c *Context) SendProgress(progress float64, total *float64, message string) error

SendProgress sends a progress notification for this context's progress token If no progress token exists, this method does nothing and returns nil

func (*Context) StartProgressOperation added in v1.5.0

func (c *Context) StartProgressOperation(total *float64, initialMessage string) *mcp.ProgressReporter

StartProgressOperation creates a ProgressReporter and sends an initial notification This is a convenience method for starting progress tracking with a single call

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. It checks that the message content types are supported in the negotiated protocol version and that the requested token count is within acceptable limits.

Parameters:

  • messages: A slice of SamplingMessage objects to validate
  • maxTokens: The requested maximum token count for the response

Returns:

  • An error if validation fails, describing the specific validation error
  • nil if validation passes

func (*Context) ValidateToolArgs added in v1.5.0

func (c *Context) ValidateToolArgs(toolName string) (interface{}, error)

ValidateToolArgs validates tool arguments against a tool's schema. This method provides type-safe argument validation for tool handlers, ensuring that the provided arguments match the expected structure and types.

The toolName parameter identifies which tool's schema to use for validation. The method returns the validated arguments as interface{} or an error if validation fails.

Example:

args, err := ctx.ValidateToolArgs("calculator")
if err != nil {
    return nil, fmt.Errorf("invalid arguments: %w", err)
}
calcArgs := args.(*CalculatorArgs)

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. This method implements part of the standard Go context.Context interface.

type EmptyResponse added in v1.6.2

type EmptyResponse struct{}

EmptyResponse represents an empty success response

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. This implementation of SamplingContentHandler manages image content for sampling conversations, storing the image data and its MIME type.

func (*ImageSamplingContent) ToMessageContent added in v1.2.0

func (i *ImageSamplingContent) ToMessageContent() SamplingMessageContent

ToMessageContent converts ImageSamplingContent to a SamplingMessageContent. This method implements the SamplingContentHandler interface for image content, transforming the internal representation into the standardized message content format.

Returns:

  • A SamplingMessageContent object configured for image content

func (*ImageSamplingContent) Validate added in v1.2.0

func (i *ImageSamplingContent) Validate() error

Validate ensures the image content is valid. This method checks that the image content meets the necessary requirements, including non-empty data and MIME type.

Returns:

  • nil if the content is valid
  • An error explaining the validation failure otherwise

type InitializeResponse added in v1.6.2

type InitializeResponse struct {
	ProtocolVersion string                 `json:"protocolVersion"`
	ServerInfo      ServerInfo             `json:"serverInfo"`
	Capabilities    map[string]interface{} `json:"capabilities"`
}

InitializeResponse represents the response for initialize requests

func NewInitializeResponse added in v1.6.2

func NewInitializeResponse(protocolVersion string, serverInfo ServerInfo, capabilities map[string]interface{}) *InitializeResponse

NewInitializeResponse creates a new InitializeResponse

type InvalidParametersError added in v1.2.0

type InvalidParametersError struct {
	// Message contains the error description
	Message string
}

InvalidParametersError represents an error with invalid parameters for prompt rendering or template variable substitution.

func NewInvalidParametersError added in v1.2.0

func NewInvalidParametersError(message string) *InvalidParametersError

NewInvalidParametersError creates a new InvalidParametersError with the given message. This is used when prompt parameters are missing or invalid.

func (*InvalidParametersError) Error added in v1.2.0

func (e *InvalidParametersError) Error() string

Error returns the error message string. This method implements the error interface.

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 WithProtocolVersion added in v1.5.0

func WithProtocolVersion(version string) Option

WithProtocolVersion sets a specific protocol version for the server to use. This bypasses the normal negotiation process and forces the server to use this version. This is useful for testing or when you need to enforce a specific protocol version.

Example:

server := server.NewServer("my-service",
    server.WithProtocolVersion("2025-03-26"),
)

func WithSamplingConfig added in v1.2.0

func WithSamplingConfig(config *SamplingConfig) Option

WithSamplingConfig returns a server option that sets the sampling configuration. This function generates a server configuration option that can be passed to NewServer or ServerBuilder to customize sampling behavior.

Parameters:

  • config: The sampling configuration to apply to the server

Returns:

  • An Option function that configures sampling when applied to a server

type OverflowStrategy added in v1.5.0

type OverflowStrategy int

OverflowStrategy defines how to handle buffer overflow when rate limiting

const (
	// DropOldest drops the oldest notifications when buffer is full
	DropOldest OverflowStrategy = iota

	// DropNewest drops the newest notifications when buffer is full
	DropNewest

	// CombineNotifications combines multiple notifications into summary notifications
	CombineNotifications

	// BlockUntilSpace blocks until buffer space is available (may cause delays)
	BlockUntilSpace
)

type ProgressNotificationHandler added in v1.5.0

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

ProgressNotificationHandler manages progress notifications and rate limiting

func NewProgressNotificationHandler added in v1.5.0

func NewProgressNotificationHandler(server *serverImpl) *ProgressNotificationHandler

NewProgressNotificationHandler creates a new progress notification handler

func (*ProgressNotificationHandler) CleanupRateLimiters added in v1.5.0

func (pnh *ProgressNotificationHandler) CleanupRateLimiters()

CleanupRateLimiters removes rate limiters for inactive tokens

func (*ProgressNotificationHandler) GetAllStatistics added in v1.5.0

func (pnh *ProgressNotificationHandler) GetAllStatistics() map[string]interface{}

GetAllStatistics returns statistics for all rate limiters

func (*ProgressNotificationHandler) GetConfiguration added in v1.5.0

func (pnh *ProgressNotificationHandler) GetConfiguration() *ProgressRateLimitConfig

GetConfiguration returns the current rate limit configuration

func (*ProgressNotificationHandler) GetOrCreateRateLimiter added in v1.5.0

func (pnh *ProgressNotificationHandler) GetOrCreateRateLimiter(progressToken string) *ProgressRateLimiter

GetOrCreateRateLimiter gets or creates a rate limiter for the given progress token

func (*ProgressNotificationHandler) GetProgressChannel added in v1.5.0

func (pnh *ProgressNotificationHandler) GetProgressChannel() *mcp.ProgressChannel

GetProgressChannel returns the bidirectional progress communication channel

func (*ProgressNotificationHandler) SetConfiguration added in v1.5.0

func (pnh *ProgressNotificationHandler) SetConfiguration(config *ProgressRateLimitConfig)

SetConfiguration updates the rate limiter configuration

type ProgressRateLimitConfig added in v1.5.0

type ProgressRateLimitConfig struct {
	// MaxNotificationsPerSecond is the maximum number of notifications allowed per second per token
	MaxNotificationsPerSecond int `json:"maxNotificationsPerSecond"`

	// BufferSize is the maximum number of notifications to buffer when rate limited
	BufferSize int `json:"bufferSize"`

	// OverflowStrategy defines how to handle buffer overflow
	OverflowStrategy OverflowStrategy `json:"overflowStrategy"`

	// CombineThreshold is the minimum time between notifications before combining them
	CombineThreshold time.Duration `json:"combineThreshold"`

	// EnableBatching enables batching of multiple notifications into single messages
	EnableBatching bool `json:"enableBatching"`

	// BatchSize is the maximum number of notifications to batch together
	BatchSize int `json:"batchSize"`

	// BatchTimeout is the maximum time to wait before sending a partial batch
	BatchTimeout time.Duration `json:"batchTimeout"`
}

ProgressRateLimitConfig defines configuration for progress notification rate limiting

func NewDefaultProgressRateLimitConfig added in v1.5.0

func NewDefaultProgressRateLimitConfig() *ProgressRateLimitConfig

NewDefaultProgressRateLimitConfig creates a default rate limit configuration

type ProgressRateLimiter added in v1.5.0

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

ProgressRateLimiter implements rate limiting for progress notifications with buffering and queue management

func NewProgressRateLimiter added in v1.5.0

func NewProgressRateLimiter(config *ProgressRateLimitConfig) *ProgressRateLimiter

NewProgressRateLimiter creates a new rate limiter with the given configuration

func (*ProgressRateLimiter) BufferNotification added in v1.5.0

func (prl *ProgressRateLimiter) BufferNotification(notification *mcp.ProgressNotification) error

BufferNotification adds a notification to the buffer when rate limited

func (*ProgressRateLimiter) CanSendNotification added in v1.5.0

func (prl *ProgressRateLimiter) CanSendNotification() bool

CanSendNotification checks if a progress notification can be sent based on rate limits

func (*ProgressRateLimiter) GetStatistics added in v1.5.0

func (prl *ProgressRateLimiter) GetStatistics() map[string]interface{}

GetStatistics returns rate limiting statistics

func (*ProgressRateLimiter) ProcessBuffer added in v1.5.0

func (prl *ProgressRateLimiter) ProcessBuffer() []*mcp.ProgressNotification

ProcessBuffer processes buffered notifications that can now be sent

type Prompt added in v1.2.0

type Prompt struct {
	// Name is the unique identifier for this prompt
	Name string

	// Description explains what the prompt is for
	Description string

	// Templates are the ordered sequence of message templates that make up the prompt
	Templates []PromptTemplate

	// Arguments are the parameters that can be passed when rendering the prompt
	Arguments []PromptArgument
}

Prompt represents a prompt registered with the server. A prompt is a named collection of templates that can be rendered with provided variable values.

type PromptArgument added in v1.2.0

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

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"`
}

PromptContent represents the content of a prompt message

type PromptGetResponse added in v1.6.2

type PromptGetResponse struct {
	Description string          `json:"description"`
	Messages    []PromptMessage `json:"messages"`
}

PromptGetResponse represents the response for prompts/get requests

func NewPromptGetResponse added in v1.6.2

func NewPromptGetResponse(description string, messages []PromptMessage) *PromptGetResponse

NewPromptGetResponse creates a new PromptGetResponse

type PromptInfo added in v1.6.2

type PromptInfo struct {
	Name        string           `json:"name"`
	Description string           `json:"description"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

PromptInfo represents information about a single prompt

type PromptListResponse added in v1.6.2

type PromptListResponse struct {
	Prompts    []PromptInfo `json:"prompts"`
	NextCursor string       `json:"nextCursor,omitempty"`
}

PromptListResponse represents the response for prompts/list requests

func NewPromptListResponse added in v1.6.2

func NewPromptListResponse(prompts []PromptInfo, nextCursor string) *PromptListResponse

NewPromptListResponse creates a new PromptListResponse

type PromptMessage added in v1.6.2

type PromptMessage struct {
	Role    string        `json:"role"`
	Content PromptContent `json:"content"`
}

PromptMessage represents a single message in a prompt response

type PromptTemplate added in v1.2.0

type PromptTemplate struct {
	// Role defines who is speaking in this template ("user" or "assistant")
	Role string

	// Content contains the template text with variables in {{variable}} format
	Content string
}

PromptTemplate represents a template for a prompt with a role and content. Templates can contain variables in the format {{variable}} which are substituted when the prompt is rendered. Only "user" and "assistant" roles are supported per MCP specification.

func Assistant added in v0.1.11

func Assistant(content string) PromptTemplate

Assistant creates an assistant prompt template. Assistant prompts represent previous or example responses from the language model.

func User added in v0.1.11

func User(content string) PromptTemplate

User creates a user prompt template. User prompts represent messages from the user to the language model.

type ProtocolSamplingConfig added in v1.2.0

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

ProtocolSamplingConfig defines protocol-specific sampling configuration. Different protocol versions have different capabilities and constraints, and this structure captures those version-specific settings.

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. It includes a numeric error code, a human-readable message, and optional additional data. Error codes follow the JSON-RPC 2.0 specification: -32700 for parse errors, -32600 for invalid requests, -32601 for method not found, -32602 for invalid params, and -32603 for internal errors.

func (*RPCError) Error added in v1.2.0

func (e *RPCError) Error() string

Error returns the error message, implementing the error interface. This method allows RPCError to be used as a standard Go error.

Returns:

  • The error message as a string

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. It contains both the raw JSON-RPC fields and parsed method-specific fields which are populated during request processing based on the method type. The struct combines generic JSON-RPC structure with MCP-specific fields to avoid multiple parsing steps.

type RequestCanceller added in v1.2.2

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

RequestCanceller manages cancellable requests and handles cancellation notifications

func NewRequestCanceller added in v1.2.2

func NewRequestCanceller() *RequestCanceller

NewRequestCanceller creates a new request canceller

func (*RequestCanceller) Cancel added in v1.2.2

func (rc *RequestCanceller) Cancel(requestID interface{}, reason string) bool

Cancel cancels a request by closing its cancellation channel Returns true if the request was found and cancelled, false otherwise

func (*RequestCanceller) Deregister added in v1.2.2

func (rc *RequestCanceller) Deregister(requestID interface{})

Deregister removes a request from the cancellation registry without cancelling it This should be called when a request completes normally

func (*RequestCanceller) IsCancelled added in v1.2.2

func (rc *RequestCanceller) IsCancelled(requestID interface{}) bool

IsCancelled checks if a request has been cancelled Returns true if the request is cancelled, false otherwise

func (*RequestCanceller) Register added in v1.2.2

func (rc *RequestCanceller) Register(requestID interface{}) <-chan struct{}

Register registers a request as cancellable and returns a channel that will be closed on cancellation

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. This struct configures the behavior of sampling requests, including timeouts, retry behavior, and capability validation requirements.

func DefaultSamplingOptions added in v1.2.0

func DefaultSamplingOptions() RequestSamplingOptions

DefaultSamplingOptions returns the default options for sampling requests. This function provides a standard configuration for timeout and retry behavior that is suitable for most sampling operations.

Returns:

  • A RequestSamplingOptions struct with sensible default values

type Resource added in v1.2.0

type Resource struct {
	// Path is the URL path pattern for the resource
	Path string

	// Description explains what the resource provides
	Description string

	// Handler is the function that executes when the resource is accessed
	Handler interface{}

	// Schema defines the expected input format for the resource
	Schema interface{}

	// IsTemplate indicates if this is a template resource (path contains {})
	IsTemplate bool

	// Annotations contains additional metadata about the resource
	Annotations map[string]interface{}

	// Template is the parsed path template used for matching URLs
	Template *wilduri.Template
}

Resource represents a resource registered with the server. Resources are endpoints that clients can access to retrieve structured data.

type ResourceContent added in v1.6.2

type ResourceContent struct {
	URI     string        `json:"uri"`
	Text    string        `json:"text,omitempty"`
	Content []ContentItem `json:"content,omitempty"`
}

ResourceContent represents a single resource content item

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 ResourceInfo added in v1.6.2

type ResourceInfo struct {
	URI         string `json:"uri"`
	Name        string `json:"name"`
	Description string `json:"description"`
	MimeType    string `json:"mimeType"`
}

ResourceInfo represents information about a single resource

type ResourceListResponse added in v1.6.2

type ResourceListResponse struct {
	Resources  []ResourceInfo `json:"resources"`
	NextCursor string         `json:"nextCursor,omitempty"`
}

ResourceListResponse represents the response for resources/list requests

func NewResourceListResponse added in v1.6.2

func NewResourceListResponse(resources []ResourceInfo, nextCursor string) *ResourceListResponse

NewResourceListResponse creates a new ResourceListResponse

type ResourceReadResponse added in v1.6.2

type ResourceReadResponse struct {
	Contents []ResourceContent `json:"contents"`
}

ResourceReadResponse represents the response for resources/read requests

func NewResourceReadResponse added in v1.6.2

func NewResourceReadResponse(contents []ResourceContent) *ResourceReadResponse

NewResourceReadResponse creates a new ResourceReadResponse

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 ResourceTemplateInfo added in v1.6.2

type ResourceTemplateInfo struct {
	URITemplate string                 `json:"uriTemplate"`
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	MimeType    string                 `json:"mimeType,omitempty"`
	Annotations map[string]interface{} `json:"annotations,omitempty"`
}

ResourceTemplateInfo represents information about a single resource template

type ResourceTemplatesListResponse added in v1.6.2

type ResourceTemplatesListResponse struct {
	ResourceTemplates []ResourceTemplateInfo `json:"resourceTemplates"`
	NextCursor        string                 `json:"nextCursor,omitempty"`
}

ResourceTemplatesListResponse represents the response for resources/templates/list requests

func NewResourceTemplatesListResponse added in v1.6.2

func NewResourceTemplatesListResponse(templates []ResourceTemplateInfo, nextCursor string) *ResourceTemplatesListResponse

NewResourceTemplatesListResponse creates a new ResourceTemplatesListResponse

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. It follows the JSON-RPC 2.0 specification with a result field for successful responses and an error field for failed ones. The ID field must match the corresponding request ID to allow clients to correlate responses with their requests.

type RootInfo added in v1.6.2

type RootInfo struct {
	URI  string `json:"uri"`
	Name string `json:"name,omitempty"`
}

RootInfo represents information about a single root

type RootsListResponse added in v1.6.2

type RootsListResponse struct {
	Roots []RootInfo `json:"roots"`
}

RootsListResponse represents the response for roots/list requests

func NewRootsListResponse added in v1.6.2

func NewRootsListResponse(roots []RootInfo) *RootsListResponse

NewRootsListResponse creates a new RootsListResponse

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. This function analyzes the protocol version to determine which features and content types the client is likely to support, particularly for sampling operations.

Parameters:

  • protocolVersion: The MCP protocol version negotiated with the client

Returns:

  • A SamplingCapabilities struct describing the client's supported features

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. This comprehensive configuration structure controls all aspects of sampling behavior, including rate limiting, timeouts, retry policies, prioritization, and protocol-specific settings.

func NewDefaultSamplingConfig added in v1.2.0

func NewDefaultSamplingConfig() *SamplingConfig

NewDefaultSamplingConfig creates a new sampling configuration with sensible defaults. This function provides a pre-configured SamplingConfig with reasonable values for all settings, suitable for most server deployments without customization.

Returns:

  • A pointer to a new SamplingConfig struct with default values

type SamplingContentHandler added in v1.2.0

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

SamplingContentHandler is the interface for all sampling content handlers. This interface defines the contract that all content type implementations must follow, allowing for consistent handling of different content types (text, image, audio) in the sampling system.

type SamplingController added in v1.2.0

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

SamplingController manages sampling operations with rate limiting and prioritization. This component enforces rate limits, tracks request statistics, manages prioritization, and validates requests against protocol-specific constraints to ensure reliable and fair resource allocation for sampling operations.

func NewSamplingController added in v1.2.0

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

NewSamplingController creates a new controller with the specified configuration. This function initializes all components of the sampling controller, including the rate limiter and request tracking system, and starts the background goroutine for periodically resetting rate limits.

Parameters:

  • config: The sampling configuration to use (or nil for default configuration)
  • logger: A structured logger for recording controller events

Returns:

  • A fully initialized SamplingController ready for managing sampling requests

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. This method evaluates both global concurrent request limits and per-client rate limits (if enabled) to determine if a new request should be accepted or rejected.

Parameters:

  • sessionID: The client session ID for per-client rate limiting

Returns:

  • true if the request can be processed, false if it would exceed 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. This method decrements the concurrent request counter when a sampling request finishes processing, regardless of whether it succeeded or failed.

Parameters:

  • sessionID: The client session ID for the completed request

func (*SamplingController) GetConcurrentRequestCount added in v1.2.0

func (sc *SamplingController) GetConcurrentRequestCount() int

GetConcurrentRequestCount returns the current number of concurrent requests. This method is useful for monitoring and debugging the server's sampling workload.

Returns:

  • The current count of active sampling requests being processed

func (*SamplingController) GetRequestOptions added in v1.2.0

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

GetRequestOptions returns appropriate request options based on configuration. This method calculates timeout and retry parameters for a sampling request based on its priority level, applying adjustments according to the controller's configuration and prioritization settings.

Parameters:

  • priority: The priority level of the request (1-10, with 10 being highest)

Returns:

  • RequestSamplingOptions containing configured timeout and retry settings

func (*SamplingController) RecordRequest added in v1.2.0

func (sc *SamplingController) RecordRequest(sessionID SessionID)

RecordRequest records a sampling request for rate limiting purposes. This method updates the concurrent request counter and per-client request counter (if enabled) when a new sampling request begins processing.

Parameters:

  • sessionID: The client session ID for per-client rate tracking

func (*SamplingController) Stop added in v1.2.0

func (sc *SamplingController) Stop()

Stop stops the sampling controller and cleans up resources. This method should be called when shutting down the server to ensure proper cleanup of background goroutines and other 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. This method checks that a sampling request conforms to the limitations of the specified protocol version, including token count limits and supported content types.

Parameters:

  • protocol: The protocol version to validate against
  • messages: The conversation messages to validate
  • maxTokens: The requested maximum token count

Returns:

  • nil if valid, or an error describing the validation failure

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. This struct contains all the information needed to make a complete sampling request to the client, including the conversation history, model preferences, system prompt, and token limits.

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. This struct encapsulates a single message exchange between a user and an assistant, including the role of the speaker and the content of the message.

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. This is a helper function for constructing properly formatted and validated sampling messages for different content types.

Parameters:

  • role: The role of the message sender (e.g., "user", "assistant")
  • content: The content handler implementation for the specific content type

Returns:

  • A properly formatted SamplingMessage
  • An error if content validation fails

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. It contains the type of content (text, image, etc.) and associated data, allowing for multimodal message exchanges in sampling conversations.

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. Different protocol versions support different content types, and this method validates whether the current content type is supported in the specified version.

Parameters:

  • version: The protocol version to check against

Returns:

  • true if the content type is supported in the specified version, false otherwise

type SamplingModelHint added in v1.2.0

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

SamplingModelHint represents a hint for model selection in sampling requests. Hints provide optional guidance to the client about which AI models might be appropriate for handling a particular sampling request.

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. These preferences allow the server to communicate desired characteristics for the AI model that will handle the sampling request, such as optimizing for cost, speed, or intelligence.

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. It contains the AI-generated response content, the role of the responder (typically "assistant"), optional model identification, and information about why the response ended.

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

	// Shutdown gracefully shuts down the server.
	//
	// This method stops accepting new connections and gracefully terminates
	// existing connections. It returns any error encountered during shutdown.
	//
	// Example:
	//  if err := server.Shutdown(); err != nil {
	//      log.Printf("Server shutdown error: %v", err)
	//  }
	Shutdown() 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 must
	// be a function with the signature:
	//   func(ctx *Context, args *StructType) (interface{}, error)
	//
	// Where StructType is a pointer to a struct and can be nil. The schema is automatically
	// extracted from the struct type using reflection and JSON tags.
	//
	// Optional annotations can be provided as additional map parameters to add
	// metadata that can be used by clients.
	//
	// Example:
	//  server.Tool("calculator", "Perform calculations", func(ctx *Context, args struct{
	//		Operation string `json:"operation"`
	//		A float64 `json:"a"`
	//		B float64 `json:"b"`
	//	}) (interface{}, error) {
	//      // Implementation here - args.Operation, args.A, args.B are fully typed
	//      return result, nil
	//  })
	Tool(name, description string, handler interface{}, annotations ...map[string]interface{}) Server

	// Resource registers a resource with the server.
	//
	// The pattern parameter is a URL path pattern that matches requests to this
	// resource. The description parameter provides human-readable documentation.
	// The handler parameter must be a function with signature:
	//   func(ctx *Context, args *StructType) (interface{}, error)
	//
	// Where StructType is a pointer to a struct and can be nil. The schema is automatically
	// extracted from the struct type using reflection and JSON tags.
	//
	// Path parameters are extracted from URI templates (e.g., /users/{id}) and
	// JSON parameters come from request body. Use struct tags to map them:
	//   - `path:"name"` for URI template parameters
	//   - `json:"name"` for JSON body parameters
	//
	// Example:
	//  server.Resource("/users/{id}", "Update user name", func(ctx *Context, args struct{
	//		ID   string `path:"id"`
	//		Name string `json:"name"`
	//	}) (interface{}, error) {
	//      // args.ID contains the path parameter from /users/{id}
	//      // args.Name contains the JSON body parameter
	//      user, err := getUserById(args.ID)
	//      if err != nil {
	//          return nil, err
	//      }
	//      user.Name = args.Name
	//      user, err = updateUser(user)
	//      if err != nil {
	//          return nil, err
	//      }
	//      return user, nil
	//  })
	Resource(path, description string, handler interface{}) Server

	// Prompt registers a prompt template with the server.
	//
	// The name parameter is the unique identifier for the prompt. The description
	// parameter provides human-readable documentation. The templates parameter
	// contains one or more prompt templates created using User() or Assistant().
	//
	// At least one template must be provided. Use server.User() and server.Assistant()
	// helper functions to create templates with the appropriate roles.
	//
	// Example:
	//  server.Prompt("greeting", "A friendly greeting",
	//      server.User("Hello, {{name}}! How are you today?"))
	//
	//  server.Prompt("conversation", "A multi-turn conversation",
	//      server.User("Please help me with {{task}}."),
	//      server.Assistant("I'll be happy to help you with that."))
	Prompt(name, description string, templates ...PromptTemplate) 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

	// IsPathInRoots checks if the given path is within any of the registered roots.
	// This security method ensures that file operations can only access paths within
	// the authorized boundaries defined by the registered root paths, preventing
	// directory traversal attacks and unauthorized file system access.
	//
	// Parameters:
	IsPathInRoots(path string) bool

	// Logger returns the server's logger.
	//
	// This method provides access to the server's configured logger for custom logging needs.
	// It can be used to log additional information or to reconfigure logging at runtime.
	//
	// Example:
	//
	//	// Log a custom message with the server's logger
	//	server.Logger().Info("custom event occurred",
	//	    "correlation_id", correlationID,
	//	    "user_id", userID,
	//	)
	Logger() *slog.Logger

	// Events returns the server's event system.
	//
	// This method provides access to the server's event system for subscribing to
	// server lifecycle events. External consumers can hook into events like server
	// initialization, client connections, tool executions, and more.
	//
	// Example:
	//
	//	// Subscribe to server initialization events
	//	events.Subscribe[MyServerEvent](server.Events(), events.TopicServerInitialized,
	//	    func(ctx context.Context, evt MyServerEvent) error {
	//	        log.Printf("Server %s initialized with %d tools", evt.Name, evt.ToolCount)
	//	        return nil
	//	    })
	//
	//	// Subscribe to client connection events
	//	events.Subscribe[MyClientEvent](server.Events(), events.TopicClientConnected,
	//	    func(ctx context.Context, evt MyClientEvent, conn net.Conn) error {
	//	        log.Printf("Client connected from %s", conn.RemoteAddr())
	//	        return nil
	//	    })
	Events() *events.Subject

	// ListTools returns a list of all registered tools.
	//
	// This method provides programmatic access to the server's tool registry,
	// returning the same information that would be provided via the tools/list
	// MCP endpoint but in a convenient Go slice format. This is useful for
	// debugging, monitoring, and multi-proxy aggregation scenarios.
	//
	// Example:
	//  tools, err := server.ListTools()
	//  if err != nil {
	//      log.Printf("Failed to list tools: %v", err)
	//      return
	//  }
	//  for _, tool := range tools {
	//      fmt.Printf("Tool: %s - %s\n", tool.Name, tool.Description)
	//  }
	ListTools() ([]mcp.Tool, error)

	// ListResources returns a list of all registered resources.
	//
	// This method provides programmatic access to the server's resource registry,
	// returning the same information that would be provided via the resources/list
	// MCP endpoint but in a convenient Go slice format. This is useful for
	// debugging, monitoring, and multi-proxy aggregation scenarios.
	//
	// Example:
	//  resources, err := server.ListResources()
	//  if err != nil {
	//      log.Printf("Failed to list resources: %v", err)
	//      return
	//  }
	//  for _, resource := range resources {
	//      fmt.Printf("Resource: %s - %s\n", resource.URI, resource.Description)
	//  }
	ListResources() ([]mcp.Resource, error)

	// ListPrompts returns a list of all registered prompts.
	//
	// This method provides programmatic access to the server's prompt registry,
	// returning the same information that would be provided via the prompts/list
	// MCP endpoint but in a convenient Go slice format. This is useful for
	// debugging, monitoring, and multi-proxy aggregation scenarios.
	//
	// Example:
	//  prompts, err := server.ListPrompts()
	//  if err != nil {
	//      log.Printf("Failed to list prompts: %v", err)
	//      return
	//  }
	//  for _, prompt := range prompts {
	//      fmt.Printf("Prompt: %s - %s\n", prompt.Name, prompt.Description)
	//  }
	ListPrompts() ([]mcp.Prompt, error)

	// AsHTTP configures the server to use HTTP for communication.
	//
	// The address parameter specifies the host and port to listen on.
	// Additional options can be provided to customize the HTTP transport behavior.
	//
	// Example:
	//  server.AsHTTP("localhost:8080")
	//  server.AsHTTP("localhost:8080", http.WithPathPrefix("/api/v1"), http.WithMCPEndpoint("/custom-mcp"))
	AsHTTP(address string, options ...http.Option) Server

	// AsGRPC configures the server to use gRPC for communication.
	//
	// gRPC provides high-performance, bidirectional streaming communication
	// with strong typing through Protocol Buffers. It supports TLS encryption,
	// configurable message sizes, and keepalive parameters for production deployments.
	//
	// The address parameter specifies the host and port to listen on.
	// Additional options can be provided to customize the gRPC transport behavior.
	//
	// Example:
	//  // Basic configuration
	//  server.AsGRPC(":50051")
	//
	//  // With TLS and custom options
	//  server.AsGRPC(":50051",
	//      grpc.WithTLS("cert.pem", "key.pem", "ca.pem"),
	//      grpc.WithMaxMessageSize(8*1024*1024),
	//      grpc.WithConnectionTimeout(20*time.Second))
	AsGRPC(address string, options ...grpc.Option) 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.
	// Optional SSE configuration options can be provided using sse.SSE.With* functions.
	//
	// Example:
	//  // Basic configuration
	//  server.AsSSE("localhost:8080")
	//
	//  // With custom paths
	//  server.AsSSE("localhost:8080", sse.SSE.WithPathPrefix("/api"), sse.SSE.WithEventsPath("/events"))
	AsSSE(address string, options ...sse.Option) Server

	// AsUnixSocket configures the server to use Unix Domain Sockets for communication.
	//
	// Unix Domain Sockets provide high-performance inter-process communication for
	// processes running on the same machine.
	//
	// Example:
	//
	//	server.AsUnixSocket("/tmp/mcp.sock")
	//	// With options:
	//	server.AsUnixSocket("/tmp/mcp.sock", unix.WithPermissions(0600))
	AsUnixSocket(socketPath string, options ...unix.UnixSocketOption) Server

	// AsUDP configures the server to use UDP for communication.
	//
	// UDP provides low-latency communication with minimal overhead,
	// suitable for high-throughput scenarios where occasional packet
	// loss is acceptable.
	//
	// Example:
	//
	//	server.AsUDP(":8080")
	//	// With options:
	//	server.AsUDP(":8080", udp.WithMaxPacketSize(2048))
	AsUDP(address string, options ...udp.UDPOption) Server

	// AsMQTT configures the server to use MQTT for communication
	// with optional configuration options.
	//
	// MQTT provides a publish/subscribe-based communication model,
	// suitable for IoT applications and distributed systems with
	// potentially intermittent connectivity.
	//
	// Example:
	//
	//	server.AsMQTT("tcp://broker.example.com:1883")
	//	// With options:
	//	server.AsMQTT("tcp://broker.example.com:1883",
	//	    mqtt.WithQoS(1),
	//	    mqtt.WithCredentials("username", "password"),
	//	    mqtt.WithTopicPrefix("custom/topic/prefix"))
	AsMQTT(brokerURL string, options ...mqtt.MQTTOption) 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

	// AsNATS configures the server to use NATS for communication
	// with optional configuration options.
	//
	// NATS provides a high-performance, cloud native communication system,
	// suitable for microservices architectures, IoT messaging, and
	// event-driven applications.
	//
	// Example:
	//
	//	server.AsNATS("nats://localhost:4222")
	//	// With options:
	//	server.AsNATS("nats://localhost:4222",
	//	    nats.WithCredentials("username", "password"),
	//	    nats.WithSubjectPrefix("custom/subject/prefix"))
	AsNATS(serverURL string, options ...nats.NATSOption) Server

	// AsEmbedded configures the server to use embedded (in-process) transport for communication.
	//
	// Embedded transport provides zero-overhead in-process communication, perfect for
	// testing, library integration, and embedded use cases where network overhead
	// should be minimized.
	//
	// The transport parameter should be the server-side transport from a transport pair
	// created using embedded.NewTransportPair().
	//
	// Example:
	//
	//	// Create transport pair
	//	serverTransport, clientTransport := embedded.NewTransportPair()
	//
	//	// Configure server with the server-side transport
	//	server.AsEmbedded(serverTransport)
	//
	//	// Use clientTransport with your MCP client
	//	client := client.NewEmbeddedTransport(clientTransport)
	AsEmbedded(transport *embedded.Transport) Server

	// GetServer returns the underlying server implementation
	// This is primarily for internal use and testing.
	GetServer() *serverImpl
}

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 ServerInfo added in v1.6.2

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ServerInfo represents server information in initialize responses

type Session added in v1.5.5

type Session = ClientSession

Session is an alias for ClientSession to provide a cleaner interface for context access

type SessionID added in v1.2.0

type SessionID string

SessionID is a unique identifier for a client session. It's used to track and manage individual client connections to the server.

type SessionManager added in v1.2.0

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

SessionManager manages client sessions. It provides methods for creating, retrieving, updating, and closing client sessions, ensuring proper lifecycle management and thread safety.

func NewSessionManager added in v1.2.0

func NewSessionManager() *SessionManager

NewSessionManager creates a new session manager. It initializes the internal data structures needed for tracking client sessions.

Returns:

  • A new SessionManager instance ready for use

func (*SessionManager) CloseSession added in v1.2.0

func (sm *SessionManager) CloseSession(id SessionID, eventSystem *events.Subject) (*ClientSession, bool)

CloseSession removes a session. This method deletes a client session from the session manager, typically called when a client disconnects or times out.

Parameters:

  • id: The unique identifier of the session to close
  • eventSystem: The event system to publish disconnection events to (can be nil)

Returns:

  • The closed session if found, nil otherwise
  • A boolean indicating whether the session was found and removed

func (*SessionManager) CreateSession added in v1.2.0

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

CreateSession creates a new client session. This method generates a unique session ID, initializes a new session with the provided client information, and adds it to the session manager.

Parameters:

  • clientInfo: Information about the client's capabilities and features
  • protocolVersion: The negotiated MCP protocol version for this client

Returns:

  • A new ClientSession instance configured for the client

func (*SessionManager) GetSession added in v1.2.0

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

GetSession retrieves a session by ID. This method looks up a client session using its unique identifier.

Parameters:

  • id: The unique identifier of the session to retrieve

Returns:

  • The ClientSession if found
  • A boolean indicating whether the session exists

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. This method modifies a session's recorded capabilities, typically called when new information about client support becomes available.

Parameters:

  • id: The unique identifier of the session to update
  • caps: The new sampling capabilities to set for the client

Returns:

  • A boolean indicating whether the session was found and updated

func (*SessionManager) UpdateSession added in v1.2.0

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

UpdateSession updates an existing session. This method applies custom updates to a session while maintaining thread safety, and automatically updates the session's last active timestamp.

Parameters:

  • id: The unique identifier of the session to update
  • update: A function that receives the session and applies updates to it

Returns:

  • A boolean indicating whether the session was found and updated

type ShutdownResponse added in v1.6.2

type ShutdownResponse struct {
	Success bool `json:"success"`
}

ShutdownResponse represents the response for shutdown requests

func NewShutdownResponse added in v1.6.2

func NewShutdownResponse(success bool) *ShutdownResponse

NewShutdownResponse creates a new shutdown response

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. This implementation of SamplingContentHandler manages plain text content for sampling conversations.

func (*TextSamplingContent) ToMessageContent added in v1.2.0

func (t *TextSamplingContent) ToMessageContent() SamplingMessageContent

ToMessageContent converts TextSamplingContent to a SamplingMessageContent. This method implements the SamplingContentHandler interface for text content, transforming the internal representation into the standardized message content format.

Returns:

  • A SamplingMessageContent object configured for text content

func (*TextSamplingContent) Validate added in v1.2.0

func (t *TextSamplingContent) Validate() error

Validate ensures the text content is valid. This method checks that the text content meets the necessary requirements, specifically that it is not empty.

Returns:

  • nil if the content is valid
  • An error explaining the validation failure otherwise

type Tool added in v1.2.0

type Tool struct {
	// Name is the unique identifier for the tool
	Name string

	// Description explains what the tool does
	Description string

	// Handler is the function that executes when the tool is called
	Handler interface{}

	// Schema defines the expected input format for the tool
	Schema interface{}

	// Annotations contains additional metadata about the tool
	Annotations map[string]interface{}
}

Tool represents a tool registered with the server. Tools are functions that clients can call to perform specific operations.

type ToolCallResponse added in v1.6.2

type ToolCallResponse struct {
	Content []ContentItem `json:"content"`
	IsError bool          `json:"isError"`
}

ToolCallResponse represents the response for tools/call requests

func NewToolCallResponse added in v1.6.2

func NewToolCallResponse(content []ContentItem, isError bool) *ToolCallResponse

NewToolCallResponse creates a new ToolCallResponse

type ToolInfo added in v1.6.2

type ToolInfo struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	InputSchema interface{}            `json:"inputSchema"`
	Annotations map[string]interface{} `json:"annotations,omitempty"`
}

ToolInfo represents information about a single tool

type ToolListResponse added in v1.6.2

type ToolListResponse struct {
	Tools      []ToolInfo `json:"tools"`
	NextCursor string     `json:"nextCursor,omitempty"`
}

ToolListResponse represents the response for tools/list requests

func NewToolListResponse added in v1.6.2

func NewToolListResponse(tools []ToolInfo, nextCursor string) *ToolListResponse

NewToolListResponse creates a new ToolListResponse

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