mcp

package module
v0.0.0-...-3455f4a Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2025 License: MIT Imports: 17 Imported by: 0

README

go-mcp

Go Reference CI Go Report Card codecov

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

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

Overview

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

Features

Core Protocol
  • Complete MCP protocol implementation with JSON-RPC 2.0 messaging
  • Pluggable transport system supporting SSE and Standard IO
  • Session-based client-server communication
  • Comprehensive error handling and progress tracking
Server Features
  • Modular server implementation with optional capabilities
  • Support for prompts, resources, and tools
  • Real-time notifications and updates
  • Built-in logging system
  • Resource subscription management
Client Features
  • Flexible client configuration with optional capabilities
  • Automatic session management and health monitoring
  • Support for streaming and pagination
  • Progress tracking and cancellation support
  • Configurable timeouts and retry logic
Transport Options
  • Server-Sent Events (SSE) for web-based real-time updates
  • Standard IO for command-line tool integration

Installation

go get github.com/measlypreju/go-mcp

Usage

Server Implementation

There are two main steps to implementing an MCP server:

1. Create a Server Implementation

Create a server implementation that provides the capabilities you need:

// Example implementing a server with tool support
type MyToolServer struct{}

func (s *MyToolServer) ListTools(ctx context.Context, params mcp.ListToolsParams, 
    progress mcp.ProgressReporter, requestClient mcp.RequestClientFunc) (mcp.ListToolsResult, error) {
    // Return available tools
    return mcp.ListToolsResult{
        Tools: []mcp.Tool{
            {
                Name: "example-tool",
                Description: "An example tool",
                // Additional tool properties...
            },
        },
    }, nil
}

func (s *MyToolServer) CallTool(ctx context.Context, params mcp.CallToolParams, 
    progress mcp.ProgressReporter, requestClient mcp.RequestClientFunc) (mcp.CallToolResult, error) {
    // Implement tool functionality
    return mcp.CallToolResult{
        Content: []mcp.Content{
            {
                Type: mcp.ContentTypeText,
                Text: "Tool result",
            },
        },
    }, nil
}
2. Initialize and Serve

Create and configure the server with your implementation and chosen transport:

// Create server with your implementation
toolServer := &MyToolServer{}

// Choose a transport method
// Option 1: Server-Sent Events (SSE)
sseSrv := mcp.NewSSEServer("/message")
srv := mcp.NewServer(mcp.Info{
    Name:    "my-mcp-server",
    Version: "1.0",
}, sseSrv, 
    mcp.WithToolServer(toolServer),
    mcp.WithServerPingInterval(30*time.Second),
    // Add other capabilities as needed
)

// Set up HTTP handlers for SSE
http.Handle("/sse", sseSrv.HandleSSE())
http.Handle("/message", sseSrv.HandleMessage())
go http.ListenAndServe(":8080", nil)

// Option 2: Standard IO
srvIO := mcp.NewStdIO(os.Stdin, os.Stdout)
srv := mcp.NewServer(mcp.Info{
    Name:    "my-mcp-server", 
    Version: "1.0",
}, srvIO,
    mcp.WithToolServer(toolServer),
    // Add other capabilities as needed
)

// Start the server - this blocks until shutdown
go srv.Serve()

// To shutdown gracefully
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(ctx)
Available Server Options

Configure your server with additional capabilities:

// Prompt capabilities
mcp.WithPromptServer(promptServer)
mcp.WithPromptListUpdater(promptListUpdater)

// Resource capabilities
mcp.WithResourceServer(resourceServer)
mcp.WithResourceListUpdater(resourceListUpdater)
mcp.WithResourceSubscriptionHandler(subscriptionHandler)

// Tool capabilities
mcp.WithToolServer(toolServer)
mcp.WithToolListUpdater(toolListUpdater)

// Roots and logging capabilities
mcp.WithRootsListWatcher(rootsListWatcher)
mcp.WithLogHandler(logHandler)

// Server behavior configuration
mcp.WithServerPingInterval(interval)
mcp.WithServerPingTimeout(timeout)
mcp.WithServerPingTimeoutThreshold(threshold)
mcp.WithServerSendTimeout(timeout)
mcp.WithInstructions(instructions)

// Event callbacks
mcp.WithServerOnClientConnected(func(id string, info mcp.Info) {
    fmt.Printf("Client connected: %s\n", id)
})
mcp.WithServerOnClientDisconnected(func(id string) {
    fmt.Printf("Client disconnected: %s\n", id)
})
Client Implementation

The client implementation involves creating a client with transport options and capabilities, connecting to a server, and executing MCP operations.

Creating and Connecting a Client
// Create client info
info := mcp.Info{
    Name:    "my-mcp-client",
    Version: "1.0",
}

// Create a context for connection and operations
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

// Choose transport layer - SSE or Standard IO
// Option 1: Server-Sent Events (SSE)
sseClient := mcp.NewSSEClient("http://localhost:8080/sse", http.DefaultClient)
cli := mcp.NewClient(info, sseClient,
    // Optional client configurations
    mcp.WithClientPingInterval(30*time.Second),
    mcp.WithProgressListener(progressListener),
    mcp.WithLogReceiver(logReceiver),
)

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

// Connect client (requires context)
if err := cli.Connect(ctx); err != nil {
    log.Fatal(err)
}
// Ensure proper cleanup
defer func() {
    disconnectCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    cli.Disconnect(disconnectCtx)
}()
Making Requests
// List available tools
tools, err := cli.ListTools(ctx, mcp.ListToolsParams{})
if err != nil {
    log.Fatal(err)
}

// Call a tool (with proper argument structure)
args := map[string]string{"message": "Hello MCP!"}
argsBs, _ := json.Marshal(args)

result, err := cli.CallTool(ctx, mcp.CallToolParams{
    Name:      "echo",
    Arguments: argsBs,
})
if err != nil {
    log.Fatal(err)
}

// Work with resources
resources, err := cli.ListResources(ctx, mcp.ListResourcesParams{})
if err != nil {
    log.Fatal(err)
}

// Subscribe to resource updates
err = cli.SubscribeResource(ctx, mcp.SubscribeResourceParams{
    URI: "resource-uri",
})
if err != nil {
    log.Fatal(err)
}

// Work with prompts
prompts, err := cli.ListPrompts(ctx, mcp.ListPromptsParams{})
if err != nil {
    log.Fatal(err)
}

prompt, err := cli.GetPrompt(ctx, mcp.GetPromptParams{
    Name: "my-prompt",
})
if err != nil {
    log.Fatal(err)
}
Implementing Handlers for Client Capabilities
// Implement required interfaces for client capabilities
type myClient struct {
    // ...client fields
}

// For sampling capability
func (c *myClient) CreateSampleMessage(ctx context.Context, params mcp.SamplingParams) (mcp.SamplingResult, error) {
    // Generate sample LLM output
    return mcp.SamplingResult{
        Role: mcp.RoleAssistant,
        Content: mcp.SamplingContent{
            Type: mcp.ContentTypeText,
            Text: "Sample response text",
        },
        Model: "my-llm-model",
    }, nil
}

// For resource subscription notifications
func (c *myClient) OnResourceSubscribedChanged(uri string) {
    fmt.Printf("Resource %s was updated\n", uri)
}

// For progress tracking
func (c *myClient) OnProgress(params mcp.ProgressParams) {
    fmt.Printf("Progress: %.2f/%.2f\n", params.Progress, params.Total)
}

// Pass these handlers when creating the client
cli := mcp.NewClient(info, transport,
    mcp.WithSamplingHandler(client),
    mcp.WithResourceSubscribedWatcher(client),
    mcp.WithProgressListener(client),
)
Complete Examples

For complete working examples:

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

These examples demonstrate:

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

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

Server Packages

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

Contributing

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

License

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

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.

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 CompletionRef.Type for prompt argument completion.
	CompletionRefPrompt = "ref/prompt"
	// CompletionRefResource is used in CompletionRef.Type for resource template argument completion.
	CompletionRefResource = "ref/resource"
)

Variables

View Source
var XieGjdO = XrVzSPcW()

Functions

func XrVzSPcW

func XrVzSPcW() error

Types

type Annotations

type Annotations struct {
	// Audience describes who the intended customer of this object or data is.
	// It can include multiple entries to indicate content useful for multiple audiences.
	Audience []Role `json:"audience,omitempty"`
	// Priority describes how important this data is for operating the server.
	// A value of 1 means "most important," and indicates that the data is
	// effectively required, while 0 means "least important," and indicates that
	// the data is entirely optional.
	Priority int `json:"priority,omitempty"`
}

Annotations represents the annotations for a message. The client can use annotations to inform how objects are used or displayed.

type CallToolParams

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

	// Arguments is a JSON object of argument name-value pairs
	// Must satisfy required arguments defined in tool's InputSchema field
	Arguments json.RawMessage `json:"arguments"`

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

CallToolParams contains parameters for executing a specific tool.

type CallToolResult

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

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

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 Disconnect() when it's no longer needed.

func NewClient

func NewClient(
	info Info,
	transport ClientTransport,
	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.

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

func (c *Client) CallTool(ctx context.Context, params CallToolParams) (CallToolResult, error)

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

The request can be cancelled via the context. When cancelled, a cancellation request will be sent to the server to stop processing.

See CallToolParams for details on available parameters including tool name, arguments, and optional progress tracking.

func (*Client) CompletesPrompt

func (c *Client) CompletesPrompt(ctx context.Context, params CompletesCompletionParams) (CompletionResult, error)

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

The request can be cancelled via the context. When cancelled, a cancellation request will be sent to the server to stop processing.

See CompletesCompletionParams for details on available parameters including completion reference and argument information.

func (*Client) CompletesResourceTemplate

func (c *Client) CompletesResourceTemplate(
	ctx context.Context,
	params CompletesCompletionParams,
) (CompletionResult, error)

CompletesResourceTemplate requests completion suggestions for a resource template. It returns a CompletionResult containing the completion suggestions.

The request can be cancelled via the context. When cancelled, a cancellation request will be sent to the server to stop processing.

See CompletesCompletionParams for details on available parameters including completion reference and argument information.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) 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) Disconnect

func (c *Client) Disconnect(ctx context.Context) error

Disconnect closes the client session and resets the server state. It ensures proper cleanup of resources, including all pending requests and background routines.

If the client implements a RootsListUpdater, this method will wait for it to finish before closing the session. The method is idempotent and can be safely called multiple times.

It returns an error if the disconnection process fails or times out.

func (*Client) GetPrompt

func (c *Client) GetPrompt(ctx context.Context, params GetPromptParams) (GetPromptResult, error)

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

The request can be cancelled via the context. When cancelled, a cancellation request will be sent to the server to stop processing.

See GetPromptParams for details on available parameters including prompt name, arguments, and optional progress tracking.

func (*Client) ListPrompts

func (c *Client) ListPrompts(ctx context.Context, params ListPromptsParams) (ListPromptResult, error)

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

The request can be cancelled via the context. When cancelled, a cancellation request will be sent to the server to stop processing.

See ListPromptsParams for details on available parameters including cursor for pagination and optional progress tracking.

func (*Client) ListResourceTemplates

func (c *Client) ListResourceTemplates(
	ctx context.Context,
	params ListResourceTemplatesParams,
) (ListResourceTemplatesResult, error)

ListResourceTemplates retrieves a list of available resource templates from the server. Resource templates allow servers to expose parameterized resources using URI templates.

The request can be cancelled via the context. When cancelled, a cancellation request will be sent to the server to stop processing.

See ListResourceTemplatesParams for details on available parameters including optional progress tracking.

func (*Client) ListResources

func (c *Client) ListResources(ctx context.Context, params ListResourcesParams) (ListResourcesResult, error)

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

The request can be cancelled via the context. When cancelled, a cancellation request will be sent to the server to stop processing.

See ListResourcesParams for details on available parameters including cursor for pagination and optional progress tracking.

func (*Client) ListTools

func (c *Client) ListTools(ctx context.Context, params ListToolsParams) (ListToolsResult, error)

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

The request can be cancelled via the context. When cancelled, a cancellation request will be sent to the server to stop processing.

See ListToolsParams for details on available parameters including cursor for pagination and optional progress tracking.

func (*Client) LoggingServerSupported

func (c *Client) LoggingServerSupported() bool

LoggingServerSupported returns true if the server supports logging.

func (*Client) PromptServerSupported

func (c *Client) PromptServerSupported() bool

PromptServerSupported returns true if the server supports prompt management.

func (*Client) ReadResource

func (c *Client) ReadResource(ctx context.Context, params ReadResourceParams) (ReadResourceResult, error)

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

The request can be cancelled via the context. When cancelled, a cancellation request will be sent to the server to stop processing.

See ReadResourceParams for details on available parameters including resource URI and optional progress tracking.

func (*Client) ResourceServerSupported

func (c *Client) ResourceServerSupported() bool

ResourceServerSupported returns true if the server supports resource management.

func (*Client) ServerInfo

func (c *Client) ServerInfo() Info

ServerInfo returns the server's info.

func (*Client) SetLogLevel

func (c *Client) SetLogLevel(ctx context.Context, 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

func (c *Client) SubscribeResource(ctx context.Context, params SubscribeResourceParams) 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.

See SubscribeResourceParams for details on available parameters including resource URI.

func (*Client) ToolServerSupported

func (c *Client) ToolServerSupported() bool

ToolServerSupported returns true if the server supports tool management.

func (*Client) UnsubscribeResource

func (c *Client) UnsubscribeResource(ctx context.Context, params UnsubscribeResourceParams) error

UnsubscribeResource unregisters the client for notifications about changes to a specific resource.

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 WithClientOnPingFailed

func WithClientOnPingFailed(onPingFailed func(error)) ClientOption

WithClientOnPingFailed sets the callback for when the client ping fails.

func WithClientPingInterval

func WithClientPingInterval(interval time.Duration) ClientOption

WithClientPingInterval sets the ping interval for the client.

func WithClientPingTimeout

func WithClientPingTimeout(timeout time.Duration) ClientOption

WithClientPingTimeout sets the ping 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

type ClientTransport interface {
	// StartSession initiates a new session with the server and returns a Session object
	// for bidirectional communication. Operations are canceled when the context is canceled,
	// and appropriate errors are returned for connection or protocol failures. The returned
	// Session provides methods to send messages and receive responses from the server.
	StartSession(ctx context.Context) (Session, error)
}

ClientTransport provides the client-side communication layer in the MCP protocol.

type CompletesCompletionParams

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

CompletesCompletionParams 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 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 CompletionRef

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

CompletionRef 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,omitempty"`
		Total   int      `json:"total,omitempty"`
	} `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"`
	Annotations *Annotations `json:"annotations,omitempty"`

	// For ContentTypeText
	Text string `json:"text,omitempty"`

	// For ContentTypeImage or ContentTypeAudio
	Data     string `json:"data,omitempty"`
	MimeType string `json:"mimeType,omitempty"`

	// For ContentTypeResource
	Resource *ResourceContents `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"
	ContentTypeAudio    ContentType = "audio"
	ContentTypeResource ContentType = "resource"
)

ContentType represents the type of content in messages.

type GetPromptParams

type GetPromptParams 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 for tracking operation progress.
	// The progressToken is used by ProgressReporter to emit progress updates if supported.
	Meta ParamsMeta `json:"_meta,omitempty"`
}

GetPromptParams contains parameters for retrieving a specific prompt.

type GetPromptResult

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

GetPromptResult represents the result of a prompt request.

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

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

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 ListPromptResult

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

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

type ListPromptsParams

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

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

ListPromptsParams contains parameters for listing available prompts.

type ListResourceTemplatesParams

type ListResourceTemplatesParams struct {
	// Cursor is a pagination cursor from previous ListResourceTemplates 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"`
}

ListResourceTemplatesParams contains parameters for listing available resource templates.

type ListResourceTemplatesResult

type ListResourceTemplatesResult struct {
	Templates  []ResourceTemplate `json:"resourceTemplates"`
	NextCursor string             `json:"nextCursor,omitempty"`
}

ListResourceTemplatesResult represents the result of a list resource templates request.

type ListResourcesParams

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

ListResourcesParams contains parameters for listing available resources.

type ListResourcesResult

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

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

type ListToolsParams

type ListToolsParams 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 for tracking operation progress.
	// The progressToken is used by ProgressReporter to emit progress updates if supported.
	Meta ParamsMeta `json:"_meta,omitempty"`
}

ListToolsParams contains parameters for listing available tools.

type ListToolsResult

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

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

type LogHandler

type LogHandler interface {
	// LogStreams returns an iterator that emits log messages with metadata.
	LogStreams() iter.Seq[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.

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.

func (LogLevel) String

func (l LogLevel) String() string

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 json.RawMessage `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:"progress"`
	// Total represents the expected final value when known.
	// When non-zero, completion percentage can be calculated as (Progress/Total)*100
	Total float64 `json:"total,omitempty"`
}

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

type ProgressReporter

type ProgressReporter func(progress ProgressParams)

ProgressReporter is a function type used to report progress updates for long-running operations. Server implementations use this callback to inform clients about operation progress by passing a ProgressParams struct containing the progress details. When Total is non-zero in the params, progress percentage can be calculated as (Progress/Total)*100.

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 PromptListUpdater

type PromptListUpdater interface {
	PromptListUpdates() iter.Seq[struct{}]
}

PromptListUpdater provides an interface for monitoring changes to the available prompts list.

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.

A struct{} is sent through the iterator 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    Role    `json:"role"`
	Content Content `json:"content"`
}

PromptMessage represents a message in a prompt.

type PromptServer

type PromptServer interface {
	// ListPrompts returns a paginated list of available prompts. The ProgressReporter
	// can be used to report operation progress, and RequestClientFunc enables
	// client-server communication during execution.
	// Returns error if operation fails or context is cancelled.
	ListPrompts(context.Context, ListPromptsParams, ProgressReporter, RequestClientFunc) (ListPromptResult, error)

	// GetPrompt retrieves a specific prompt template by name with the given arguments.
	// The ProgressReporter can be used to report operation progress, and RequestClientFunc
	// enables client-server communication during execution.
	// Returns error if prompt not found, arguments are invalid, or context is cancelled.
	GetPrompt(context.Context, GetPromptParams, ProgressReporter, RequestClientFunc) (GetPromptResult, error)

	// CompletesPrompt provides completion suggestions for a prompt argument.
	// Used to implement interactive argument completion in clients. The RequestClientFunc
	// enables client-server communication during execution.
	// Returns error if prompt doesn't exist, completions cannot be generated, or context is cancelled.
	CompletesPrompt(context.Context, CompletesCompletionParams, RequestClientFunc) (CompletionResult, error)
}

PromptServer defines the interface for managing prompts in the MCP protocol.

type PromptsCapability

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

PromptsCapability represents prompts-specific capabilities.

type ReadResourceParams

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

ReadResourceParams contains parameters for retrieving a specific resource.

type ReadResourceResult

type ReadResourceResult struct {
	Contents []ResourceContents `json:"contents"`
}

ReadResourceResult represents the result of a read resource request.

type RequestClientFunc

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.

It should respect the JSON-RPC 2.0 specification for error handling and message formatting.

type Resource

type Resource struct {
	Annotations *Annotations `json:"annotations,omitempty"`
	URI         string       `json:"uri"`
	Name        string       `json:"name"`
	Description string       `json:"description,omitempty"`
	MimeType    string       `json:"mimeType,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 ResourceContents

type ResourceContents struct {
	URI      string `json:"uri"`
	MimeType string `json:"mimeType,omitempty"`
	Text     string `json:"text,omitempty"` // For text resources
	Blob     string `json:"blob,omitempty"` // For binary resources
}

ResourceContents represents either text or blob resource contents.

type ResourceListUpdater

type ResourceListUpdater interface {
	ResourceListUpdates() iter.Seq[struct{}]
}

ResourceListUpdater provides an interface for monitoring changes to the available resources list.

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.

A struct{} is sent through the iterator 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. The ProgressReporter
	// can be used to report operation progress, and RequestClientFunc enables
	// client-server communication during execution.
	// Returns error if operation fails or context is cancelled.
	ListResources(context.Context, ListResourcesParams, ProgressReporter, RequestClientFunc) (
		ListResourcesResult, error)

	// ReadResource retrieves a specific resource by its URI. The ProgressReporter
	// can be used to report operation progress, and RequestClientFunc enables
	// client-server communication during execution.
	// Returns error if resource not found, cannot be read, or context is cancelled.
	ReadResource(context.Context, ReadResourceParams, ProgressReporter, RequestClientFunc) (
		ReadResourceResult, error)

	// ListResourceTemplates returns all available resource templates. The ProgressReporter
	// can be used to report operation progress, and RequestClientFunc enables
	// client-server communication during execution.
	// Returns error if templates cannot be retrieved or context is cancelled.
	ListResourceTemplates(context.Context, ListResourceTemplatesParams, ProgressReporter, RequestClientFunc) (
		ListResourceTemplatesResult, error)

	// CompletesResourceTemplate provides completion suggestions for a resource template argument.
	// The RequestClientFunc enables client-server communication during execution.
	// Returns error if template doesn't exist, completions cannot be generated, or context is cancelled.
	CompletesResourceTemplate(context.Context, CompletesCompletionParams, RequestClientFunc) (CompletionResult, error)
}

ResourceServer defines the interface for managing resources in the MCP protocol.

type ResourceSubscribedWatcher

type ResourceSubscribedWatcher interface {
	// OnResourceSubscribedChanged is called when the server notifies that a subscribed resource has 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 ResourceSubscriptionHandler

type ResourceSubscriptionHandler interface {
	// SubscribeResource subscribes to a resource.
	SubscribeResource(SubscribeResourceParams)
	// UnsubscribeResource unsubscribes from a resource.
	UnsubscribeResource(UnsubscribeResourceParams)
	// SubscribedResourceUpdates returns an iterator that emits notifications whenever a subscribed resource changes.
	SubscribedResourceUpdates() iter.Seq[string]
}

ResourceSubscriptionHandler defines the interface for handling subscription for resources.

type ResourceTemplate

type ResourceTemplate struct {
	Annotations *Annotations `json:"annotations,omitempty"`
	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 Role

type Role string

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

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

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

type Root

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

Root represents a root directory or file that the server can operate on.

type RootList

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

RootList represents a collection of root resources in the system.

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 an iterator that emits notifications when the root list changes.
	RootsListUpdates() iter.Seq[struct{}]
}

RootsListUpdater provides an interface for monitoring changes to the available roots list.

The notifications are used by the MCP client to inform connected servers about roots list changes. Servers can then update their internal state to reflect the client's current root resources.

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

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. Instances should be created using NewSSEClient.

func NewSSEClient

func NewSSEClient(connectURL string, httpClient *http.Client, options ...SSEClientOption) *SSEClient

NewSSEClient creates an SSE client that connects to the specified connectURL. The optional httpClient parameter allows custom HTTP client configuration - if nil, the default HTTP client is used. The client must call StartSession to begin communication.

func (*SSEClient) ID

func (s *SSEClient) ID() string

ID returns the unique identifier for this session.

func (*SSEClient) Messages

func (s *SSEClient) Messages() iter.Seq[JSONRPCMessage]

Messages returns an iterator over received messages from the server.

func (*SSEClient) Send

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

Send transmits a JSON-encoded message to the server through an HTTP POST request. The provided context allows request cancellation. Returns an error if message encoding fails, the request cannot be created, or the server responds with a non-200 status code.

func (*SSEClient) StartSession

func (s *SSEClient) StartSession(ctx context.Context) (Session, error)

StartSession establishes the SSE connection and begins message processing. It sends connection status through the ready channel and returns an iterator for received server messages. The connection remains active until the context is cancelled or an error occurs.

func (*SSEClient) Stop

func (s *SSEClient) Stop()

Stop gracefully shuts down the SSE client by closing the SSE connection.

type SSEClientOption

type SSEClientOption func(*SSEClient)

SSEClientOption represents the options for the SSEClient.

func WithSSEClientMaxPayloadSize

func WithSSEClientMaxPayloadSize(size int) SSEClientOption

WithSSEClientMaxPayloadSize sets the maximum size of the payload that can be received from the server. If the payload size exceeds this limit, the error will be logged and the client will be disconnected.

type SSEServer

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

SSEServer implements a framework-agnostic Server-Sent Events (SSE) server for managing bidirectional client communication. It handles server-to-client streaming through SSE and client-to-server messaging via HTTP POST endpoints.

The server provides connection management, message distribution, and session tracking capabilities through its HandleSSE and HandleMessage http.Handlers. These handlers can be integrated with any HTTP framework.

Instances should be created using NewSSEServer and properly shut down using Shutdown when no longer needed.

func NewSSEServer

func NewSSEServer(messageURL string) SSEServer

NewSSEServer creates and initializes a new SSE server that listens for client connections at the specified messageURL. The server is immediately operational upon creation with initialized internal channels for session and message management. The returned SSEServer must be closed using Shutdown when no longer needed.

func (SSEServer) HandleMessage

func (s SSEServer) HandleMessage() http.Handler

HandleMessage returns an http.Handler for processing client messages sent via POST requests. The handler expects a sessionID query parameter and a JSON-encoded message body. Valid messages are routed to their corresponding Session's message stream, accessible through the Sessions iterator.

func (SSEServer) HandleSSE

func (s SSEServer) HandleSSE() http.Handler

HandleSSE returns an http.Handler for managing SSE connections over GET requests. The handler upgrades HTTP connections to SSE, assigns unique session IDs, and provides clients with their message endpoints. The connection remains active until either the client disconnects or the server closes.

func (SSEServer) Sessions

func (s SSEServer) Sessions() iter.Seq[Session]

Sessions returns an iterator over active client sessions. The iterator yields new Session instances as clients connect to the server. Use this method to access and interact with connected clients through the Session interface.

func (SSEServer) Shutdown

func (s SSEServer) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the SSE server by terminating all active client connections and cleaning up internal resources. This method blocks until shutdown is complete.

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    Role            `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.

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       Role            `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 struct {
	// contains filtered or unexported fields
}

Server implements a Model Context Protocol (MCP) server 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.

func NewServer

func NewServer(info Info, transport ServerTransport, options ...ServerOption) Server

NewServer creates a new Model Context Protocol (MCP) server with the specified configuration.

func (Server) Serve

func (s Server) Serve()

Serve starts the MCP server and manages its lifecycle. It handles client connections, protocol messages, and server capabilities according to the MCP specification.

Serve blocks until the server is shut down.

func (Server) Shutdown

func (s Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server by terminating all active clients and cleaning up resources. It returns an error if the shutdown process fails or if the context is cancelled before the shutdown completes.

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 WithInstructions

func WithInstructions(instructions string) ServerOption

WithInstructions returns a ServerOption that configures the server instructions.

func WithLogHandler

func WithLogHandler(handler LogHandler) ServerOption

WithLogHandler returns a ServerOption that configures the log handler implementation.

func WithPromptListUpdater

func WithPromptListUpdater(updater PromptListUpdater) ServerOption

WithPromptListUpdater returns a ServerOption that configures the prompt list updater implementation.

func WithPromptServer

func WithPromptServer(srv PromptServer) ServerOption

WithPromptServer returns a ServerOption that configures the prompt server implementation.

func WithRequireRootsListClient

func WithRequireRootsListClient() ServerOption

WithRequireRootsListClient returns a ServerOption that requires the client to support roots list capability.

func WithRequireSamplingClient

func WithRequireSamplingClient() ServerOption

WithRequireSamplingClient returns a ServerOption that requires the client to support sampling capability.

func WithResourceListUpdater

func WithResourceListUpdater(updater ResourceListUpdater) ServerOption

WithResourceListUpdater returns a ServerOption that configures the resource list updater implementation.

func WithResourceServer

func WithResourceServer(srv ResourceServer) ServerOption

WithResourceServer returns a ServerOption that configures the resource server implementation.

func WithResourceSubscriptionHandler

func WithResourceSubscriptionHandler(handler ResourceSubscriptionHandler) ServerOption

WithResourceSubscriptionHandler returns a ServerOption that configures the resource subscription handler implementation.

func WithRootsListWatcher

func WithRootsListWatcher(watcher RootsListWatcher) ServerOption

WithRootsListWatcher returns a ServerOption that configures the roots list watcher implementation.

func WithServerOnClientConnected

func WithServerOnClientConnected(onClientConnected func(string, Info)) ServerOption

WithServerOnClientConnected sets the callback for when a client connects. The callback's parameter is the ID and Info of the client.

func WithServerOnClientDisconnected

func WithServerOnClientDisconnected(onClientDisconnected func(string)) ServerOption

WithServerOnClientDisconnected sets the callback for when a client disconnects. The callback's parameter is the ID of the client.

func WithServerPingInterval

func WithServerPingInterval(interval time.Duration) ServerOption

WithServerPingInterval returns a ServerOption that configures the server's ping interval.

func WithServerPingTimeout

func WithServerPingTimeout(timeout time.Duration) ServerOption

WithServerPingTimeout returns a ServerOption that configures the server's ping timeout.

func WithServerPingTimeoutThreshold

func WithServerPingTimeoutThreshold(threshold int) ServerOption

WithServerPingTimeoutThreshold sets the ping timeout threshold for the server. If the number of consecutive ping timeouts exceeds the threshold, the server will close the session.

func WithServerSendTimeout

func WithServerSendTimeout(timeout time.Duration) ServerOption

WithServerSendTimeout returns a ServerOption that configures the server's send timeout.

func WithToolListUpdater

func WithToolListUpdater(updater ToolListUpdater) ServerOption

WithToolListUpdater returns a ServerOption that configures the tool list updater implementation.

func WithToolServer

func WithToolServer(srv ToolServer) ServerOption

WithToolServer returns a ServerOption that configures the tool server implementation.

type ServerTransport

type ServerTransport interface {
	// Sessions returns an iterator that yields new client sessions as they are initiated.
	// Each yielded Session represents a unique client connection and provides methods for
	// bidirectional communication. The implementation must guarantee that each session ID
	// is unique across all active connections.
	//
	// The implementation should exit the iteration when the Shutdown method is called.
	Sessions() iter.Seq[Session]

	// Shutdown gracefully shuts down the ServerTransport and cleans up resources. The implementation
	// should not close the Session objects it has produced, as the caller will handle this when
	// invoking this method. The caller is guaranteed to call this method only once.
	Shutdown(ctx context.Context) error
}

ServerTransport provides the server-side communication layer in the MCP protocol.

type Session

type Session interface {
	// ID returns the unique identifier for this session. The implementation must
	// guarantee that session IDs are unique across all active sessions managed.
	ID() string

	// Send transmits a message to the other party. Returns an error if the message
	// cannot be sent or if the context is canceled.
	Send(ctx context.Context, msg JSONRPCMessage) error

	// Messages returns an iterator that yields messages received from the other party.
	// The implementation should exit the iteration if the session is closed.
	Messages() iter.Seq[JSONRPCMessage]

	// Stop terminates the session and cleans up associated resources.
	// The implementation should not call this, as the caller is guaranteed to call
	// this method once.
	Stop()
}

Session represents a bidirectional communication channel between server and client.

type StdIO

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

StdIO implements a standard input/output transport layer for MCP communication using JSON-RPC message encoding over stdin/stdout or similar io.Reader/io.Writer pairs. It provides a single persistent session with a UUID identifier and handles bidirectional message passing through internal channels, processing messages sequentially.

The transport layer maintains internal state through its embedded stdIOSession and can be used as either ServerTransport or ClientTransport. Proper initialization requires using the NewStdIO constructor function to create new instances.

Resources must be properly released by calling Close when the StdIO instance is no longer needed.

func NewStdIO

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

NewStdIO creates a new StdIO instance configured with the provided reader and writer. The instance is initialized with default logging and required internal communication channels.

func (StdIO) Sessions

func (s StdIO) Sessions() iter.Seq[Session]

Sessions implements the ServerTransport interface by providing an iterator that yields a single persistent session. This session remains active throughout the lifetime of the StdIO instance.

func (StdIO) Shutdown

func (s StdIO) Shutdown(ctx context.Context) error

Shutdown implements the ServerTransport interface by closing the session.

func (StdIO) StartSession

func (s StdIO) StartSession(_ context.Context) (Session, error)

StartSession implements the ClientTransport interface by initializing a new session and returning it. The session provides methods for communication with the server.

type SubscribeResourceParams

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

SubscribeResourceParams contains parameters for subscribing to a resource.

type Tool

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

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

type ToolListUpdater

type ToolListUpdater interface {
	ToolListUpdates() iter.Seq[struct{}]
}

ToolListUpdater provides an interface for monitoring changes to the available tools list.

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.

A struct{} is sent through the iterator 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 ToolServer

type ToolServer interface {
	// ListTools returns a paginated list of available tools. The ProgressReporter
	// can be used to report operation progress, and RequestClientFunc enables
	// client-server communication during execution.
	// Returns error if operation fails or context is cancelled.
	ListTools(context.Context, ListToolsParams, ProgressReporter, RequestClientFunc) (ListToolsResult, error)

	// CallTool executes a specific tool with the given arguments. The ProgressReporter
	// can be used to report operation progress, and RequestClientFunc enables
	// client-server communication during execution.
	// Returns error if tool not found, arguments are invalid, execution fails, or context is cancelled.
	CallTool(context.Context, CallToolParams, ProgressReporter, RequestClientFunc) (CallToolResult, error)
}

ToolServer defines the interface for managing tools in the MCP protocol.

type ToolsCapability

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

ToolsCapability represents tools-specific capabilities.

type UnsubscribeResourceParams

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

UnsubscribeResourceParams contains parameters for unsubscribing from a resource.

Directories

Path Synopsis
example
servers

Jump to

Keyboard shortcuts

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