Documentation
¶
Overview ¶
Package server provides the server-side implementation of the MCP protocol. It offers a comprehensive API for building and running MCP servers that can register tools, resources, and prompt templates for client interaction.
Index ¶
- func DefaultGRPCServerOptions() []grpc.Option
- func ExtractProtocolVersion(params json.RawMessage) (string, error)
- func FormatResourceResponse(uri string, result interface{}, version string) map[string]interface{}
- func HandleMessage(s *serverImpl, message []byte) ([]byte, error)
- func HandleMessageWithVersion(srv Server, message []byte, version string) ([]byte, error)
- func SimpleJSONResponse(data interface{}) map[string]interface{}
- func SimpleTextResponse(text string) map[string]interface{}
- func SubstituteVariables(content string, variables map[string]interface{}) (string, error)
- func ValidateContentForVersion(content SamplingContentHandler, version string) error
- func WithGRPCKeepAlive(time, timeout time.Duration) grpc.Option
- func WithGRPCMaxMessageSize(size int) grpc.Option
- func WithGRPCTLS(certFile, keyFile, caFile string) grpc.Option
- func WithGRPCTimeout(timeout time.Duration) grpc.Option
- type AudioResource
- type AudioSamplingContent
- type ClientInfo
- type ClientSession
- type ContentItem
- func BlobContent(blob string, mimeType string) ContentItem
- func FileContent(fileURL string, filename string, mimeType string) ContentItem
- func ImageContent(imageURL string, altText string, optMimeType ...string) ContentItem
- func JSONContent(data interface{}) ContentItem
- func LinkContent(url, title string) ContentItem
- func TextContent(text string) ContentItem
- type ContentType
- type Context
- func (c *Context) Deadline() (deadline interface{}, ok bool)
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) ExecuteResource(resourcePath string) (interface{}, error)
- func (c *Context) ExecuteTool(toolName string, args map[string]interface{}) (interface{}, error)
- func (c *Context) GetRegisteredResources() ([]*Resource, error)
- func (c *Context) GetRegisteredTools() ([]*Tool, error)
- func (c *Context) GetResourceDetails(resourcePath string) (*Resource, error)
- func (c *Context) GetSamplingController() (*SamplingController, error)
- func (c *Context) GetToolDetails(toolName string) (*Tool, error)
- func (c *Context) RequestSampling(messages []SamplingMessage, preferences SamplingModelPreferences, ...) (*SamplingResponse, error)
- func (c *Context) RequestSamplingWithPriority(messages []SamplingMessage, preferences SamplingModelPreferences, ...) (*SamplingResponse, error)
- func (c *Context) ValidateSamplingRequest(messages []SamplingMessage, maxTokens int) error
- func (c *Context) Value(key interface{}) interface{}
- type FileResource
- type ImageResource
- type ImageSamplingContent
- type InvalidParametersError
- type JSONResource
- type LinkResource
- type Option
- type Prompt
- type PromptArgument
- type PromptContent
- type PromptTemplate
- type ProtocolSamplingConfig
- type RPCError
- type Request
- type RequestSamplingOptions
- type Resource
- type ResourceConverter
- type ResourceHandler
- type ResourceResponse
- type Response
- type SamplingCapabilities
- type SamplingConfig
- type SamplingContentHandler
- type SamplingController
- func (sc *SamplingController) CanProcessRequest(sessionID SessionID) bool
- func (sc *SamplingController) CompleteRequest(sessionID SessionID)
- func (sc *SamplingController) GetConcurrentRequestCount() int
- func (sc *SamplingController) GetRequestOptions(priority int) RequestSamplingOptions
- func (sc *SamplingController) RecordRequest(sessionID SessionID)
- func (sc *SamplingController) Stop()
- func (sc *SamplingController) ValidateForProtocol(protocol string, messages []SamplingMessage, maxTokens int) error
- type SamplingCreateMessageParams
- type SamplingMessage
- func CreateAudioSamplingMessage(role, audioData, mimeType string) SamplingMessage
- func CreateImageSamplingMessage(role, imageData, mimeType string) SamplingMessage
- func CreateSamplingMessage(role string, content SamplingContentHandler) (SamplingMessage, error)
- func CreateTextSamplingMessage(role, text string) SamplingMessage
- type SamplingMessageContent
- type SamplingModelHint
- type SamplingModelPreferences
- type SamplingResponse
- type Server
- type SessionID
- type SessionManager
- func (sm *SessionManager) CloseSession(id SessionID) bool
- func (sm *SessionManager) CreateSession(clientInfo ClientInfo, protocolVersion string) *ClientSession
- func (sm *SessionManager) GetSession(id SessionID) (*ClientSession, bool)
- func (sm *SessionManager) UpdateClientCapabilities(id SessionID, caps SamplingCapabilities) bool
- func (sm *SessionManager) UpdateSession(id SessionID, update func(*ClientSession)) bool
- type TextResource
- type TextSamplingContent
- type Tool
- type ToolHandler
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultGRPCServerOptions ¶ added in v1.2.1
DefaultGRPCServerOptions returns a set of default options for gRPC server.
func ExtractProtocolVersion ¶ added in v1.2.0
func ExtractProtocolVersion(params json.RawMessage) (string, error)
ExtractProtocolVersion extracts the protocol version from the initialize request params. It attempts to parse the protocolVersion field from JSON-RPC params, handling different data types and formats that clients might send.
Parameters:
- params: The raw JSON params from an initialize request
Returns:
- The extracted protocol version as a string, or empty string if not found
- An error if the params cannot be parsed
func FormatResourceResponse ¶ added in v1.2.0
FormatResourceResponse formats a response according to MCP validation requirements. This ensures that text/blob content items have the required fields and format.
func HandleMessage ¶ added in v1.2.0
HandleMessage handles an incoming message from the transport. It parses the message, routes it to the appropriate handler, and returns the response.
func HandleMessageWithVersion ¶ added in v1.2.0
HandleMessageWithVersion handles a JSON-RPC message with a forced MCP version. This is primarily used for testing and allows processing messages with a specific protocol version regardless of what was negotiated during initialization. It provides a simplified subset of method handlers compared to the main HandleMessage function.
func SimpleJSONResponse ¶ added in v1.2.0
func SimpleJSONResponse(data interface{}) map[string]interface{}
SimpleJSONResponse creates a JSON resource response
func SimpleTextResponse ¶ added in v1.2.0
SimpleTextResponse creates a simple text response map
func SubstituteVariables ¶ added in v1.2.0
SubstituteVariables replaces all {{variable}} patterns in the content string with their corresponding values from the variables map. Returns an error if a required variable is missing from the map.
func ValidateContentForVersion ¶ added in v1.2.0
func ValidateContentForVersion(content SamplingContentHandler, version string) error
ValidateContentForVersion checks if a content handler is valid for the given protocol version. This function combines content validation with protocol version compatibility checking to ensure that messages conform to both content-specific rules and protocol constraints.
Parameters:
- content: The content handler to validate
- version: The protocol version to check against
Returns:
- nil if the content is valid for the protocol version
- An error describing the validation failure otherwise
func WithGRPCKeepAlive ¶ added in v1.2.1
WithGRPCKeepAlive configures keepalive parameters for the gRPC transport.
func WithGRPCMaxMessageSize ¶ added in v1.2.1
WithGRPCMaxMessageSize sets the maximum message size for the gRPC transport.
func WithGRPCTLS ¶ added in v1.2.1
WithGRPCTLS configures TLS for the gRPC transport.
Types ¶
type AudioResource ¶ added in v1.2.0
type AudioResource struct {
// URL is the URL of the audio file. Required for all versions.
URL string
// Data is the base64-encoded audio data. Used in 2025-03-26 version.
Data string
// MimeType is the MIME type of the audio file. Required for all versions.
MimeType string
// AltText is an optional descriptive text for the audio
AltText string
}
AudioResource represents an audio resource to be returned from a handler
func (AudioResource) ToResourceResponse ¶ added in v1.2.0
func (a AudioResource) ToResourceResponse() map[string]interface{}
ToResourceResponse converts the AudioResource to a protocol-specific representation
type AudioSamplingContent ¶ added in v1.2.0
AudioSamplingContent creates an audio content struct for sampling messages. This implementation of SamplingContentHandler manages audio content for sampling conversations, storing the audio data and its MIME type.
func (*AudioSamplingContent) ToMessageContent ¶ added in v1.2.0
func (a *AudioSamplingContent) ToMessageContent() SamplingMessageContent
ToMessageContent converts AudioSamplingContent to a SamplingMessageContent. This method implements the SamplingContentHandler interface for audio content, transforming the internal representation into the standardized message content format.
Returns:
- A SamplingMessageContent object configured for audio content
func (*AudioSamplingContent) Validate ¶ added in v1.2.0
func (a *AudioSamplingContent) Validate() error
Validate ensures the audio content is valid. This method checks that the audio content meets the necessary requirements, including non-empty data and MIME type.
Returns:
- nil if the content is valid
- An error explaining the validation failure otherwise
type ClientInfo ¶ added in v1.2.0
type ClientInfo struct {
SamplingSupported bool
SamplingCaps SamplingCapabilities
ProtocolVersion string
}
ClientInfo represents information about a connected client
type ClientSession ¶
type ClientSession struct {
ID SessionID // Unique session identifier
ClientInfo ClientInfo // Information about the client
Created time.Time // When the session was created
LastActive time.Time // Last time the session was active
ProtocolVersion string // Negotiated protocol version
Metadata map[string]string // Additional session metadata
}
ClientSession represents a session with a client. It encapsulates all client-specific information including capabilities, negotiated protocol version, and session metadata needed for managing the client connection lifecycle.
type ContentItem ¶ added in v1.2.0
type ContentItem struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ImageURL string `json:"imageUrl,omitempty"`
AltText string `json:"altText,omitempty"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
Data interface{} `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Filename string `json:"filename,omitempty"`
Blob string `json:"blob,omitempty"` // Add blob support for MCP Inspector validation
}
ContentItem represents a single content item in a response. In the MCP protocol, responses are structured as collections of typed content items, allowing for rich, multimodal responses that can include text, images, links, files, JSON data, and binary blobs with appropriate metadata.
func BlobContent ¶ added in v1.2.0
func BlobContent(blob string, mimeType string) ContentItem
BlobContent creates a new blob content item.
func FileContent ¶ added in v1.2.0
func FileContent(fileURL string, filename string, mimeType string) ContentItem
FileContent creates a content item of type "file"
func ImageContent ¶ added in v1.2.0
func ImageContent(imageURL string, altText string, optMimeType ...string) ContentItem
ImageContent creates a new image content item. This function creates a properly formatted image content item for inclusion in MCP responses.
Parameters:
- imageURL: The URL where the image can be accessed
- altText: Accessibility description of the image content
- optMimeType: Optional MIME type of the image (e.g., "image/png")
Returns:
- A ContentItem of type "image" properly formatted for the MCP protocol
func JSONContent ¶ added in v1.2.0
func JSONContent(data interface{}) ContentItem
JSONContent creates a content item of type "json"
func LinkContent ¶ added in v1.2.0
func LinkContent(url, title string) ContentItem
LinkContent creates a new link content item. This function creates a properly formatted link content item for inclusion in MCP responses.
Parameters:
- url: The target URL of the link
- title: The display text or title for the link
Returns:
- A ContentItem of type "link" properly formatted for the MCP protocol
func TextContent ¶ added in v1.2.0
func TextContent(text string) ContentItem
TextContent creates a new text content item. This function creates a properly formatted text content item for inclusion in MCP responses, handling edge cases like empty text to ensure protocol compliance.
Parameters:
- text: The text content to include in the response
Returns:
- A ContentItem of type "text" properly formatted for the MCP protocol
type ContentType ¶ added in v1.2.0
type ContentType string
ContentType represents the type of content in a prompt message. Different content types have different required fields and rendering behaviors.
const ( // ContentTypeText is used for plain text content ContentTypeText ContentType = "text" // ContentTypeImage is used for image content, which requires an imageUrl ContentTypeImage ContentType = "image" // ContentTypeAudio is used for audio content, which requires audio data ContentTypeAudio ContentType = "audio" // ContentTypeResource is used for referencing resources by URI ContentTypeResource ContentType = "resource" )
Content type constants define the supported content types for prompts.
type Context ¶ added in v0.1.11
type Context struct {
// The raw request bytes
RequestBytes []byte
// The parsed request
Request *Request
// The response to be sent back
Response *Response
// Logger for this request
Logger *slog.Logger
// Version of the MCP protocol being used
Version string
// Request ID for tracing
RequestID string
// Metadata for storing contextual information during request processing
Metadata map[string]interface{}
// contains filtered or unexported fields
}
Context represents the execution context for a server request. It encapsulates all request-specific information including request data, response data, server reference, and metadata for tracking the request. Context objects are created for each incoming client request and provide access to server functionality through convenience methods.
func NewContext ¶ added in v0.1.11
NewContext creates a new request context for processing an incoming request. It parses the request bytes, initializes response structures, and extracts method-specific parameters based on the request method. This function is called for each incoming message to create a self-contained context for request processing.
Parameters:
- ctx: Standard Go context for cancellation and timeouts
- requestBytes: Raw JSON-RPC request bytes
- server: Reference to the server implementation
Returns:
- A new Context object ready for request processing
- An error if request parsing fails
func (*Context) Deadline ¶ added in v1.2.0
Deadline returns the time when this context will be canceled, if any. This method implements part of the standard Go context.Context interface.
func (*Context) Done ¶ added in v1.1.2
func (c *Context) Done() <-chan struct{}
Done returns a channel that's closed when this context is canceled. This method implements part of the standard Go context.Context interface, allowing the Context to be used with functions expecting a cancellable context.
func (*Context) Err ¶ added in v1.2.0
Err returns nil if Done is not yet closed, otherwise it returns the reason. This method implements part of the standard Go context.Context interface.
func (*Context) ExecuteResource ¶ added in v1.2.0
ExecuteResource provides a convenient way to execute a resource from within another resource handler. This is useful for resource composition and internal resource calls, allowing one resource to build upon another or reuse existing resource handlers. The method handles path matching, parameter extraction, and result formatting.
Parameters:
- resourcePath: The path of the resource to execute
Returns:
- The result of the resource execution
- An error if the resource cannot be found or execution fails
func (*Context) ExecuteTool ¶ added in v1.2.0
ExecuteTool provides a convenient way to execute a tool from within another tool handler. This is useful for tool composition and internal tool calls when one tool needs to invoke another as part of its implementation. The method handles parameter validation and result formatting automatically.
Parameters:
- toolName: The name of the tool to execute
- args: A map of argument values to pass to the tool
Returns:
- The result of the tool execution
- An error if the tool cannot be found or execution fails
func (*Context) GetRegisteredResources ¶ added in v1.2.0
GetRegisteredResources returns a list of all resources registered with the server. This is useful for handlers that need to inspect or enumerate available resources, such as implementing a custom resources/list endpoint or providing resource discovery functionality.
Returns:
- A slice of Resource objects containing all registered resources
- An error if the server reference is not available
func (*Context) GetRegisteredTools ¶ added in v1.2.0
GetRegisteredTools returns a list of all tools registered with the server. This is useful for tools that need to inspect or enumerate available tools, such as implementing a custom tools/list endpoint or providing tool discovery functionality.
Returns:
- A slice of Tool objects containing all registered tools
- An error if the server reference is not available
func (*Context) GetResourceDetails ¶ added in v1.2.0
GetResourceDetails returns detailed information about a specific resource. This is useful for handlers that need to inspect the capabilities of other resources, validate resource availability, or provide detailed resource information to clients. The method supports both exact path matching and template pattern matching.
Parameters:
- resourcePath: The path of the resource to retrieve details for
Returns:
- A Resource object containing the resource's metadata and handler
- An error if the resource doesn't exist or the server reference is not available
func (*Context) GetSamplingController ¶ added in v1.2.0
func (c *Context) GetSamplingController() (*SamplingController, error)
GetSamplingController provides access to the server's sampling controller. The sampling controller manages rate limiting, request tracking, and other aspects of the server's sampling behavior. This method is used by sampling-related functions to access the controller for validation and configuration.
Returns:
- A pointer to the server's SamplingController
- An error if the server reference is not available or the controller is not initialized
func (*Context) GetToolDetails ¶ added in v1.2.0
GetToolDetails returns detailed information about a specific tool. This is useful for tools that need to inspect the capabilities of other tools, validate tool availability before executing, or provide detailed tool information to clients.
Parameters:
- toolName: The name of the tool to retrieve details for
Returns:
- A Tool object containing the tool's metadata and handler
- An error if the tool doesn't exist or the server reference is not available
func (*Context) RequestSampling ¶ added in v1.2.0
func (c *Context) RequestSampling(messages []SamplingMessage, preferences SamplingModelPreferences, systemPrompt string, maxTokens int) (*SamplingResponse, error)
RequestSampling sends a sampling request using the context's session information. This is a convenience wrapper around the server's RequestSamplingFromContext method, which automatically uses the current context's session, protocol version, and other metadata when making the sampling request.
Parameters:
- messages: A slice of SamplingMessage objects representing the conversation
- preferences: Model preferences for the sampling request
- systemPrompt: Optional system prompt to help guide the model's behavior
- maxTokens: Maximum number of tokens to generate in the response
Returns:
- A SamplingResponse containing the model's generated content
- An error if the sampling request fails or the server is not available
func (*Context) RequestSamplingWithPriority ¶ added in v1.2.0
func (c *Context) RequestSamplingWithPriority(messages []SamplingMessage, preferences SamplingModelPreferences, systemPrompt string, maxTokens int, priority int) (*SamplingResponse, error)
RequestSamplingWithPriority sends a sampling request with a specific priority level. The priority affects timeout and retry behavior according to the server's configuration. Higher priority levels typically get more generous timeout and retry settings, while lower priority requests might have shorter timeouts and fewer retries.
Parameters:
- messages: A slice of SamplingMessage objects representing the conversation
- preferences: Model preferences for the sampling request
- systemPrompt: Optional system prompt to help guide the model's behavior
- maxTokens: Maximum number of tokens to generate in the response
- priority: Priority level that determines timeout and retry behavior
Returns:
- A SamplingResponse containing the model's generated content
- An error if the sampling request fails, times out, or the server is not available
func (*Context) ValidateSamplingRequest ¶ added in v1.2.0
func (c *Context) ValidateSamplingRequest(messages []SamplingMessage, maxTokens int) error
ValidateSamplingRequest validates that a sampling request is valid for the current protocol version and client capabilities. It checks that the message content types are supported in the negotiated protocol version and that the requested token count is within acceptable limits.
Parameters:
- messages: A slice of SamplingMessage objects to validate
- maxTokens: The requested maximum token count for the response
Returns:
- An error if validation fails, describing the specific validation error
- nil if validation passes
type FileResource ¶ added in v1.2.0
FileResource represents a file resource
func (FileResource) ToResourceResponse ¶ added in v1.2.0
func (fr FileResource) ToResourceResponse() map[string]interface{}
ToResourceResponse converts FileResource to ResourceResponse
type ImageResource ¶ added in v1.2.0
ImageResource represents an image resource
func (ImageResource) ToResourceResponse ¶ added in v1.2.0
func (ir ImageResource) ToResourceResponse() map[string]interface{}
ToResourceResponse converts ImageResource to ResourceResponse
type ImageSamplingContent ¶ added in v1.2.0
ImageSamplingContent creates an image content struct for sampling messages. This implementation of SamplingContentHandler manages image content for sampling conversations, storing the image data and its MIME type.
func (*ImageSamplingContent) ToMessageContent ¶ added in v1.2.0
func (i *ImageSamplingContent) ToMessageContent() SamplingMessageContent
ToMessageContent converts ImageSamplingContent to a SamplingMessageContent. This method implements the SamplingContentHandler interface for image content, transforming the internal representation into the standardized message content format.
Returns:
- A SamplingMessageContent object configured for image content
func (*ImageSamplingContent) Validate ¶ added in v1.2.0
func (i *ImageSamplingContent) Validate() error
Validate ensures the image content is valid. This method checks that the image content meets the necessary requirements, including non-empty data and MIME type.
Returns:
- nil if the content is valid
- An error explaining the validation failure otherwise
type InvalidParametersError ¶ added in v1.2.0
type InvalidParametersError struct {
// Message contains the error description
Message string
}
InvalidParametersError represents an error with invalid parameters for prompt rendering or template variable substitution.
func NewInvalidParametersError ¶ added in v1.2.0
func NewInvalidParametersError(message string) *InvalidParametersError
NewInvalidParametersError creates a new InvalidParametersError with the given message. This is used when prompt parameters are missing or invalid.
func (*InvalidParametersError) Error ¶ added in v1.2.0
func (e *InvalidParametersError) Error() string
Error returns the error message string. This method implements the error interface.
type JSONResource ¶ added in v1.2.0
type JSONResource struct {
Data interface{}
}
JSONResource represents a JSON resource
func (JSONResource) ToResourceResponse ¶ added in v1.2.0
func (jr JSONResource) ToResourceResponse() map[string]interface{}
ToResourceResponse converts JSONResource to ResourceResponse
type LinkResource ¶ added in v1.2.0
LinkResource represents a link resource
func (LinkResource) ToResourceResponse ¶ added in v1.2.0
func (lr LinkResource) ToResourceResponse() map[string]interface{}
ToResourceResponse converts LinkResource to ResourceResponse
type Option ¶ added in v1.2.0
type Option func(*serverImpl)
Option represents a server configuration option. Server options are used to customize the behavior and configuration of a server instance when it is created with NewServer.
func WithLogger ¶ added in v1.0.1
WithLogger sets the server's logger.
This option configures the structured logger used by the server for logging events, errors, and debug information.
Example:
jsonHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
})
logger := slog.New(jsonHandler)
server := server.NewServer("my-service",
server.WithLogger(logger),
)
func WithSamplingConfig ¶ added in v1.2.0
func WithSamplingConfig(config *SamplingConfig) Option
WithSamplingConfig returns a server option that sets the sampling configuration. This function generates a server configuration option that can be passed to NewServer or ServerBuilder to customize sampling behavior.
Parameters:
- config: The sampling configuration to apply to the server
Returns:
- An Option function that configures sampling when applied to a server
type Prompt ¶ added in v1.2.0
type Prompt struct {
// Name is the unique identifier for this prompt
Name string
// Description explains what the prompt is for
Description string
// Templates are the ordered sequence of message templates that make up the prompt
Templates []PromptTemplate
// Arguments are the parameters that can be passed when rendering the prompt
Arguments []PromptArgument
}
Prompt represents a prompt registered with the server. A prompt is a named collection of templates that can be rendered with provided variable values.
type PromptArgument ¶ added in v1.2.0
type PromptArgument struct {
// Name is the identifier for the argument, matching {{name}} in templates
Name string `json:"name"`
// Description explains what the argument is for
Description string `json:"description"`
// Required indicates whether the argument must be provided
Required bool `json:"required"`
}
PromptArgument represents an argument for a prompt. Arguments are defined by variable names in prompt templates.
type PromptContent ¶ added in v1.2.0
type PromptContent struct {
// Type specifies the kind of content (text, image, audio, resource)
Type ContentType `json:"type"`
// Text contains the text content when Type is ContentTypeText
Text string `json:"text,omitempty"`
// Data contains binary data encoded as base64 for non-text content
Data string `json:"data,omitempty"`
// MimeType specifies the format of the Data field
MimeType string `json:"mimeType,omitempty"`
// Resource contains resource reference information when Type is ContentTypeResource
Resource map[string]interface{} `json:"resource,omitempty"`
}
PromptContent represents the content of a prompt message. It defines a block of content with a specific type and associated data.
type PromptTemplate ¶ added in v1.2.0
type PromptTemplate struct {
// Role defines who is speaking in this template (system, user, assistant)
Role string
// Content contains the template text with variables in {{variable}} format
Content string
// Variables holds the variable names extracted from the Content
Variables []string
}
PromptTemplate represents a template for a prompt with a role and content. Templates can contain variables in the format {{variable}} which are substituted when the prompt is rendered.
func Assistant ¶ added in v0.1.11
func Assistant(content string) PromptTemplate
Assistant creates an assistant prompt template. Assistant prompts represent previous or example responses from the language model.
func System ¶ added in v0.1.11
func System(content string) PromptTemplate
System creates a system prompt template. System prompts provide context or instructions to the language model.
func User ¶ added in v0.1.11
func User(content string) PromptTemplate
User creates a user prompt template. User prompts represent messages from the user to the language model.
type ProtocolSamplingConfig ¶ added in v1.2.0
type ProtocolSamplingConfig struct {
MaxTokens int
SupportedContentTypes map[string]bool
StreamingSupported bool
}
ProtocolSamplingConfig defines protocol-specific sampling configuration. Different protocol versions have different capabilities and constraints, and this structure captures those version-specific settings.
type RPCError ¶ added in v1.2.0
type RPCError struct {
Code int `json:"code"` // Error code
Message string `json:"message"` // Error message
Data interface{} `json:"data,omitempty"`
}
RPCError represents a JSON-RPC 2.0 error object. It includes a numeric error code, a human-readable message, and optional additional data. Error codes follow the JSON-RPC 2.0 specification: -32700 for parse errors, -32600 for invalid requests, -32601 for method not found, -32602 for invalid params, and -32603 for internal errors.
type Request ¶ added in v1.2.0
type Request struct {
// JSON-RPC 2.0 fields
JSONRPC string `json:"jsonrpc"`
ID interface{} `json:"id,omitempty"` // string or number or null
Method string `json:"method"` // The method to call
Params json.RawMessage `json:"params,omitempty"` // Parameters for the method call
// Parsed params based on method type
// These fields are populated after parsing
ToolName string
ToolArgs map[string]interface{}
ResourcePath string
PromptName string
PromptArgs map[string]interface{}
}
Request represents an incoming JSON-RPC 2.0 request. It contains both the raw JSON-RPC fields and parsed method-specific fields which are populated during request processing based on the method type. The struct combines generic JSON-RPC structure with MCP-specific fields to avoid multiple parsing steps.
type RequestSamplingOptions ¶ added in v1.2.0
type RequestSamplingOptions struct {
Timeout time.Duration // Maximum time to wait for a response
MaxRetries int // Maximum number of retry attempts on timeout
RetryInterval time.Duration // Time to wait between retries
IgnoreCapability bool // Whether to ignore client capability validation
ForceSession bool // Whether to force using the specified session
}
RequestSamplingOptions defines options for sampling requests. This struct configures the behavior of sampling requests, including timeouts, retry behavior, and capability validation requirements.
func DefaultSamplingOptions ¶ added in v1.2.0
func DefaultSamplingOptions() RequestSamplingOptions
DefaultSamplingOptions returns the default options for sampling requests. This function provides a standard configuration for timeout and retry behavior that is suitable for most sampling operations.
Returns:
- A RequestSamplingOptions struct with sensible default values
type Resource ¶ added in v1.2.0
type Resource struct {
// Path is the URL pattern for accessing this resource
Path string
// Description explains what the resource provides
Description string
// Handler is the function that executes when the resource is accessed
Handler ResourceHandler
// Schema defines the expected format of the resource data
Schema interface{}
// Template is the parsed path template used for matching URLs
Template *wilduri.Template
// IsTemplate indicates whether this resource path contains parameters
IsTemplate bool // Whether this resource is a template with parameters
}
Resource represents a resource registered with the server. Resources are endpoints that clients can access to retrieve structured data.
type ResourceConverter ¶ added in v1.2.0
type ResourceConverter interface {
ToResourceResponse() map[string]interface{}
}
ResourceConverter allows custom types to be converted to resource responses
type ResourceHandler ¶ added in v1.2.0
ResourceHandler is a function that handles resource requests. It receives a context with the request information and arguments, and returns a result and any error that occurred.
func ConvertToResourceHandler ¶ added in v1.2.0
func ConvertToResourceHandler(handler interface{}) (ResourceHandler, bool)
ConvertToResourceHandler converts a function to a ResourceHandler if possible. It uses reflection to validate the function signature and creates a wrapper that adapts the function to the ResourceHandler interface. Returns the converted handler and a boolean indicating success.
type ResourceResponse ¶ added in v1.2.0
type ResourceResponse struct {
Content []ContentItem `json:"content"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
IsError bool `json:"isError,omitempty"`
}
ResourceResponse is a standard response for MCP resources. It ensures the response format follows the MCP protocol.
func NewResourceResponse ¶ added in v1.2.0
func NewResourceResponse(items ...ContentItem) ResourceResponse
NewResourceResponse creates a new resource response with the given content items.
func (ResourceResponse) AsError ¶ added in v1.2.0
func (r ResourceResponse) AsError() ResourceResponse
AsError marks the response as an error.
func (ResourceResponse) WithMetadata ¶ added in v1.2.0
func (r ResourceResponse) WithMetadata(metadata map[string]interface{}) ResourceResponse
WithMetadata adds metadata to the resource response.
type Response ¶ added in v1.2.0
type Response struct {
// JSON-RPC 2.0 fields
JSONRPC string `json:"jsonrpc"`
ID interface{} `json:"id,omitempty"` // Must match request ID
Result interface{} `json:"result,omitempty"` // Result data, null if error
Error *RPCError `json:"error,omitempty"` // Error data, null if success
}
Response represents an outgoing JSON-RPC 2.0 response. It follows the JSON-RPC 2.0 specification with a result field for successful responses and an error field for failed ones. The ID field must match the corresponding request ID to allow clients to correlate responses with their requests.
type SamplingCapabilities ¶ added in v1.2.0
type SamplingCapabilities struct {
Supported bool
TextSupport bool
ImageSupport bool
AudioSupport bool
}
SamplingCapabilities defines what sampling features a client supports
func DetectClientCapabilities ¶ added in v1.2.0
func DetectClientCapabilities(protocolVersion string) SamplingCapabilities
DetectClientCapabilities infers client capabilities from the protocol version. This function analyzes the protocol version to determine which features and content types the client is likely to support, particularly for sampling operations.
Parameters:
- protocolVersion: The MCP protocol version negotiated with the client
Returns:
- A SamplingCapabilities struct describing the client's supported features
type SamplingConfig ¶ added in v1.2.0
type SamplingConfig struct {
// Rate limiting settings
MaxRequestsPerMinute int // Maximum number of sampling requests per minute
MaxConcurrentRequests int // Maximum number of concurrent sampling requests
MaxTokensPerRequest int // Maximum tokens allowed per request
PerClientRateLimit bool // Whether to apply rate limits per client
// Timeout settings
DefaultTimeout time.Duration // Default timeout for sampling requests
MaxTimeout time.Duration // Maximum allowed timeout for sampling requests
// Retry settings
DefaultMaxRetries int // Default number of retries for failed requests
DefaultRetryInterval time.Duration // Default interval between retries
// Priority settings
EnablePrioritization bool // Whether to enable request prioritization
DefaultPriority int // Default priority for sampling requests (1-10, 10 being highest)
// Resource allocation
ResourceQuota map[string]int // Resource quotas for different content types
// Error handling
GracefulDegradation bool // Whether to enable graceful degradation on errors
// Protocol-specific settings
ProtocolDefaults map[string]*ProtocolSamplingConfig // Protocol-specific settings
}
SamplingConfig defines server-side configuration options for sampling operations. This comprehensive configuration structure controls all aspects of sampling behavior, including rate limiting, timeouts, retry policies, prioritization, and protocol-specific settings.
func NewDefaultSamplingConfig ¶ added in v1.2.0
func NewDefaultSamplingConfig() *SamplingConfig
NewDefaultSamplingConfig creates a new sampling configuration with sensible defaults. This function provides a pre-configured SamplingConfig with reasonable values for all settings, suitable for most server deployments without customization.
Returns:
- A pointer to a new SamplingConfig struct with default values
type SamplingContentHandler ¶ added in v1.2.0
type SamplingContentHandler interface {
ToMessageContent() SamplingMessageContent
Validate() error
}
SamplingContentHandler is the interface for all sampling content handlers. This interface defines the contract that all content type implementations must follow, allowing for consistent handling of different content types (text, image, audio) in the sampling system.
type SamplingController ¶ added in v1.2.0
type SamplingController struct {
// contains filtered or unexported fields
}
SamplingController manages sampling operations with rate limiting and prioritization. This component enforces rate limits, tracks request statistics, manages prioritization, and validates requests against protocol-specific constraints to ensure reliable and fair resource allocation for sampling operations.
func NewSamplingController ¶ added in v1.2.0
func NewSamplingController(config *SamplingConfig, logger *slog.Logger) *SamplingController
NewSamplingController creates a new controller with the specified configuration. This function initializes all components of the sampling controller, including the rate limiter and request tracking system, and starts the background goroutine for periodically resetting rate limits.
Parameters:
- config: The sampling configuration to use (or nil for default configuration)
- logger: A structured logger for recording controller events
Returns:
- A fully initialized SamplingController ready for managing sampling requests
func (*SamplingController) CanProcessRequest ¶ added in v1.2.0
func (sc *SamplingController) CanProcessRequest(sessionID SessionID) bool
CanProcessRequest checks if a sampling request can be processed based on rate limits. This method evaluates both global concurrent request limits and per-client rate limits (if enabled) to determine if a new request should be accepted or rejected.
Parameters:
- sessionID: The client session ID for per-client rate limiting
Returns:
- true if the request can be processed, false if it would exceed rate limits
func (*SamplingController) CompleteRequest ¶ added in v1.2.0
func (sc *SamplingController) CompleteRequest(sessionID SessionID)
CompleteRequest marks a request as completed, updating rate limiting counters. This method decrements the concurrent request counter when a sampling request finishes processing, regardless of whether it succeeded or failed.
Parameters:
- sessionID: The client session ID for the completed request
func (*SamplingController) GetConcurrentRequestCount ¶ added in v1.2.0
func (sc *SamplingController) GetConcurrentRequestCount() int
GetConcurrentRequestCount returns the current number of concurrent requests. This method is useful for monitoring and debugging the server's sampling workload.
Returns:
- The current count of active sampling requests being processed
func (*SamplingController) GetRequestOptions ¶ added in v1.2.0
func (sc *SamplingController) GetRequestOptions(priority int) RequestSamplingOptions
GetRequestOptions returns appropriate request options based on configuration. This method calculates timeout and retry parameters for a sampling request based on its priority level, applying adjustments according to the controller's configuration and prioritization settings.
Parameters:
- priority: The priority level of the request (1-10, with 10 being highest)
Returns:
- RequestSamplingOptions containing configured timeout and retry settings
func (*SamplingController) RecordRequest ¶ added in v1.2.0
func (sc *SamplingController) RecordRequest(sessionID SessionID)
RecordRequest records a sampling request for rate limiting purposes. This method updates the concurrent request counter and per-client request counter (if enabled) when a new sampling request begins processing.
Parameters:
- sessionID: The client session ID for per-client rate tracking
func (*SamplingController) Stop ¶ added in v1.2.0
func (sc *SamplingController) Stop()
Stop stops the sampling controller and cleans up resources. This method should be called when shutting down the server to ensure proper cleanup of background goroutines and other resources.
func (*SamplingController) ValidateForProtocol ¶ added in v1.2.0
func (sc *SamplingController) ValidateForProtocol(protocol string, messages []SamplingMessage, maxTokens int) error
ValidateForProtocol validates sampling parameters against protocol constraints. This method checks that a sampling request conforms to the limitations of the specified protocol version, including token count limits and supported content types.
Parameters:
- protocol: The protocol version to validate against
- messages: The conversation messages to validate
- maxTokens: The requested maximum token count
Returns:
- nil if valid, or an error describing the validation failure
type SamplingCreateMessageParams ¶ added in v1.2.0
type SamplingCreateMessageParams struct {
Messages []SamplingMessage `json:"messages"`
ModelPreferences SamplingModelPreferences `json:"modelPreferences"`
SystemPrompt string `json:"systemPrompt,omitempty"`
MaxTokens int `json:"maxTokens,omitempty"`
}
SamplingCreateMessageParams represents the parameters for a sampling/createMessage request. This struct contains all the information needed to make a complete sampling request to the client, including the conversation history, model preferences, system prompt, and token limits.
type SamplingMessage ¶ added in v1.2.0
type SamplingMessage struct {
Role string `json:"role"`
Content SamplingMessageContent `json:"content"`
}
SamplingMessage represents a message in a sampling conversation. This struct encapsulates a single message exchange between a user and an assistant, including the role of the speaker and the content of the message.
func CreateAudioSamplingMessage ¶ added in v1.2.0
func CreateAudioSamplingMessage(role, audioData, mimeType string) SamplingMessage
CreateAudioSamplingMessage creates a sampling message with audio content.
func CreateImageSamplingMessage ¶ added in v1.2.0
func CreateImageSamplingMessage(role, imageData, mimeType string) SamplingMessage
CreateImageSamplingMessage creates a sampling message with image content.
func CreateSamplingMessage ¶ added in v1.2.0
func CreateSamplingMessage(role string, content SamplingContentHandler) (SamplingMessage, error)
CreateSamplingMessage creates a sampling message with the provided content handler. This is a helper function for constructing properly formatted and validated sampling messages for different content types.
Parameters:
- role: The role of the message sender (e.g., "user", "assistant")
- content: The content handler implementation for the specific content type
Returns:
- A properly formatted SamplingMessage
- An error if content validation fails
func CreateTextSamplingMessage ¶ added in v1.2.0
func CreateTextSamplingMessage(role, text string) SamplingMessage
CreateTextSamplingMessage creates a sampling message with text content.
type SamplingMessageContent ¶ added in v1.2.0
type SamplingMessageContent struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
SamplingMessageContent represents the content of a sampling message. It contains the type of content (text, image, etc.) and associated data, allowing for multimodal message exchanges in sampling conversations.
func (*SamplingMessageContent) IsValidForVersion ¶ added in v1.2.0
func (c *SamplingMessageContent) IsValidForVersion(version string) bool
IsValidForVersion checks if the content type is valid for the given protocol version. Different protocol versions support different content types, and this method validates whether the current content type is supported in the specified version.
Parameters:
- version: The protocol version to check against
Returns:
- true if the content type is supported in the specified version, false otherwise
type SamplingModelHint ¶ added in v1.2.0
type SamplingModelHint struct {
Name string `json:"name"`
}
SamplingModelHint represents a hint for model selection in sampling requests. Hints provide optional guidance to the client about which AI models might be appropriate for handling a particular sampling request.
type SamplingModelPreferences ¶ added in v1.2.0
type SamplingModelPreferences struct {
Hints []SamplingModelHint `json:"hints,omitempty"`
CostPriority *float64 `json:"costPriority,omitempty"`
SpeedPriority *float64 `json:"speedPriority,omitempty"`
IntelligencePriority *float64 `json:"intelligencePriority,omitempty"`
}
SamplingModelPreferences represents the model preferences for a sampling request. These preferences allow the server to communicate desired characteristics for the AI model that will handle the sampling request, such as optimizing for cost, speed, or intelligence.
type SamplingResponse ¶ added in v1.2.0
type SamplingResponse struct {
Role string `json:"role"`
Content SamplingMessageContent `json:"content"`
Model string `json:"model,omitempty"`
StopReason string `json:"stopReason,omitempty"`
}
SamplingResponse represents the response to a sampling/createMessage request. It contains the AI-generated response content, the role of the responder (typically "assistant"), optional model identification, and information about why the response ended.
type Server ¶
type Server interface {
// Run starts the server and blocks until it exits.
//
// This method initializes the server, starts listening for connections,
// and processes incoming requests. It blocks until the server encounters
// an error or is explicitly stopped.
//
// Example:
// if err := server.Run(); err != nil {
// log.Fatalf("Server error: %v", err)
// }
Run() error
// Tool registers a tool with the server.
//
// The name parameter is the unique identifier for the tool. The description
// parameter provides human-readable documentation. The handler parameter is
// a function that implements the tool's logic.
//
// Tool handlers can have one of the following signatures:
// func(ctx *Context) (interface{}, error)
// func(ctx *Context, args T) (interface{}, error)
// func(ctx *Context) error
// func(ctx *Context, args T) error
//
// Where T is any struct type that can be unmarshaled from JSON. The struct
// fields should use `json` tags to map to JSON property names.
//
// Example:
// server.Tool("add", "Add two numbers", func(ctx *server.Context, args struct {
// X float64 `json:"x" required:"true"`
// Y float64 `json:"y" required:"true"`
// }) (float64, error) {
// return args.X + args.Y, nil
// })
Tool(name string, description string, handler interface{}) Server
// WithAnnotations adds annotations to a tool.
//
// Annotations provide additional metadata about a tool, such as examples,
// parameter descriptions, or usage notes.
//
// Example:
// server.Tool("greet", "Greet a user", greetHandler).
// WithAnnotations("greet", map[string]interface{}{
// "examples": []map[string]interface{}{
// {
// "description": "Greet a user by name",
// "args": map[string]interface{}{
// "name": "Alice",
// },
// },
// },
// })
WithAnnotations(toolName string, annotations map[string]interface{}) Server
// Resource registers a resource with the server.
//
// The path parameter defines the resource path, which can include path
// parameters in the format {paramName}. The description parameter provides
// human-readable documentation. The handler parameter is a function that
// implements the resource's logic.
//
// Example:
// server.Resource("/users/{id}", "Get user information", func(ctx *server.Context, params struct {
// ID string `path:"id"`
// }) (interface{}, error) {
// return getUserById(params.ID)
// })
Resource(path string, description string, handler interface{}) Server
// Prompt registers a prompt with the server.
//
// The name parameter is the unique identifier for the prompt. The description
// parameter provides human-readable documentation. The template parameters
// define the prompt template and can be either a string or a function that
// generates the template.
//
// Example:
// server.Prompt("greeting", "Greeting template",
// "Hello, {{name}}! Welcome to {{service}}.")
Prompt(name string, description string, template ...interface{}) Server
// Root sets the allowed root paths.
//
// Root paths are the entry points for resource navigation. At least one
// root path must be defined for resources to be accessible.
//
// Example:
// server.Root("/api/v1", "/api/v2")
Root(paths ...string) Server
// AsStdio configures the server to use Standard I/O for communication.
//
// This is useful for child processes or integration with other MCP systems.
// An optional logFile parameter can be provided to redirect stdio logs.
//
// Example:
// server.AsStdio("./mcp-server.log")
AsStdio(logFile ...string) Server
// AsWebsocket configures the server to use WebSocket for communication.
//
// The address parameter specifies the host and port to listen on.
//
// Example:
// server.AsWebsocket("localhost:8080")
AsWebsocket(address string) Server
// AsWebsocketWithPaths configures the server to use WebSocket for communication with custom paths.
//
// Example:
//
// server.AsWebsocketWithPaths("localhost:8080", "/api/v1", "/socket")
AsWebsocketWithPaths(address, pathPrefix, wsPath string) Server
// AsSSE configures the server to use Server-Sent Events for communication.
//
// The address parameter specifies the host and port to listen on.
//
// Example:
// server.AsSSE("localhost:8080")
AsSSE(address string) Server
// AsHTTP configures the server to use HTTP for communication.
//
// The address parameter specifies the host and port to listen on.
//
// Example:
// server.AsHTTP("localhost:8080")
AsHTTP(address string) Server
// AsHTTPWithPaths configures the server to use HTTP for communication with custom paths.
//
// Example:
//
// server.AsHTTPWithPaths("localhost:8080", "/api/v1", "/rpc")
AsHTTPWithPaths(address, pathPrefix, apiPath string) Server
// AsUnixSocket configures the server to use Unix Domain Sockets for communication.
//
// Unix Domain Sockets provide high-performance inter-process communication for
// processes running on the same machine.
//
// Example:
//
// server.AsUnixSocket("/tmp/mcp.sock")
// // With options:
// server.AsUnixSocket("/tmp/mcp.sock", unix.WithPermissions(0600))
AsUnixSocket(socketPath string, options ...unix.UnixSocketOption) Server
// AsUDP configures the server to use UDP for communication.
//
// UDP provides low-latency communication with minimal overhead,
// suitable for high-throughput scenarios where occasional packet
// loss is acceptable.
//
// Example:
//
// server.AsUDP(":8080")
// // With options:
// server.AsUDP(":8080", udp.WithMaxPacketSize(2048))
AsUDP(address string, options ...udp.UDPOption) Server
// AsMQTT configures the server to use MQTT for communication
// with optional configuration options.
//
// MQTT provides a publish/subscribe-based communication model,
// suitable for IoT applications and distributed systems with
// potentially intermittent connectivity.
//
// Example:
//
// server.AsMQTT("tcp://broker.example.com:1883")
// // With options:
// server.AsMQTT("tcp://broker.example.com:1883",
// mqtt.WithQoS(1),
// mqtt.WithCredentials("username", "password"),
// mqtt.WithTopicPrefix("custom/topic/prefix"))
AsMQTT(brokerURL string, options ...mqtt.MQTTOption) Server
// AsMQTTWithClientID configures the server to use MQTT with a specific client ID
// along with optional configuration options.
//
// This is useful when you need to control the client ID to implement
// features like persistent sessions or shared subscriptions.
//
// Example:
//
// server.AsMQTTWithClientID("tcp://broker.example.com:1883", "mcp-server-1")
// // With options:
// server.AsMQTTWithClientID("tcp://broker.example.com:1883", "mcp-server-1",
// mqtt.WithQoS(2),
// mqtt.WithTopicPrefix("my-org/mcp"))
AsMQTTWithClientID(brokerURL string, clientID string, options ...mqtt.MQTTOption) Server
// AsMQTTWithTLS configures the server to use MQTT with TLS security
// along with optional configuration options.
//
// This is recommended for production environments to encrypt
// communications between the server and the MQTT broker.
//
// Example:
//
// server.AsMQTTWithTLS("ssl://broker.example.com:8883",
// mqtt.TLSConfig{
// CertFile: "/path/to/cert.pem",
// KeyFile: "/path/to/key.pem",
// CAFile: "/path/to/ca.pem",
// })
AsMQTTWithTLS(brokerURL string, tlsConfig mqtt.TLSConfig, options ...mqtt.MQTTOption) Server
// AsNATS configures the server to use NATS for communication
// with optional configuration options.
//
// NATS provides a high-performance, cloud native communication system,
// suitable for microservices architectures, IoT messaging, and
// event-driven applications.
//
// Example:
//
// server.AsNATS("nats://localhost:4222")
// // With options:
// server.AsNATS("nats://localhost:4222",
// nats.WithCredentials("username", "password"),
// nats.WithSubjectPrefix("custom/subject/prefix"))
AsNATS(serverURL string, options ...nats.NATSOption) Server
// AsNATSWithClientID configures the server to use NATS with a specific client ID
// along with optional configuration options.
//
// Example:
//
// server.AsNATSWithClientID("nats://localhost:4222", "mcp-server-1")
// // With options:
// server.AsNATSWithClientID("nats://localhost:4222", "mcp-server-1",
// nats.WithSubjectPrefix("my-org/mcp"))
AsNATSWithClientID(serverURL string, clientID string, options ...nats.NATSOption) Server
// AsNATSWithToken configures the server to use NATS with token authentication
// along with optional configuration options.
//
// Example:
//
// server.AsNATSWithToken("nats://localhost:4222", "s3cr3t-t0k3n")
// // With options:
// server.AsNATSWithToken("nats://localhost:4222", "s3cr3t-t0k3n",
// nats.WithClientID("mcp-server-1"),
// nats.WithSubjectPrefix("my-org/mcp"))
AsNATSWithToken(serverURL string, token string, options ...nats.NATSOption) Server
// GetServer returns the underlying server implementation.
//
// This is primarily used for advanced configuration or testing.
GetServer() *serverImpl
// GetRoots returns the list of registered root paths.
GetRoots() []string
// IsPathInRoots checks if a path is within any registered root.
IsPathInRoots(path string) bool
// WithSamplingConfig sets the sampling configuration for the server.
//
// Sampling configuration controls how sampling requests are handled,
// including rate limits, caching, and other performance parameters.
//
// Example:
// config := server.NewSamplingConfig().WithRateLimit(10)
// server.WithSamplingConfig(config)
WithSamplingConfig(config *SamplingConfig) Server
// WithSamplingController sets a custom sampling controller for the server.
//
// This is an advanced method for applications that need fine-grained
// control over sampling behavior.
WithSamplingController(controller *SamplingController) Server
// Logger returns the server's configured logger.
//
// This can be used to access the logger for custom logging needs.
Logger() *slog.Logger
}
Server represents an MCP server with fluent configuration methods. It provides a builder-style API for configuring all aspects of an MCP server including tools, resources, prompts, and transport options.
func NewServer ¶
NewServer creates a new MCP server with the given name and options.
The server is initialized with default settings that can be customized using the provided options. By default, the server uses stdio transport and default logging configuration.
The name parameter is a human-readable identifier for the server, used in logs and server information.
Example:
// Create a basic server with default settings
server := server.NewServer("my-service")
// Create a server with custom logger and sampling configuration
customLogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
samplingConfig := server.NewSamplingConfig().WithRateLimit(100)
server := server.NewServer("my-service",
server.WithLogger(customLogger),
server.WithSamplingConfig(samplingConfig),
)
type SessionID ¶ added in v1.2.0
type SessionID string
SessionID is a unique identifier for a client session. It's used to track and manage individual client connections to the server.
type SessionManager ¶ added in v1.2.0
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager manages client sessions. It provides methods for creating, retrieving, updating, and closing client sessions, ensuring proper lifecycle management and thread safety.
func NewSessionManager ¶ added in v1.2.0
func NewSessionManager() *SessionManager
NewSessionManager creates a new session manager. It initializes the internal data structures needed for tracking client sessions.
Returns:
- A new SessionManager instance ready for use
func (*SessionManager) CloseSession ¶ added in v1.2.0
func (sm *SessionManager) CloseSession(id SessionID) bool
CloseSession removes a session. This method deletes a client session from the session manager, typically called when a client disconnects or times out.
Parameters:
- id: The unique identifier of the session to close
Returns:
- A boolean indicating whether the session was found and removed
func (*SessionManager) CreateSession ¶ added in v1.2.0
func (sm *SessionManager) CreateSession(clientInfo ClientInfo, protocolVersion string) *ClientSession
CreateSession creates a new client session. This method generates a unique session ID, initializes a new session with the provided client information, and adds it to the session manager.
Parameters:
- clientInfo: Information about the client's capabilities and features
- protocolVersion: The negotiated MCP protocol version for this client
Returns:
- A new ClientSession instance configured for the client
func (*SessionManager) GetSession ¶ added in v1.2.0
func (sm *SessionManager) GetSession(id SessionID) (*ClientSession, bool)
GetSession retrieves a session by ID. This method looks up a client session using its unique identifier.
Parameters:
- id: The unique identifier of the session to retrieve
Returns:
- The ClientSession if found
- A boolean indicating whether the session exists
func (*SessionManager) UpdateClientCapabilities ¶ added in v1.2.0
func (sm *SessionManager) UpdateClientCapabilities(id SessionID, caps SamplingCapabilities) bool
UpdateClientCapabilities updates the capabilities of a client session. This method modifies a session's recorded capabilities, typically called when new information about client support becomes available.
Parameters:
- id: The unique identifier of the session to update
- caps: The new sampling capabilities to set for the client
Returns:
- A boolean indicating whether the session was found and updated
func (*SessionManager) UpdateSession ¶ added in v1.2.0
func (sm *SessionManager) UpdateSession(id SessionID, update func(*ClientSession)) bool
UpdateSession updates an existing session. This method applies custom updates to a session while maintaining thread safety, and automatically updates the session's last active timestamp.
Parameters:
- id: The unique identifier of the session to update
- update: A function that receives the session and applies updates to it
Returns:
- A boolean indicating whether the session was found and updated
type TextResource ¶ added in v1.2.0
type TextResource struct {
Text string
}
TextResource represents a simple text resource
func (TextResource) ToResourceResponse ¶ added in v1.2.0
func (tr TextResource) ToResourceResponse() map[string]interface{}
ToResourceResponse converts TextResource to ResourceResponse
type TextSamplingContent ¶ added in v1.2.0
type TextSamplingContent struct {
Text string
}
TextSamplingContent creates a text content struct for sampling messages. This implementation of SamplingContentHandler manages plain text content for sampling conversations.
func (*TextSamplingContent) ToMessageContent ¶ added in v1.2.0
func (t *TextSamplingContent) ToMessageContent() SamplingMessageContent
ToMessageContent converts TextSamplingContent to a SamplingMessageContent. This method implements the SamplingContentHandler interface for text content, transforming the internal representation into the standardized message content format.
Returns:
- A SamplingMessageContent object configured for text content
func (*TextSamplingContent) Validate ¶ added in v1.2.0
func (t *TextSamplingContent) Validate() error
Validate ensures the text content is valid. This method checks that the text content meets the necessary requirements, specifically that it is not empty.
Returns:
- nil if the content is valid
- An error explaining the validation failure otherwise
type Tool ¶ added in v1.2.0
type Tool struct {
// Name is the unique identifier for the tool
Name string
// Description explains what the tool does
Description string
// Handler is the function that executes when the tool is called
Handler ToolHandler
// Schema defines the expected input format for the tool
Schema interface{}
// Annotations contains additional metadata about the tool
Annotations map[string]interface{}
}
Tool represents a tool registered with the server. Tools are functions that can be called by clients connected to the server.
type ToolHandler ¶ added in v1.2.0
ToolHandler is a function that handles tool calls. It receives a context with request information and arguments, and returns a result and any error that occurred.