mcp

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2024 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package mcp implements the Model Context Protocol (MCP), providing a framework for integrating Large Language Models (LLMs) with external data sources and tools. This implementation follows the official specification from https://spec.modelcontextprotocol.io/specification/.

The package enables seamless integration between LLM applications and external data sources through a standardized protocol, making it suitable for building AI-powered IDEs, enhancing chat interfaces, or creating custom AI workflows.

Core Architecture

The package is built on a JSON-RPC 2.0 message passing protocol with support for bidirectional communication between clients and servers. It provides comprehensive session management, including automatic connection lifecycle, health monitoring through ping/pong mechanisms, and graceful shutdown procedures.

Transport Layer

The package supports multiple transport mechanisms:

StdIO Transport uses standard input/output for command-line focused communication. It provides:

  • Single session support per server-client lifetime
  • Synchronous operations with JSON-RPC line processing
  • Context-aware cancellation
  • Non-blocking message handling

SSE Transport implements Server-Sent Events over HTTP, offering:

  • Real-time updates with automatic reconnection
  • Multi-client capabilities
  • Thread-safe operations using sync.Map
  • CORS and custom HTTP client support
  • Channel-based message routing

Server Components

Servers implement a modular architecture through interfaces:

Base Server interface (required) provides:

  • Information provision
  • Capability management

Optional specialized servers:

PromptServer handles template management and prompt operations:

  • Template-based prompt management
  • Version control
  • Argument completion handling

ResourceServer manages content access and subscription systems:

  • Hierarchical resource organization
  • Content type handling
  • Subscription-based change notifications

ToolServer provides tool integration:

  • Dynamic tool discovery
  • Synchronous/asynchronous execution
  • Result streaming
  • Error handling and recovery

Additional server interfaces support:

  • Progress reporting for long-running operations
  • Multi-level logging system
  • Real-time updates through various updater interfaces

Client Components

Clients are built around a required base Client struct with optional extensions:

Core Client capabilities:

  • Connection management
  • Request/response cycle handling
  • Protocol feature APIs
  • Event processing
  • Automatic request ID generation

Optional interfaces:

RootsListHandler manages filesystem roots:

  • Root resource management
  • Path resolution
  • Change notification handling

SamplingHandler processes LLM requests:

  • Model response handling
  • Sampling parameter management
  • Result processing

Various watchers handle real-time updates:

  • PromptListWatcher for template changes
  • ResourceListWatcher for content updates
  • ToolListWatcher for tool availability
  • Progress and log monitoring

Interface Requirements

The package enforces strict capability matching between servers and clients:

Server requirements:

  • Must implement all capabilities required by connected clients
  • Base Server interface is mandatory
  • Optional interfaces based on client needs

Client requirements:

  • Must implement all capabilities required by their servers
  • Optional interfaces determined by server capabilities

Required interface pairs:

  • RootsListWatcher (server) with RootsListUpdater (client)
  • PromptListUpdater (server) with PromptListWatcher (client)
  • ResourceListUpdater (server) with ResourceListWatcher (client)
  • ResourceSubscribedUpdater (server) with ResourceSubscribedWatcher (client)
  • ToolListUpdater (server) with ToolListWatcher (client)
  • ProgressReporter (server) with ProgressListener (client)
  • LogHandler (server) with LogReceiver (client)

Concurrency Support

Thread-safety is ensured through:

  • Goroutine-based processing
  • Synchronized state management
  • Channel communication
  • Context-aware operations

Extension Points

The package supports extensibility through:

  • Custom transport layer implementations
  • Pluggable tool architecture
  • Flexible resource handling
  • Configurable logging system

Index

Constants

View Source
const (
	// JSONRPCVersion specifies the JSON-RPC protocol version used for communication.
	JSONRPCVersion = "2.0"

	// MethodPromptsList is the method name for retrieving a list of available prompts.
	MethodPromptsList = "prompts/list"
	// MethodPromptsGet is the method name for retrieving a specific prompt by identifier.
	MethodPromptsGet = "prompts/get"

	// MethodResourcesList is the method name for listing available resources.
	MethodResourcesList = "resources/list"
	// MethodResourcesRead is the method name for reading the content of a specific resource.
	MethodResourcesRead = "resources/read"
	// MethodResourcesTemplatesList is the method name for listing available resource templates.
	MethodResourcesTemplatesList = "resources/templates/list"
	// MethodResourcesSubscribe is the method name for subscribing to resource updates.
	MethodResourcesSubscribe = "resources/subscribe"
	// MethodResourcesUnsubscribe is the method name for unsubscribing from resource updates.
	MethodResourcesUnsubscribe = "resources/unsubscribe"

	// MethodToolsList is the method name for retrieving a list of available tools.
	MethodToolsList = "tools/list"
	// MethodToolsCall is the method name for invoking a specific tool.
	MethodToolsCall = "tools/call"

	// MethodRootsList is the method name for retrieving a list of root resources.
	MethodRootsList = "roots/list"
	// MethodSamplingCreateMessage is the method name for creating a new sampling message.
	MethodSamplingCreateMessage = "sampling/createMessage"

	// MethodCompletionComplete is the method name for requesting completion suggestions.
	MethodCompletionComplete = "completion/complete"

	// MethodLoggingSetLevel is the method name for setting the minimum severity level for emitted log messages.
	MethodLoggingSetLevel = "logging/setLevel"

	// CompletionRefPrompt is used in CompletionCompleteRef.Type for prompt argument completion.
	CompletionRefPrompt = "ref/prompt"
	// CompletionRefResource is used in CompletionCompleteRef.Type for resource template argument completion.
	CompletionRefResource = "ref/resource"
)

Variables

This section is empty.

Functions

func Serve added in v0.2.0

func Serve(
	ctx context.Context,
	server Server,
	transport ServerTransport,
	errsChan chan error,
	options ...ServerOption,
)

Serve starts a Model Context Protocol (MCP) server and manages its lifecycle. It handles client connections, protocol messages, and server capabilities according to the MCP specification.

The server parameter must implement the Server interface to define core MCP capabilities like prompts, resources, and tools. The transport parameter specifies how the server communicates with clients (e.g., HTTP, WebSocket, stdio). Errors encountered during server operation are sent to errsChan.

Serve blocks until the provided context is cancelled, at which point it performs a graceful shutdown by closing all active sessions and cleaning up resources.

Example usage:

srv := &MyMCPServer{} // implements Server interface
transport := mcp.NewHTTPTransport(":8080")
errChan := make(chan error, 10)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// Start server with custom options
mcp.Serve(ctx, srv, transport, errChan,
    mcp.WithServerWriteTimeout(30*time.Second),
    mcp.WithProgressReporter(myReporter),
)

Types

type Client

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

Client implements a Model Context Protocol (MCP) client that enables communication between LLM applications and external data sources and tools. It manages the connection lifecycle, handles protocol messages, and provides access to MCP server capabilities.

The client supports various server interactions including prompt management, resource handling, tool execution, and logging. It maintains session state and provides automatic connection health monitoring through periodic pings.

A Client must be created using NewClient() and requires Connect() to be called before any operations can be performed. The client should be properly closed using Close() when it's no longer needed.

Example usage:

client := NewClient(info, transport, requirement)
if err := client.Connect(); err != nil {
    log.Fatal(err)
}
defer client.Close()

// Use client methods...
prompts, err := client.ListPrompts(ctx, "", "")

func NewClient added in v0.2.0

func NewClient(
	info Info,
	transport ClientTransport,
	serverRequirement ServerRequirement,
	options ...ClientOption,
) *Client

NewClient creates a new Model Context Protocol (MCP) client with the specified configuration. It establishes a client that can communicate with MCP servers according to the protocol specification at https://spec.modelcontextprotocol.io/specification/.

The info parameter provides client identification and version information. The transport parameter defines how the client communicates with the server. ServerRequirement specifies which server capabilities are required for this client instance.

Optional client behaviors can be configured through ClientOption functions. These include handlers for roots management, sampling, resource management, tool operations, progress tracking, and logging. Timeouts and intervals can also be configured through options.

The client will not be connected until Connect() is called. After creation, use Connect() to establish the session with the server and initialize the protocol.

func (*Client) CallTool added in v0.2.0

func (c *Client) CallTool(
	ctx context.Context,
	name string,
	arguments map[string]any,
	progressToken MustString,
) (ToolResult, error)

CallTool executes a specific tool with the given arguments and returns its result. It provides a way to invoke server-side tools that can perform specialized operations.

The name parameter identifies which tool to execute. The arguments parameter provides tool-specific configuration as key-value pairs that will be passed to the tool during execution.

The progressToken allows tracking the operation's progress through progress notifications. Pass an empty string if progress tracking is not needed.

If the provided context is cancelled, a cancellation request will be sent to the server to stop processing the tool execution. This is particularly useful for long-running tool operations that need to be interrupted.

func (*Client) Close added in v0.2.0

func (c *Client) Close()

Close terminates the client's connection to the server and releases all associated resources. It closes the error channel, stops all background routines, and terminates the transport connection.

After Close is called, the client cannot be reused. A new client must be created to establish another connection.

func (*Client) CompletesPrompt added in v0.2.0

func (c *Client) CompletesPrompt(ctx context.Context, name string, arg CompletionArgument) (CompletionResult, error)

CompletesPrompt requests completion suggestions for a prompt-based completion. It returns a CompletionResult containing the completion suggestions.

The name parameter specifies which prompt to use as the completion source. The arg parameter provides the completion context and configuration through the CompletionArgument structure.

This method is particularly useful for implementing intelligent code completion or text suggestions based on prompt templates.

If the provided context is cancelled, a cancellation request will be sent to the server to stop processing the completion request. This allows graceful interruption of long-running completion operations.

func (*Client) CompletesResourceTemplate added in v0.2.0

func (c *Client) CompletesResourceTemplate(
	ctx context.Context,
	uri string,
	arg CompletionArgument,
) (CompletionResult, error)

CompletesResourceTemplate requests completion suggestions for a resource template. It returns a CompletionResult containing the completion suggestions based on the template's content and structure.

The uri parameter identifies the resource template to use for completion. The arg parameter provides completion context and configuration through the CompletionArgument structure.

This method is particularly useful for implementing intelligent code completion or content suggestions based on resource templates.

If the provided context is cancelled, a cancellation request will be sent to the server to stop processing the completion request.

func (*Client) Connect added in v0.2.0

func (c *Client) Connect() error

Connect establishes a session with the MCP server and initializes the protocol handshake. It starts background routines for message handling and server health checks through periodic pings.

The initialization process verifies protocol version compatibility and required server capabilities. If the server's capabilities don't match the client's requirements, Connect returns an error.

Connect must be called after creating a new client and before making any other client method calls. It returns an error if the session cannot be established or if the initialization fails.

func (*Client) Errors added in v0.2.0

func (c *Client) Errors() <-chan error

Errors returns a channel that provides access to errors encountered during client operations. This includes transport errors, protocol violations, and other operational issues that don't directly relate to specific method calls.

The returned channel is receive-only and will be closed when the client is closed. Clients should monitor this channel to detect and handle operational issues.

Note that method-specific errors are returned directly by the respective methods and won't appear on this channel.

func (*Client) GetPrompt added in v0.2.0

func (c *Client) GetPrompt(
	ctx context.Context,
	name string,
	arguments map[string]string,
	progressToken MustString,
) (PromptResult, error)

GetPrompt retrieves a specific prompt by name with the given arguments. It returns a PromptResult containing the prompt's content and metadata.

The name parameter specifies which prompt to retrieve. The arguments parameter allows passing key-value pairs that will be used to customize the prompt content.

The progressToken allows tracking the operation's progress through progress notifications. Pass an empty string if progress tracking is not needed.

If the provided context is cancelled, a cancellation request will be sent to the server to stop processing the request. This is particularly useful for long-running prompt generations that need to be interrupted.

func (*Client) ListPrompts added in v0.2.0

func (c *Client) ListPrompts(ctx context.Context, cursor string, progressToken MustString) (PromptList, error)

ListPrompts retrieves a paginated list of available prompts from the server. It returns a PromptList containing prompt metadata and pagination information.

The cursor parameter enables pagination through the prompt list. An empty cursor starts from the beginning. Use the NextCursor from the returned PromptList for subsequent pages.

The progressToken allows tracking the operation's progress through progress notifications. Pass an empty string if progress tracking is not needed.

If the provided context is cancelled, a cancellation request will be sent to the server to stop processing the request.

func (*Client) ListResourceTemplates added in v0.2.0

func (c *Client) ListResourceTemplates(ctx context.Context, progressToken MustString) ([]ResourceTemplate, error)

ListResourceTemplates retrieves a list of available resource templates from the server. Resource templates allow servers to expose parameterized resources using URI templates. These templates can be used to generate resource URIs by providing arguments, which may be auto-completed through the CompletesResourceTemplate.

The progressToken allows tracking the operation's progress through progress notifications. Pass an empty string if progress tracking is not needed.

If the provided context is cancelled, a cancellation request will be sent to the server to stop processing the request.

func (*Client) ListResources added in v0.2.0

func (c *Client) ListResources(ctx context.Context, cursor string, progressToken MustString) (ResourceList, error)

ListResources retrieves a paginated list of available resources from the server. It returns a ResourceList containing resource metadata and pagination information.

The cursor parameter enables pagination through the resource list. An empty cursor starts from the beginning. Use the NextCursor from the returned ResourceList for subsequent pages.

The progressToken allows tracking the operation's progress through progress notifications. Pass an empty string if progress tracking is not needed.

If the provided context is cancelled, a cancellation request will be sent to the server to stop processing the request.

func (*Client) ListTools added in v0.2.0

func (c *Client) ListTools(ctx context.Context, cursor string, progressToken MustString) (ToolList, error)

ListTools retrieves a paginated list of available tools from the server. It returns a ToolList containing tool metadata and pagination information.

The cursor parameter enables pagination through the tool list. An empty cursor starts from the beginning. Use the NextCursor from the returned ToolList for subsequent pages.

The progressToken allows tracking the operation's progress through progress notifications. Pass an empty string if progress tracking is not needed.

If the provided context is cancelled, a cancellation request will be sent to the server to stop processing the request.

func (*Client) ReadResource added in v0.2.0

func (c *Client) ReadResource(ctx context.Context, uri string, progressToken MustString) (Resource, error)

ReadResource retrieves the content and metadata of a specific resource identified by its URI. It returns a Resource containing the resource's content, type, and associated metadata.

The uri parameter specifies which resource to retrieve. The URI format should follow the server's resource addressing scheme.

The progressToken allows tracking the operation's progress through progress notifications. Pass an empty string if progress tracking is not needed.

If the provided context is cancelled, a cancellation request will be sent to the server to stop processing the request.

func (*Client) SetLogLevel added in v0.2.0

func (c *Client) SetLogLevel(level LogLevel) error

SetLogLevel configures the logging level for the MCP server. It allows dynamic adjustment of the server's logging verbosity during runtime.

The level parameter specifies the desired logging level. Valid levels are defined by the LogLevel type. The server will adjust its logging output to match the requested level.

func (*Client) SubscribeResource added in v0.2.0

func (c *Client) SubscribeResource(ctx context.Context, uri string) error

SubscribeResource registers the client for notifications about changes to a specific resource. When the resource is modified, the client will receive notifications through the ResourceSubscribedWatcher interface if one was set using WithResourceSubscribedWatcher.

The uri parameter identifies the resource to monitor for changes.

func (*Client) UnsubscribeResource added in v0.2.0

func (c *Client) UnsubscribeResource(ctx context.Context, uri string) error

UnsubscribeResource cancels an existing subscription for notifications about changes to a specific resource. After unsubscribing, the client will no longer receive notifications through the ResourceSubscribedWatcher interface for this resource.

The uri parameter identifies the resource to stop monitoring for changes.

type ClientCapabilities

type ClientCapabilities struct {
	Roots    *RootsCapability    `json:"roots,omitempty"`
	Sampling *SamplingCapability `json:"sampling,omitempty"`
}

ClientCapabilities represents client capabilities.

type ClientOption

type ClientOption func(*Client)

ClientOption is a function that configures a client.

func WithClientPingInterval

func WithClientPingInterval(interval time.Duration) ClientOption

WithClientPingInterval sets the ping interval for the client.

func WithClientReadTimeout

func WithClientReadTimeout(timeout time.Duration) ClientOption

WithClientReadTimeout sets the read timeout for the client.

func WithClientWriteTimeout

func WithClientWriteTimeout(timeout time.Duration) ClientOption

WithClientWriteTimeout sets the write timeout for the client.

func WithLogReceiver

func WithLogReceiver(receiver LogReceiver) ClientOption

WithLogReceiver sets the log receiver for the client.

func WithProgressListener

func WithProgressListener(listener ProgressListener) ClientOption

WithProgressListener sets the progress listener for the client.

func WithPromptListWatcher

func WithPromptListWatcher(watcher PromptListWatcher) ClientOption

WithPromptListWatcher sets the prompt list watcher for the client.

func WithResourceListWatcher

func WithResourceListWatcher(watcher ResourceListWatcher) ClientOption

WithResourceListWatcher sets the resource list watcher for the client.

func WithResourceSubscribedWatcher

func WithResourceSubscribedWatcher(watcher ResourceSubscribedWatcher) ClientOption

WithResourceSubscribedWatcher sets the resource subscribe watcher for the client.

func WithRootsListHandler

func WithRootsListHandler(handler RootsListHandler) ClientOption

WithRootsListHandler sets the roots list handler for the client.

func WithRootsListUpdater

func WithRootsListUpdater(updater RootsListUpdater) ClientOption

WithRootsListUpdater sets the roots list updater for the client.

func WithSamplingHandler

func WithSamplingHandler(handler SamplingHandler) ClientOption

WithSamplingHandler sets the sampling handler for the client.

func WithToolListWatcher

func WithToolListWatcher(watcher ToolListWatcher) ClientOption

WithToolListWatcher sets the tool list watcher for the client.

type ClientTransport added in v0.2.0

type ClientTransport interface {
	Transport

	// StartSession initiates a new session with the server and returns the
	// assigned session identifier. The implementation may cache the session ID
	// internally to route subsequent messages.
	//
	// Returns an error if the session cannot be established. Implementations
	// should provide meaningful error information to help diagnose connection
	// issues.
	StartSession() (string, error)
}

ClientTransport extends the base Transport interface with client-specific functionality for initiating sessions with servers. It provides the client-side communication layer in the MCP protocol.

type CompletionArgument

type CompletionArgument struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

CompletionArgument defines the structure for arguments passed in completion requests, containing the argument name and its corresponding value.

type CompletionCompleteParams

type CompletionCompleteParams struct {
	// Ref identifies what is being completed (e.g. prompt, resource template)
	Ref CompletionCompleteRef `json:"ref"`
	// Argument specifies which argument needs completion suggestions
	Argument CompletionArgument `json:"argument"`
}

CompletionCompleteParams contains parameters for requesting completion suggestions. It includes a reference to what is being completed (e.g. a prompt or resource template) and the specific argument that needs completion suggestions.

type CompletionCompleteRef

type CompletionCompleteRef struct {
	// Type specifies what kind of completion is being requested.
	// Must be either "ref/prompt" or "ref/resource".
	Type string `json:"type"`
	// Name contains the prompt name when Type is "ref/prompt".
	Name string `json:"name,omitempty"`
	// URI contains the resource template URI when Type is "ref/resource".
	URI string `json:"uri,omitempty"`
}

CompletionCompleteRef identifies what is being completed in a completion request. Type must be one of:

  • "ref/prompt": Completing a prompt argument, Name field must be set to prompt name
  • "ref/resource": Completing a resource template argument, URI field must be set to template URI

type CompletionResult

type CompletionResult struct {
	Completion struct {
		Values  []string `json:"values"`
		HasMore bool     `json:"hasMore"`
	} `json:"completion"`
}

CompletionResult contains the response data for a completion request, including possible completion values and whether more completions are available.

type Content

type Content struct {
	Type ContentType `json:"type"`

	Text string `json:"text,omitempty"`

	Data     string `json:"data,omitempty"`
	MimeType string `json:"mimeType,omitempty"`

	Resource *Resource `json:"resource,omitempty"`
}

Content represents a message content with its type.

type ContentType

type ContentType string

ContentType represents the type of content in messages.

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

ContentType represents the type of content in messages.

type Info

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

Info contains metadata about a server or client instance including its name and version.

type JSONRPCError added in v0.2.0

type JSONRPCError struct {
	// Code indicates the error type that occurred.
	// Must use standard JSON-RPC error codes or custom codes outside the reserved range.
	Code int `json:"code"`

	// Message provides a short description of the error.
	// Should be limited to a concise single sentence.
	Message string `json:"message"`

	// Data contains additional information about the error.
	// The value is unstructured and may be omitted.
	Data map[string]any `json:"data,omitempty"`
}

JSONRPCError represents an error response in the JSON-RPC 2.0 protocol. It follows the standard error object format defined in the JSON-RPC 2.0 specification.

func (JSONRPCError) Error added in v0.2.0

func (j JSONRPCError) Error() string

type JSONRPCMessage

type JSONRPCMessage struct {
	// JSONRPC must always be "2.0" per the JSON-RPC specification
	JSONRPC string `json:"jsonrpc"`
	// ID uniquely identifies request-response pairs and must be a string or number
	ID MustString `json:"id,omitempty"`
	// Method contains the RPC method name for requests and notifications
	Method string `json:"method,omitempty"`
	// Params contains the parameters for the method call as a raw JSON message
	Params json.RawMessage `json:"params,omitempty"`
	// Result contains the successful response data as a raw JSON message
	Result json.RawMessage `json:"result,omitempty"`
	// Error contains error details if the request failed
	Error *JSONRPCError `json:"error,omitempty"`
}

JSONRPCMessage represents a JSON-RPC 2.0 message used for communication in the MCP protocol. It can represent either a request, response, or notification depending on which fields are populated:

  • Request: JSONRPC, ID, Method, and Params are set
  • Response: JSONRPC, ID, and either Result or Error are set
  • Notification: JSONRPC and Method are set (no ID)

type LogData

type LogData struct {
	Message string         `json:"message"`
	Details map[string]any `json:"details,omitempty"`
}

LogData represents the data of a log message.

type LogHandler

type LogHandler interface {
	// LogStreams returns a channel that emits log messages with metadata.
	// The channel remains open for the lifetime of the handler and is safe for concurrent receives.
	LogStreams() <-chan LogParams

	// SetLogLevel configures the minimum severity level for emitted log messages.
	// Messages below this level are filtered out.
	SetLogLevel(level LogLevel)
}

LogHandler provides an interface for streaming log messages from the MCP server to connected clients. It maintains a channel for emitting log messages and allows configuration of minimum severity level.

type LogLevel

type LogLevel int

LogLevel represents the severity level of log messages.

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelNotice
	LogLevelWarning
	LogLevelError
	LogLevelCritical
	LogLevelAlert
	LogLevelEmergency
)

LogLevel represents the severity level of log messages.

type LogParams

type LogParams struct {
	// Level indicates the severity level of the message.
	// Must be one of the defined LogLevel constants.
	Level LogLevel `json:"level"`
	// Logger identifies the source/component that generated the message.
	Logger string `json:"logger"`
	// Data contains the message content and any structured metadata.
	Data LogData `json:"data"`
}

LogParams represents the parameters for a log message.

type LogReceiver

type LogReceiver interface {
	// OnLog is called when a log message is received from the server.
	OnLog(params LogParams)
}

LogReceiver provides an interface for receiving log messages from the server. Implementations can use these notifications to display logs in a UI, write them to a file, or forward them to a logging service.

type LoggingCapability

type LoggingCapability struct{}

LoggingCapability represents logging-specific capabilities.

type MustString

type MustString string

MustString is a type that enforces string representation for fields that can be either string or integer in the protocol specification, such as request IDs and progress tokens. It handles automatic conversion during JSON marshaling/unmarshaling.

func (MustString) MarshalJSON

func (m MustString) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler to convert MustString into its JSON representation, always encoding as a string value.

func (*MustString) UnmarshalJSON

func (m *MustString) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler to convert JSON data into MustString, handling both string and numeric input formats.

type ParamsMeta

type ParamsMeta struct {
	// ProgressToken uniquely identifies an operation for progress tracking.
	// When provided, the server can emit progress updates via ProgressReporter.
	ProgressToken MustString `json:"progressToken"`
}

ParamsMeta contains optional metadata that can be included with request parameters. It is used to enable features like progress tracking for long-running operations.

type ProgressListener

type ProgressListener interface {
	// OnProgress is called when a progress update is received for an operation.
	OnProgress(params ProgressParams)
}

ProgressListener provides an interface for receiving progress updates on long-running operations. Implementations can use these notifications to update progress bars, status indicators, or other UI elements that show operation progress to users.

type ProgressParams

type ProgressParams struct {
	// ProgressToken uniquely identifies the operation this progress update relates to
	ProgressToken MustString `json:"progressToken"`
	// Progress represents the current progress value
	Progress float64 `json:"value"`
	// Total represents the expected final value when known.
	// When non-zero, completion percentage can be calculated as (Progress/Total)*100
	Total float64 `json:"total"`
}

ProgressParams represents the progress status of a long-running operation.

type ProgressReporter

type ProgressReporter interface {
	// ProgressReports returns a channel that emits progress updates for operations.
	// The channel remains open for the lifetime of the reporter and is safe for concurrent receives.
	ProgressReports() <-chan ProgressParams
}

ProgressReporter provides an interface for reporting progress updates on long-running operations. It maintains a channel that emits progress updates for operations identified by progress tokens.

type Prompt

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

Prompt defines a template for generating prompts with optional arguments. It's returned by GetPrompt and contains metadata about the prompt.

type PromptArgument

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

PromptArgument defines a single argument that can be passed to a prompt. Required indicates whether the argument must be provided when using the prompt.

type PromptList

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

PromptList represents a paginated list of prompts returned by ListPrompts. NextCursor can be used to retrieve the next page of results.

type PromptListUpdater

type PromptListUpdater interface {
	PromptListUpdates() <-chan struct{}
}

PromptListUpdater provides an interface for monitoring changes to the available prompts list. It maintains a channel that emits notifications whenever prompts are added, removed, or modified.

The notifications are used by the MCP server to inform connected clients about prompt list changes via the "notifications/prompts/list_changed" method. Clients can then refresh their cached prompt lists by calling ListPrompts again.

The channel returned by PromptListUpdates must: - Remain open for the lifetime of the updater - Be safe for concurrent receives from multiple goroutines - Never block on sends using buffered channels or dropped notifications

A struct{} is sent through the channel as only the notification matters, not the value.

type PromptListWatcher

type PromptListWatcher interface {
	// OnPromptListChanged is called when the server notifies that its prompt list has changed.
	// This can happen when prompts are added, removed, or modified on the server side.
	OnPromptListChanged()
}

PromptListWatcher provides an interface for receiving notifications when the server's prompt list changes. Implementations can use these notifications to update their internal state or trigger UI updates when available prompts are added, removed, or modified.

type PromptMessage

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

PromptMessage represents a message in a prompt.

type PromptResult

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

PromptResult represents the result of a prompt request.

type PromptRole

type PromptRole string

PromptRole represents the role in a conversation (user or assistant).

const (
	PromptRoleUser      PromptRole = "user"
	PromptRoleAssistant PromptRole = "assistant"
)

PromptRole represents the role in a conversation (user or assistant).

type PromptServer

type PromptServer interface {
	// ListPrompts returns a paginated list of available prompts.
	// Returns error if operation fails or context is cancelled.
	ListPrompts(ctx context.Context, params PromptsListParams, requestClient RequestClientFunc) (PromptList, error)

	// GetPrompt retrieves a specific prompt template by name with the given arguments.
	// Returns error if prompt not found, arguments are invalid, or context is cancelled.
	GetPrompt(ctx context.Context, params PromptsGetParams, requestClient RequestClientFunc) (PromptResult, error)

	// CompletesPrompt provides completion suggestions for a prompt argument.
	// Used to implement interactive argument completion in clients.
	// Returns error if prompt doesn't exist, completions cannot be generated, or context is cancelled.
	CompletesPrompt(ctx context.Context, params CompletionCompleteParams,
		requestClient RequestClientFunc) (CompletionResult, error)
}

PromptServer defines the interface for managing prompts in the MCP protocol. It provides functionality for listing available prompts, retrieving specific prompts with arguments, and providing prompt argument completions.

type PromptsCapability

type PromptsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

PromptsCapability represents prompts-specific capabilities.

type PromptsGetParams

type PromptsGetParams struct {
	// Name is the unique identifier of the prompt to retrieve
	Name string `json:"name"`

	// Arguments is a map of argument name-value pairs
	// Must satisfy required arguments defined in prompt's Arguments field
	Arguments map[string]string `json:"arguments"`

	// Meta contains optional metadata including:
	// - progressToken: Unique token for tracking operation progress
	//   * Used by ProgressReporter to emit progress updates if supported
	//   * Optional - may be ignored if progress tracking not supported
	Meta ParamsMeta `json:"_meta,omitempty"`
}

PromptsGetParams contains parameters for retrieving a specific prompt.

type PromptsListParams

type PromptsListParams struct {
	// Cursor is an optional pagination cursor from previous ListPrompts call.
	// Empty string requests the first page.
	Cursor string `json:"cursor"`

	// Meta contains optional metadata including:
	// - progressToken: Unique token for tracking operation progress
	//   * Used by ProgressReporter to emit progress updates if supported
	//   * Optional - may be ignored if progress tracking not supported
	Meta ParamsMeta `json:"_meta,omitempty"`
}

PromptsListParams contains parameters for listing available prompts.

type RequestClientFunc added in v0.2.0

type RequestClientFunc func(msg JSONRPCMessage) (JSONRPCMessage, error)

RequestClientFunc is a function type that handles JSON-RPC message communication between client and server. It takes a JSON-RPC request message as input and returns the corresponding response message.

The function is used by server implementations to send requests to clients and receive responses during method handling. For example, when a server needs to request additional information from a client while processing a method call.

Parameters:

  • msg: The JSON-RPC request message to send to the client

Returns:

  • JSONRPCMessage: The response message from the client
  • error: Any error that occurred during the request-response cycle

The implementation must handle timeouts, connection errors, and invalid responses appropriately. It should respect the JSON-RPC 2.0 specification for error handling and message formatting.

type Resource

type Resource struct {
	URI         string `json:"uri"`
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
	MimeType    string `json:"mimeType,omitempty"`
	Text        string `json:"text,omitempty"`
	Blob        string `json:"blob,omitempty"`
}

Resource represents a content resource in the system with associated metadata. The content can be provided either as Text or Blob, with MimeType indicating the format.

type ResourceList

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

ResourceList represents a paginated list of resources returned by ListResources. NextCursor can be used to retrieve the next page of results.

type ResourceListUpdater

type ResourceListUpdater interface {
	ResourceListUpdates() <-chan struct{}
}

ResourceListUpdater provides an interface for monitoring changes to the available resources list. It maintains a channel that emits notifications whenever resources are added, removed, or modified.

The notifications are used by the MCP server to inform connected clients about resource list changes. Clients can then refresh their cached resource lists by calling ListResources again.

The channel returned by ResourceListUpdates must: - Remain open for the lifetime of the updater - Be safe for concurrent receives from multiple goroutines - Never block on sends using buffered channels or dropped notifications

A struct{} is sent through the channel as only the notification matters, not the value.

type ResourceListWatcher

type ResourceListWatcher interface {
	// OnResourceListChanged is called when the server notifies that its resource list has changed.
	// This can happen when resources are added, removed, or modified on the server side.
	OnResourceListChanged()
}

ResourceListWatcher provides an interface for receiving notifications when the server's resource list changes. Implementations can use these notifications to update their internal state or trigger UI updates when available resources are added, removed, or modified.

type ResourceServer

type ResourceServer interface {
	// ListResources returns a paginated list of available resources.
	// Returns error if operation fails or context is cancelled.
	ListResources(ctx context.Context, params ResourcesListParams, requestClient RequestClientFunc) (ResourceList, error)

	// ReadResource retrieves a specific resource by its URI.
	// Returns error if resource not found, cannot be read, or context is cancelled.
	ReadResource(ctx context.Context, params ResourcesReadParams, requestClient RequestClientFunc) (Resource, error)

	// ListResourceTemplates returns all available resource templates.
	// Returns error if templates cannot be retrieved or context is cancelled.
	ListResourceTemplates(ctx context.Context, params ResourcesTemplatesListParams,
		requestClient RequestClientFunc) ([]ResourceTemplate, error)

	// CompletesResourceTemplate provides completion suggestions for a resource template argument.
	// Returns error if template doesn't exist, completions cannot be generated, or context is cancelled.
	CompletesResourceTemplate(ctx context.Context, params CompletionCompleteParams,
		requestClient RequestClientFunc) (CompletionResult, error)

	// SubscribeResource registers interest in a specific resource URI.
	SubscribeResource(params ResourcesSubscribeParams)

	// UnsubscribeResource unregisters interest in a specific resource URI.
	UnsubscribeResource(params ResourcesSubscribeParams)
}

ResourceServer defines the interface for managing resources in the MCP protocol. It provides functionality for listing, reading, and subscribing to resources, as well as managing resource templates.

type ResourceSubscribedUpdater

type ResourceSubscribedUpdater interface {
	ResourceSubscribedUpdates() <-chan string
}

ResourceSubscribedUpdater provides an interface for monitoring changes to subscribed resources. It maintains a channel that emits notifications whenever a subscribed resource changes.

The notifications are used by the MCP server to inform connected clients about changes to resources they have subscribed to. The channel emits the URI of the changed resource.

The channel returned by ResourceSubscribedUpdates must: - Remain open for the lifetime of the updater - Be safe for concurrent receives from multiple goroutines - Never block on sends using buffered channels or dropped notifications

A string (resource URI) is sent through the channel to identify which resource changed.

type ResourceSubscribedWatcher

type ResourceSubscribedWatcher interface {
	// OnResourceSubscribedChanged is called when the server notifies that a subscribed resource has changed.
	//
	// Parameters:
	// - uri: The unique identifier of the resource that changed
	OnResourceSubscribedChanged(uri string)
}

ResourceSubscribedWatcher provides an interface for receiving notifications when a subscribed resource changes. Implementations can use these notifications to update their internal state or trigger UI updates when specific resources they are interested in are modified.

type ResourceTemplate

type ResourceTemplate struct {
	URITemplate string `json:"uriTemplate"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	MimeType    string `json:"mimeType,omitempty"`
}

ResourceTemplate defines a template for generating resource URIs. It's returned by ListResourceTemplates and used with CompletesResourceTemplate.

type ResourcesCapability

type ResourcesCapability struct {
	Subscribe   bool `json:"subscribe,omitempty"`
	ListChanged bool `json:"listChanged,omitempty"`
}

ResourcesCapability represents resources-specific capabilities.

type ResourcesListParams

type ResourcesListParams struct {
	// Cursor is a pagination cursor from previous ListResources call.
	// Empty string requests the first page.
	Cursor string `json:"cursor"`

	// Meta contains optional metadata including progressToken for tracking operation progress.
	// The progressToken is used by ProgressReporter to emit progress updates if supported.
	Meta ParamsMeta `json:"_meta,omitempty"`
}

ResourcesListParams contains parameters for listing available resources.

type ResourcesReadParams

type ResourcesReadParams struct {
	// URI is the unique identifier of the resource to retrieve.
	URI string `json:"uri"`

	// Meta contains optional metadata including progressToken for tracking operation progress.
	// The progressToken is used by ProgressReporter to emit progress updates if supported.
	Meta ParamsMeta `json:"_meta,omitempty"`
}

ResourcesReadParams contains parameters for retrieving a specific resource.

type ResourcesSubscribeParams

type ResourcesSubscribeParams struct {
	// URI is the unique identifier of the resource to subscribe to.
	// Must match URI used in ReadResource calls.
	URI string `json:"uri"`
}

ResourcesSubscribeParams contains parameters for subscribing to a resource.

type ResourcesTemplatesListParams

type ResourcesTemplatesListParams struct {
	// Meta contains optional metadata including progressToken for tracking operation progress.
	// The progressToken is used by ProgressReporter to emit progress updates if supported.
	Meta ParamsMeta `json:"_meta,omitempty"`
}

ResourcesTemplatesListParams contains parameters for listing available resource templates.

type Root

type Root struct {
	URI  string `json:"uri"`
	Name string `json:"name"`
}

Root represents a top-level resource entry point in the system.

type RootList

type RootList struct {
	Roots []Root `json:"roots"`
}

RootList represents a collection of root resources in the system. Contains: - Roots: Array of Root objects, each containing:

  • URI: A unique identifier for accessing the root resource
  • Name: A human-readable name for the root

type RootsCapability

type RootsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

RootsCapability represents roots-specific capabilities.

type RootsListHandler

type RootsListHandler interface {
	// RootsList returns the list of available root resources.
	// Returns error if operation fails or context is cancelled.
	RootsList(ctx context.Context) (RootList, error)
}

RootsListHandler defines the interface for retrieving the list of root resources in the MCP protocol. Root resources represent top-level entry points in the resource hierarchy that clients can access.

type RootsListUpdater

type RootsListUpdater interface {
	// RootsListUpdates returns a channel that emits notifications when the root list changes.
	// The returned channel remains open for the lifetime of the updater and is safe for concurrent use.
	RootsListUpdates() <-chan struct{}
}

RootsListUpdater provides an interface for monitoring changes to the available roots list. Implementations should maintain a channel that emits notifications whenever the list of available roots changes, such as when roots are added, removed, or modified.

type RootsListWatcher

type RootsListWatcher interface {
	// OnRootsListChanged is called when the client notifies that its root list has changed
	OnRootsListChanged()
}

RootsListWatcher provides an interface for receiving notifications when the client's root list changes. The implementation can use these notifications to update its internal state or perform necessary actions when the client's available roots change.

type SSEClient

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

SSEClient implements a Server-Sent Events (SSE) client that manages server connections and bidirectional message handling. It provides real-time communication through SSE for server-to-client streaming and HTTP POST for client-to-server messages.

The client maintains a persistent connection to the server and handles message routing through channels while providing automatic reconnection and error handling capabilities.

func NewSSEClient

func NewSSEClient(baseURL string, httpClient *http.Client) *SSEClient

NewSSEClient creates and initializes a new SSE client instance with the specified base URL and HTTP client. If httpClient is nil, the default HTTP client will be used.

The baseURL parameter should point to the SSE endpoint of the server.

func (*SSEClient) Close

func (s *SSEClient) Close()

Close shuts down the SSE client by closing all internal channels and terminating the connection to the server. This stops all message processing and releases associated resources.

func (*SSEClient) Errors added in v0.2.0

func (s *SSEClient) Errors() <-chan error

Errors returns a receive-only channel that provides client-side errors that occur during operation. This includes connection errors, message parsing failures, and other operational errors.

func (*SSEClient) Send added in v0.2.0

func (s *SSEClient) Send(ctx context.Context, msg SessionMsg) error

Send delivers a message to the server using an HTTP POST request. The message is marshaled to JSON and sent to the server's message endpoint. The operation can be cancelled via the provided context.

Returns an error if message marshaling fails, the request cannot be created, or the server returns a non-200 status code.

func (*SSEClient) SessionMessages added in v0.2.0

func (s *SSEClient) SessionMessages() <-chan SessionMsgWithErrs

SessionMessages returns a receive-only channel that provides incoming messages from the server. Each message includes the session ID, the message content, and an error channel for reporting processing results back to the server.

func (*SSEClient) StartSession added in v0.2.0

func (s *SSEClient) StartSession() (string, error)

StartSession initiates a new SSE connection with the server and returns the session ID. It establishes the event stream connection and starts listening for server messages in a separate goroutine.

The returned session ID can be used to correlate messages with this specific connection. Returns an error if the connection cannot be established or the server response is invalid.

type SSEServer

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

SSEServer implements a Server-Sent Events (SSE) server that manages client connections and message distribution. It provides bidirectional communication through SSE for server-to-client streaming and HTTP POST for client-to-server messages.

The server maintains active client connections and handles message routing through channels while providing thread-safe operations using sync.Map for connection management.

func NewSSEServer

func NewSSEServer() SSEServer

NewSSEServer creates and initializes a new SSE server instance with all necessary channels for session management, message handling, and error reporting.

func (SSEServer) Close added in v0.2.0

func (s SSEServer) Close()

Close shuts down the SSE server by closing all internal channels. This terminates all active connections and stops message processing.

func (SSEServer) Errors added in v0.2.0

func (s SSEServer) Errors() <-chan error

Errors returns a receive-only channel that provides server-side errors that occur during operation. This includes connection, message handling, and internal processing errors.

func (SSEServer) HandleMessage

func (s SSEServer) HandleMessage() http.Handler

HandleMessage returns an http.Handler that processes incoming messages from clients via HTTP POST requests. It expects a session ID as a query parameter and the message content as JSON in the request body.

Messages are validated and routed through the server's message channel system for processing. Results are communicated back through the response.

func (SSEServer) HandleSSE

func (s SSEServer) HandleSSE(messageBaseURL string) http.Handler

HandleSSE returns an http.Handler that manages SSE connections from clients. It sets up appropriate headers for SSE communication, creates a new session, and maintains the connection until closed by the client or server.

The messageBaseURL parameter specifies the base URL for client message endpoints. Each client receives a unique message endpoint URL with their session ID.

func (SSEServer) Send added in v0.2.0

func (s SSEServer) Send(ctx context.Context, msg SessionMsg) error

Send delivers a message to a specific client session identified by the SessionMsg. It marshals the message to JSON and writes it to the client's event stream. The operation can be cancelled via the provided context.

Returns an error if the session is not found, message marshaling fails, or the write operation fails.

func (SSEServer) SessionMessages added in v0.2.0

func (s SSEServer) SessionMessages() <-chan SessionMsgWithErrs

SessionMessages returns a receive-only channel that provides incoming messages from clients. Each message includes the session ID, the message content, and an error channel for reporting processing results back to the client.

func (SSEServer) Sessions added in v0.2.0

func (s SSEServer) Sessions() <-chan SessionCtx

Sessions returns a receive-only channel that provides notifications of new client sessions. Each SessionCtx contains the session ID and associated context.

type SamplingCapability

type SamplingCapability struct{}

SamplingCapability represents sampling-specific capabilities.

type SamplingContent

type SamplingContent struct {
	Type ContentType `json:"type"`

	Text string `json:"text"`

	Data     string `json:"data"`
	MimeType string `json:"mimeType"`
}

SamplingContent represents the content of a sampling message. Contains the content type identifier, plain text content for text messages, or binary data with MIME type for non-text content. Either Text or Data should be populated based on the content Type.

type SamplingHandler

type SamplingHandler interface {
	// CreateSampleMessage generates a response message based on the provided conversation history and parameters.
	// Returns error if model selection fails, generation fails, token limit is exceeded, or context is cancelled.
	CreateSampleMessage(ctx context.Context, params SamplingParams) (SamplingResult, error)
}

SamplingHandler provides an interface for generating AI model responses based on conversation history. It handles the core sampling functionality including managing conversation context, applying model preferences, and generating appropriate responses while respecting token limits.

type SamplingMessage

type SamplingMessage struct {
	Role    PromptRole      `json:"role"`
	Content SamplingContent `json:"content"`
}

SamplingMessage represents a message in the sampling conversation history. Contains a role indicating the message sender (user or assistant) and the content of the message with its type and data.

type SamplingModelPreferences

type SamplingModelPreferences struct {
	Hints []struct {
		Name string `json:"name"`
	} `json:"hints"`
	CostPriority         int `json:"costPriority"`
	SpeedPriority        int `json:"speedPriority"`
	IntelligencePriority int `json:"intelligencePriority"`
}

SamplingModelPreferences defines preferences for model selection and behavior. Contains hints to guide model selection, and priority values for different aspects (cost, speed, intelligence) that influence the sampling process and model choice.

type SamplingParams

type SamplingParams struct {
	// Messages contains the conversation history as a sequence of user and assistant messages
	Messages []SamplingMessage `json:"messages"`

	// ModelPreferences controls model selection through cost, speed, and intelligence priorities
	ModelPreferences SamplingModelPreferences `json:"modelPreferences"`

	// SystemPrompts provides system-level instructions to guide the model's behavior
	SystemPrompts string `json:"systemPrompts"`

	// MaxTokens specifies the maximum number of tokens allowed in the generated response
	MaxTokens int `json:"maxTokens"`
}

SamplingParams defines the parameters for generating a sampled message. It provides complete control over the sampling process including:

  • Conversation history as a sequence of user and assistant messages
  • Model selection preferences for balancing cost, speed, and intelligence
  • System-level prompts that guide the model's behavior
  • Token limit constraints for the generated response

The params are used by SamplingHandler.CreateSampleMessage to generate appropriate AI model responses while respecting the specified constraints and preferences.

type SamplingResult

type SamplingResult struct {
	Role       PromptRole      `json:"role"`
	Content    SamplingContent `json:"content"`
	Model      string          `json:"model"`
	StopReason string          `json:"stopReason"`
}

SamplingResult represents the output of a sampling operation. Contains the role of the generated message, its content, the name of the model that generated it, and the reason why generation stopped (e.g., max tokens reached, natural completion).

type Server

type Server interface {
	Info() Info
	RequireRootsListClient() bool
	RequireSamplingClient() bool
}

Server represents the main MCP server interface that users will implement.

type ServerCapabilities

type ServerCapabilities struct {
	Prompts   *PromptsCapability   `json:"prompts,omitempty"`
	Resources *ResourcesCapability `json:"resources,omitempty"`
	Tools     *ToolsCapability     `json:"tools,omitempty"`
	Logging   *LoggingCapability   `json:"logging,omitempty"`
}

ServerCapabilities represents server capabilities.

type ServerOption

type ServerOption func(*server)

ServerOption represents the options for the server.

func WithLogHandler

func WithLogHandler(handler LogHandler) ServerOption

WithLogHandler sets the log handler for the server.

func WithProgressReporter

func WithProgressReporter(reporter ProgressReporter) ServerOption

WithProgressReporter sets the progress reporter for the server.

func WithPromptListUpdater

func WithPromptListUpdater(updater PromptListUpdater) ServerOption

WithPromptListUpdater sets the prompt list watcher for the server.

func WithPromptServer

func WithPromptServer(srv PromptServer) ServerOption

WithPromptServer sets the prompt server for the server.

func WithResourceListUpdater

func WithResourceListUpdater(updater ResourceListUpdater) ServerOption

WithResourceListUpdater sets the resource list watcher for the server.

func WithResourceServer

func WithResourceServer(srv ResourceServer) ServerOption

WithResourceServer sets the resource server for the server.

func WithResourceSubscribedUpdater

func WithResourceSubscribedUpdater(updater ResourceSubscribedUpdater) ServerOption

WithResourceSubscribedUpdater sets the resource subscribe watcher for the server.

func WithRootsListWatcher

func WithRootsListWatcher(watcher RootsListWatcher) ServerOption

WithRootsListWatcher sets the roots list watcher for the server.

func WithServerPingInterval

func WithServerPingInterval(interval time.Duration) ServerOption

WithServerPingInterval sets the ping interval for the server. If set to 0, the server will not send pings.

func WithServerReadTimeout

func WithServerReadTimeout(timeout time.Duration) ServerOption

WithServerReadTimeout sets the read timeout for the server.

func WithServerWriteTimeout

func WithServerWriteTimeout(timeout time.Duration) ServerOption

WithServerWriteTimeout sets the write timeout for the server.

func WithToolListUpdater

func WithToolListUpdater(updater ToolListUpdater) ServerOption

WithToolListUpdater sets the tool list watcher for the server.

func WithToolServer

func WithToolServer(srv ToolServer) ServerOption

WithToolServer sets the tool server for the server.

type ServerRequirement added in v0.2.0

type ServerRequirement struct {
	PromptServer   bool
	ResourceServer bool
	ToolServer     bool
}

ServerRequirement is a struct that specifies which server capabilities are required.

type ServerTransport added in v0.2.0

type ServerTransport interface {
	Transport

	// Sessions returns a receive-only channel that emits new client session
	// connections. Each SessionCtx contains both the unique session identifier
	// and a context that is cancelled when the session ends.
	//
	// The implementation must:
	// - Maintain session ordering and deliver all sessions without drops
	// - Keep the channel open for the transport's lifetime
	// - Close the context when its associated session terminates
	// - Support concurrent access from multiple goroutines
	Sessions() <-chan SessionCtx
}

ServerTransport extends the base Transport interface with server-specific functionality for accepting and managing client sessions. It provides the server-side communication layer in the MCP protocol.

type SessionCtx added in v0.2.0

type SessionCtx struct {
	// Ctx controls the session lifecycle. It is cancelled when the session ends.
	Ctx context.Context

	// ID uniquely identifies the session within the transport.
	// Must remain constant for the session duration.
	ID string
}

SessionCtx represents a client session context in the MCP protocol. It combines a context.Context for lifecycle management with a unique session identifier.

type SessionMsg added in v0.2.0

type SessionMsg struct {
	// SessionID identifies which session this message belongs to.
	// Must match an active session ID in the transport.
	SessionID string

	// Msg contains the JSON-RPC message payload.
	// Can be a request, response, or notification.
	Msg JSONRPCMessage
}

SessionMsg represents a message associated with a specific session. It combines the session identifier with the JSON-RPC message payload.

type SessionMsgWithErrs added in v0.2.0

type SessionMsgWithErrs struct {
	// SessionID identifies which session this message belongs to.
	// Must match an active session ID in the transport.
	SessionID string

	// Msg contains the JSON-RPC message payload.
	// Can be a request, response, or notification.
	Msg JSONRPCMessage

	// Errs receives exactly one error value after message processing completes.
	// A nil error indicates successful processing.
	Errs chan<- error
}

SessionMsgWithErrs extends SessionMsg with an error reporting channel. It enables asynchronous error handling for message processing operations.

type StdIO added in v0.2.0

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

StdIO implements a standard input/output transport layer for MCP communication. It provides bidirectional message passing using stdin/stdout or similar io.Reader/io.Writer pairs, with JSON-RPC message encoding.

StdIO manages a single persistent session and handles message routing through internal channels. It provides non-blocking error reporting and graceful shutdown capabilities through its channel-based architecture.

The transport layer maintains a single persistent session identified by "1" and processes messages sequentially through its internal channels. Error handling is managed through a dedicated error channel that provides non-blocking error reporting.

func NewStdIO added in v0.2.0

func NewStdIO(reader io.Reader, writer io.Writer) StdIO

NewStdIO creates a new standard IO transport instance using the provided reader and writer. The reader is typically os.Stdin and writer is typically os.Stdout, though any io.Reader and io.Writer implementations can be used for testing or custom IO scenarios.

It initializes internal channels for message passing, error handling, and shutdown coordination. The transport is ready for use immediately after creation but requires Start() to be called to begin processing messages. and io.Writer implementations can be used for testing or custom IO scenarios.

func (StdIO) Close added in v0.2.0

func (s StdIO) Close()

Close terminates the StdIO transport by closing the message and control channels. This will cause the Start() method to exit if it is running and prevent any new messages from being processed.

After Close() is called, the transport cannot be reused and a new instance should be created if needed.

func (StdIO) Errors added in v0.2.0

func (s StdIO) Errors() <-chan error

Errors returns a receive-only channel that provides access to transport-level errors. These may include message parsing errors, write failures, or other operational issues encountered during transport operation.

The channel is non-blocking and may drop errors if not consumed quickly enough.

func (StdIO) Send added in v0.2.0

func (s StdIO) Send(ctx context.Context, msg SessionMsg) error

Send writes a JSON-RPC message to the writer with context cancellation support. It marshals the message to JSON, appends a newline, and writes it to the underlying writer.

The context allows for cancellation of long-running write operations. If the context is cancelled before the write completes, the operation is abandoned and ctx.Err() is returned.

Returns an error if marshaling fails, the write operation fails, or the context is cancelled.

func (StdIO) SessionMessages added in v0.2.0

func (s StdIO) SessionMessages() <-chan SessionMsgWithErrs

SessionMessages returns a receive-only channel that provides access to incoming messages with their associated error channels. Each message is wrapped in a SessionMsgWithErrs struct that includes the session ID and an error channel for reporting processing results.

The channel is closed when the StdIO instance is closed via Close().

func (StdIO) Sessions added in v0.2.0

func (s StdIO) Sessions() <-chan SessionCtx

Sessions returns a receive-only channel that provides the single session context used by this transport. Since StdIO only supports a single session, this method sends one SessionCtx with ID "1" and a background context.

The returned channel should be consumed to prevent goroutine leaks.

func (StdIO) Start added in v0.2.0

func (s StdIO) Start()

Start begins processing input messages from the reader in a blocking manner. It continuously reads JSON-RPC messages line by line, unmarshals them, and forwards them to the message channel for processing.

The processing loop continues until either the reader is exhausted or Close() is called. Any unmarshaling or processing errors are sent to the error channel.

This method should typically be called in a separate goroutine as it blocks until completion or shutdown.

func (StdIO) StartSession added in v0.2.0

func (s StdIO) StartSession() (string, error)

StartSession initializes a new session for the StdIO transport. Since this implementation only supports a single session, it always returns the session ID "1" with no error.

This method is part of the Transport interface but has limited utility in the StdIO implementation due to its single-session nature.

type Tool

type Tool struct {
	Name        string             `json:"name"`
	Description string             `json:"description,omitempty"`
	InputSchema *jsonschema.Schema `json:"inputSchema,omitempty"`
}

Tool defines a callable tool with its input schema. InputSchema defines the expected format of arguments for CallTool.

type ToolList

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

ToolList represents a paginated list of tools returned by ListTools. NextCursor can be used to retrieve the next page of results.

type ToolListUpdater

type ToolListUpdater interface {
	ToolListUpdates() <-chan struct{}
}

ToolListUpdater provides an interface for monitoring changes to the available tools list. It maintains a channel that emits notifications whenever tools are added, removed, or modified.

The notifications are used by the MCP server to inform connected clients about tool list changes. Clients can then refresh their cached tool lists by calling ListTools again.

The channel returned by ToolListUpdates must: - Remain open for the lifetime of the updater - Be safe for concurrent receives from multiple goroutines - Never block on sends using buffered channels or dropped notifications

A struct{} is sent through the channel as only the notification matters, not the value.

type ToolListWatcher

type ToolListWatcher interface {
	// OnToolListChanged is called when the server notifies that its tool list has changed.
	// This can happen when tools are added, removed, or modified on the server side.
	OnToolListChanged()
}

ToolListWatcher provides an interface for receiving notifications when the server's tool list changes. Implementations can use these notifications to update their internal state or trigger UI updates when available tools are added, removed, or modified.

type ToolResult

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

ToolResult represents the outcome of a tool invocation via CallTool. IsError indicates whether the operation failed, with details in Content.

type ToolServer

type ToolServer interface {
	// ListTools returns a paginated list of available tools.
	// Returns error if operation fails or context is cancelled.
	ListTools(ctx context.Context, params ToolsListParams, requestClient RequestClientFunc) (ToolList, error)

	// CallTool executes a specific tool with the given arguments.
	// Returns error if tool not found, arguments are invalid, execution fails, or context is cancelled.
	CallTool(ctx context.Context, params ToolsCallParams, requestClient RequestClientFunc) (ToolResult, error)
}

ToolServer defines the interface for managing tools in the MCP protocol. It provides functionality for listing available tools and executing tool operations.

type ToolsCallParams

type ToolsCallParams struct {
	// Name is the unique identifier of the tool to execute
	Name string `json:"name"`

	// Arguments is a map of argument name-value pairs
	// Must satisfy required arguments defined in tool's InputSchema field
	Arguments map[string]any `json:"arguments"`

	// Meta contains optional metadata including:
	// - progressToken: Unique token for tracking operation progress
	//   * Used by ProgressReporter to emit progress updates if supported
	//   * Optional - may be ignored if progress tracking not supported
	Meta ParamsMeta `json:"_meta,omitempty"`
}

ToolsCallParams contains parameters for executing a specific tool.

type ToolsCapability

type ToolsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

ToolsCapability represents tools-specific capabilities.

type ToolsListParams

type ToolsListParams struct {
	// Cursor is a pagination cursor from previous ListTools call.
	// Empty string requests the first page.
	Cursor string `json:"cursor"`

	// Meta contains optional metadata including:
	// - progressToken: Unique token for tracking operation progress
	//   * Used by ProgressReporter to emit progress updates if supported
	//   * Optional - may be ignored if progress tracking not supported
	Meta ParamsMeta `json:"_meta,omitempty"`
}

ToolsListParams contains parameters for listing available tools.

type Transport added in v0.2.0

type Transport interface {
	// Send transmits a message to either server or client within a specific session.
	// The context controls the send operation's lifetime - implementations must respect
	// context cancellation and return appropriate errors.
	//
	// The SessionMsg parameter contains both the target session ID and the message payload.
	// Implementations should maintain session isolation to prevent cross-session interference.
	Send(ctx context.Context, msg SessionMsg) error

	// SessionMessages returns a receive-only channel that emits incoming messages from
	// connected peers. Each message includes the originating session ID, the message
	// content, and an error channel for reporting processing outcomes.
	//
	// The returned channel remains open for the lifetime of the transport. Implementations
	// must ensure the channel is properly closed when the transport is closed.
	//
	// The error channel in SessionMsgWithErrs must be handled by receiving exactly one
	// error value, even if errors are not relevant to the implementation.
	SessionMessages() <-chan SessionMsgWithErrs

	// Close terminates the transport, releasing any held resources and closing
	// all active sessions. After Close is called, no new messages can be sent
	// or received, and all pending operations should be cancelled.
	Close()
}

Transport provides the core communication interface between MCP servers and clients. It handles bidirectional message passing with support for multiple concurrent sessions. Implementations must ensure thread-safety and proper handling of context cancellation.

Jump to

Keyboard shortcuts

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