client

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

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

This package contains the Client interface and implementation for communicating with MCP services. It enables Go applications to interact with MCP servers through a clean, type-safe API that handles all aspects of the protocol, including version negotiation, connection management, and request/response handling.

Basic Usage

// Create a new client and connect to an MCP server
client, err := client.NewClient("my-client",
	client.WithProtocolVersion("2025-03-26"),
	client.WithLogger(logger),
)
if err != nil {
	log.Fatalf("Failed to connect: %v", err)
}
defer client.Close()

// Call a tool
result, err := client.CallTool("calculate", map[string]interface{}{
	"operation": "add",
	"values": []float64{1.5, 2.5, 3.0},
})

Client Options

The NewClient function accepts various options to customize client behavior:

  • WithProtocolVersion: Set a specific protocol version
  • WithProtocolNegotiation: Enable/disable automatic protocol negotiation
  • WithLogger: Configure a custom logger
  • WithTransport: Specify a custom transport implementation
  • WithRequestTimeout: Set request timeout duration
  • WithConnectionTimeout: Set connection timeout duration
  • WithSamplingOptimizations: Configure sampling performance optimizations

Thread Safety

All Client methods are thread-safe and can be called concurrently from multiple goroutines.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsProtocolVersionSupported added in v1.2.0

func IsProtocolVersionSupported(version string) bool

IsProtocolVersionSupported checks if a given protocol version is supported for sampling

func IsStreamingSupportedForVersionForTest added in v1.2.0

func IsStreamingSupportedForVersionForTest(version string) bool

IsStreamingSupportedForVersionForTest exposes isStreamingSupportedForVersion for testing

func NewDefaultLogger added in v1.2.0

func NewDefaultLogger() *slog.Logger

NewDefaultLogger creates a simple logger suitable for MCP clients

func RegisterSamplingHandler added in v1.2.0

func RegisterSamplingHandler(c Client, handler SamplingHandler)

RegisterSamplingHandler registers a sampling handler on the client

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

func ValidateSamplingResponseForVersionForTest added in v1.2.0

func ValidateSamplingResponseForVersionForTest(response *SamplingResponse, version string) error

ValidateSamplingResponseForVersionForTest exposes validateSamplingResponseForVersion for testing

func ValidateStreamingSamplingResponseForVersionForTest added in v1.2.0

func ValidateStreamingSamplingResponseForVersionForTest(response *StreamingSamplingResponse, version string) error

ValidateStreamingSamplingResponseForVersionForTest exposes validateStreamingSamplingResponseForVersion for testing

Types

type AudioSamplingContent added in v1.2.0

type AudioSamplingContent struct {
	Data     string
	MimeType string
}

AudioSamplingContent creates an audio content struct for sampling messages

func (*AudioSamplingContent) ToMessageContent added in v1.2.0

func (a *AudioSamplingContent) ToMessageContent() SamplingMessageContent

ToMessageContent converts AudioSamplingContent to a SamplingMessageContent

func (*AudioSamplingContent) Validate added in v1.2.0

func (a *AudioSamplingContent) Validate() error

Validate ensures the audio content is valid

type Client

type Client interface {
	// CallTool invokes a tool on the connected MCP server.
	//
	// The name parameter specifies the tool to call. The args parameter contains
	// the arguments to pass to the tool as key-value pairs. The returned interface{}
	// contains the tool's output, which can be any JSON-serializable value.
	//
	// Example:
	//  result, err := client.CallTool("translate", map[string]interface{}{
	//      "text": "Hello world",
	//      "target_language": "Spanish",
	//  })
	CallTool(name string, args map[string]interface{}) (interface{}, error)

	// GetResource retrieves a resource from the server by its path.
	//
	// The path parameter specifies the resource to retrieve. The returned interface{}
	// contains the resource content, which can be any JSON-serializable value.
	//
	// Example:
	//  resource, err := client.GetResource("/users/123")
	GetResource(path string) (interface{}, error)

	// GetPrompt retrieves and renders a prompt from the server.
	//
	// The name parameter specifies the prompt to render. The variables parameter
	// contains the variables to substitute in the prompt template.
	//
	// Example:
	//  prompt, err := client.GetPrompt("greeting", map[string]interface{}{
	//      "name": "Alice",
	//      "time_of_day": "morning",
	//  })
	GetPrompt(name string, variables map[string]interface{}) (interface{}, error)

	// GetRoot retrieves the root resource from the server.
	//
	// This is a convenience method equivalent to calling GetResource("/").
	//
	// Example:
	//  root, err := client.GetRoot()
	GetRoot() (interface{}, error)

	// Close closes the client connection to the server and releases all resources.
	//
	// After calling Close, the client cannot be used for further operations.
	// It is good practice to defer this call after creating a client.
	//
	// Example:
	//  client, err := client.NewClient("my-client")
	//  if err != nil {
	//      log.Fatal(err)
	//  }
	//  defer client.Close()
	Close() error

	// AddRoot registers a new root endpoint with the server.
	//
	// The uri parameter specifies the path of the root. The name parameter
	// provides a human-readable name for the root.
	//
	// Example:
	//  err := client.AddRoot("/api/v2", "API Version 2")
	AddRoot(uri string, name string) error

	// RemoveRoot unregisters a root endpoint from the server.
	//
	// The uri parameter specifies the path of the root to remove.
	//
	// Example:
	//  err := client.RemoveRoot("/api/v1")
	RemoveRoot(uri string) error

	// GetRoots retrieves the list of root endpoints from the server.
	//
	// The returned slice contains all registered roots with their URIs and names.
	//
	// Example:
	//  roots, err := client.GetRoots()
	//  for _, root := range roots {
	//      fmt.Printf("Root: %s (%s)\n", root.URI, root.Name)
	//  }
	GetRoots() ([]Root, error)

	// Version returns the negotiated protocol version with the server.
	//
	// This returns one of the standardized version strings: "draft", "2024-11-05",
	// or "2025-03-26".
	//
	// Example:
	//  version := client.Version()
	//  fmt.Printf("Connected using MCP protocol version %s\n", version)
	Version() string

	// IsInitialized returns whether the client has been initialized.
	//
	// Initialization occurs during the first operation that requires
	// server communication.
	IsInitialized() bool

	// IsConnected returns whether the client is currently connected to the server.
	//
	// Example:
	//  if client.IsConnected() {
	//      fmt.Println("Client is connected to the server")
	//  } else {
	//      fmt.Println("Client is not connected")
	//  }
	IsConnected() bool

	// WithSamplingHandler registers a handler for sampling requests.
	//
	// The handler will be called when the server requests sampling (e.g., for LLM interactions).
	// Returns the client instance for method chaining.
	//
	// Example:
	//  client = client.WithSamplingHandler(func(params SamplingCreateMessageParams) (SamplingResponse, error) {
	//      // Process sampling request
	//      return SamplingResponse{...}, nil
	//  })
	WithSamplingHandler(handler SamplingHandler) Client

	// GetSamplingHandler returns the currently registered sampling handler.
	GetSamplingHandler() SamplingHandler

	// RequestSampling initiates a sampling request to the server.
	//
	// This is typically used by advanced clients that need to request
	// sampling capabilities from the server.
	RequestSampling(req *SamplingRequest) (*SamplingResponse, error)

	// RequestStreamingSampling initiates a streaming sampling request to the server.
	//
	// The streaming API is available only in protocol version 2025-03-26 and later.
	// The handler is called for each chunk of the streaming response.
	RequestStreamingSampling(req *StreamingSamplingRequest, handler StreamingResponseHandler) (*StreamingSamplingSession, error)
}

Client represents an MCP client for communicating with MCP servers. It provides methods for all MCP operations including tool calls, resource access, prompt rendering, root management, and sampling functionality.

func NewClient

func NewClient(url string, options ...Option) (Client, error)

NewClient creates a new MCP client with the given URL and options. The client will automatically detect and adapt to the server's MCP specification version. It immediately establishes a connection to the server and returns an error if the connection fails.

The url parameter is interpreted based on its format:

  • "stdio:///": Uses Standard I/O for communication (useful for child processes)
  • "ws://host:port/path": Uses WebSocket protocol
  • "http://host:port/path": Uses HTTP protocol
  • "sse://host:port/path": Uses Server-Sent Events protocol
  • Custom schemes can be handled with a custom Transport implementation

Errors returned by NewClient may include:

  • Connection failures (e.g., server unreachable)
  • Protocol negotiation failures
  • Transport initialization errors

Example:

// Basic client with default options
client, err := client.NewClient("ws://localhost:8080/mcp")
if err != nil {
	log.Fatalf("Failed to create client: %v", err)
}

// Client with custom options
client, err := client.NewClient("http://api.example.com/mcp",
	client.WithProtocolVersion("2025-03-26"),
	client.WithLogger(myCustomLogger),
	client.WithRequestTimeout(time.Second * 20),
)

func SetupOptimizedSamplingClient added in v1.2.0

func SetupOptimizedSamplingClient(baseClient Client, opts *SamplingOptimizationOptions) Client

SetupOptimizedSamplingClient creates a client with sampling optimizations. This follows a separate constructor pattern rather than a functional option.

type ClientCapabilities added in v1.2.0

type ClientCapabilities struct {
	Roots        RootsCapability        `json:"roots,omitempty"`
	Sampling     map[string]interface{} `json:"sampling,omitempty"`
	Experimental map[string]interface{} `json:"experimental,omitempty"`
}

ClientCapabilities represents the capabilities supported by this client.

type ContentSizeAnalyzer added in v1.2.0

type ContentSizeAnalyzer struct {
	// Constants for size limitations
	MaxTextBytes     int
	MaxImageBytes    int
	MaxAudioBytes    int
	WarningThreshold float64 // 0.0-1.0 percentage of max before warning
}

ContentSizeAnalyzer analyzes and manages content size in sampling operations.

func NewContentSizeAnalyzer added in v1.2.0

func NewContentSizeAnalyzer() *ContentSizeAnalyzer

NewContentSizeAnalyzer creates a new analyzer with default limits.

func (*ContentSizeAnalyzer) AnalyzeContent added in v1.2.0

func (a *ContentSizeAnalyzer) AnalyzeContent(content SamplingMessageContent) (bool, string)

AnalyzeContent checks content size against limits and returns warnings/errors.

type ImageOptimizer added in v1.2.0

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

ImageOptimizer provides utilities for optimizing image data for sampling requests.

func NewImageOptimizer added in v1.2.0

func NewImageOptimizer(maxDimension int, quality int) *ImageOptimizer

NewImageOptimizer creates a new image optimizer with the specified settings.

func (*ImageOptimizer) OptimizeImageData added in v1.2.0

func (o *ImageOptimizer) OptimizeImageData(data string, mimeType string) (string, string, error)

OptimizeImageData optimizes image data for inclusion in sampling messages. This is a placeholder that would typically use an image processing library to resize and recompress the image.

type ImageSamplingContent added in v1.2.0

type ImageSamplingContent struct {
	Data     string
	MimeType string
}

ImageSamplingContent creates an image content struct for sampling messages

func (*ImageSamplingContent) ToMessageContent added in v1.2.0

func (i *ImageSamplingContent) ToMessageContent() SamplingMessageContent

ToMessageContent converts ImageSamplingContent to a SamplingMessageContent

func (*ImageSamplingContent) Validate added in v1.2.0

func (i *ImageSamplingContent) Validate() error

Validate ensures the image content is valid

type MCPServer added in v1.2.0

type MCPServer struct {
	Name   string
	Client Client
	// contains filtered or unexported fields
}

MCPServer represents a running MCP server process with a connected client

type Option added in v1.2.0

type Option func(*clientImpl)

Option is a client configuration option.

func WithConnectionTimeout added in v1.2.0

func WithConnectionTimeout(timeout time.Duration) Option

WithConnectionTimeout sets the client's connection timeout.

func WithExperimentalCapability added in v1.2.0

func WithExperimentalCapability(name string, config interface{}) Option

WithExperimentalCapability adds an experimental capability.

func WithLogger added in v0.1.11

func WithLogger(logger *slog.Logger) Option

WithLogger sets the client's logger.

func WithProtocolNegotiation added in v1.2.0

func WithProtocolNegotiation(enabled bool) Option

WithProtocolNegotiation enables or disables protocol version negotiation.

func WithProtocolVersion added in v1.2.0

func WithProtocolVersion(version string) Option

WithProtocolVersion sets the preferred protocol version for the client.

func WithRequestTimeout added in v0.1.11

func WithRequestTimeout(timeout time.Duration) Option

WithRequestTimeout sets the client's request timeout.

func WithRoots added in v1.2.0

func WithRoots(roots []Root) Option

WithRoots sets the initial roots for the client.

func WithRootsCapability added in v1.2.0

func WithRootsCapability(enabled bool, listChanged bool) Option

WithRootsCapability enables or disables the roots capability.

func WithSamplingCapability added in v1.2.0

func WithSamplingCapability(enabled bool, config map[string]interface{}) Option

WithSamplingCapability enables or disables the sampling capability.

func WithSamplingOptimizations added in v1.2.0

func WithSamplingOptimizations(opts *SamplingOptimizationOptions) Option

WithSamplingOptimizations enables sampling optimizations for the client.

func WithServerConfig added in v1.2.0

func WithServerConfig(configPath string, serverName string) Option

WithServerConfig loads server configurations from a file and connects to a specific named server. This is used to integrate with the server registry system to automatically manage server processes. If the server requires starting a new process, it will be launched and managed by the registry. When the client is closed, the associated server process will be terminated if it was launched by this option.

func WithServers added in v1.2.0

func WithServers(config ServerConfig, serverName string) Option

WithServers provides direct server configurations to the client. This is similar to WithServerConfig but accepts an in-memory configuration instead of loading from a file.

func WithTransport added in v1.2.0

func WithTransport(transport Transport) Option

WithTransport sets the client's transport.

func WithVersionDetector added in v1.2.0

func WithVersionDetector(detector *mcp.VersionDetector) Option

WithVersionDetector sets the client's version detector.

type RetryConfig added in v1.2.0

type RetryConfig struct {
	MaxRetries      int
	RetryInterval   time.Duration
	RetryMultiplier float64 // For exponential backoff
	MaxInterval     time.Duration
}

RetryConfig defines the retry behavior for sampling requests

func DefaultRetryConfig added in v1.2.0

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a default retry configuration

type Root added in v1.2.0

type Root struct {
	URI      string                 `json:"uri"`
	Name     string                 `json:"name,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

Root represents a filesystem root exposed to the MCP server.

type RootsCapability added in v1.2.0

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

RootsCapability represents the client's roots capability.

type SamplingCache added in v1.2.0

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

SamplingCache provides caching for sampling operations to improve performance. It is safe for concurrent use by multiple goroutines.

func NewSamplingCache added in v1.2.0

func NewSamplingCache(capacity int, ttl time.Duration) *SamplingCache

NewSamplingCache creates a new sampling cache with the specified capacity and TTL.

func (*SamplingCache) Clear added in v1.2.0

func (c *SamplingCache) Clear()

Clear empties the cache.

func (*SamplingCache) GetConfig added in v1.2.0

func (c *SamplingCache) GetConfig(key string) (*SamplingConfig, bool)

GetConfig retrieves a cached configuration by key, if it exists.

func (*SamplingCache) GetResponse added in v1.2.0

func (c *SamplingCache) GetResponse(params SamplingCreateMessageParams, version string) (SamplingResponse, bool)

GetResponse retrieves a cached response for a request, if it exists and hasn't expired.

func (*SamplingCache) SetConfig added in v1.2.0

func (c *SamplingCache) SetConfig(key string, config *SamplingConfig)

SetConfig caches a configuration with the specified key.

func (*SamplingCache) SetResponse added in v1.2.0

func (c *SamplingCache) SetResponse(params SamplingCreateMessageParams, version string, response SamplingResponse)

SetResponse caches a response for a request.

type SamplingChunk added in v1.2.0

type SamplingChunk struct {
	Content SamplingMessageContent `json:"content"`
}

SamplingChunk represents a chunk of a streaming response.

type SamplingCompletion added in v1.2.0

type SamplingCompletion struct {
	Model      string `json:"model,omitempty"`
	StopReason string `json:"stopReason,omitempty"`
}

SamplingCompletion represents the completion of a streaming response.

type SamplingConfig added in v1.2.0

type SamplingConfig struct {
	// Protocol specific parameters
	MaxTokens             int             // Maximum tokens to generate
	MaxSystemPrompt       int             // Maximum allowed system prompt length
	SupportedContentTypes map[string]bool // Map of supported content types
	ProtocolVersion       string          // The protocol version this config is for

	// Timeout and retry settings
	RequestTimeout time.Duration
	RetryConfig    RetryConfig

	// Streaming settings
	StreamingSupported bool
	MinChunkSize       int
	MaxChunkSize       int
	DefaultChunkSize   int

	// Model configuration
	ModelNameMaxLength int
}

SamplingConfig defines a complete configuration for sampling operations, allowing users to customize behavior within protocol constraints.

func NewSamplingConfig added in v1.2.0

func NewSamplingConfig() *SamplingConfig

NewSamplingConfig creates a new sampling configuration with sensible defaults. This is the ONLY constructor for SamplingConfig - all customization is done through fluent methods following this constructor.

func (*SamplingConfig) Apply added in v1.2.0

func (c *SamplingConfig) Apply(req *SamplingRequest) error

Apply applies the configuration to a sampling request

func (*SamplingConfig) ApplyToStreaming added in v1.2.0

func (c *SamplingConfig) ApplyToStreaming(req *StreamingSamplingRequest) error

ApplyToStreaming applies the configuration to a streaming sampling request

func (*SamplingConfig) ForVersion added in v1.2.0

func (c *SamplingConfig) ForVersion(version string) (*SamplingConfig, error)

ForVersion configures the sampling config for a specific protocol version, setting all version-specific constraints and capabilities.

func (*SamplingConfig) OptimizeForCompletion added in v1.2.0

func (c *SamplingConfig) OptimizeForCompletion() *SamplingConfig

OptimizeForCompletion configures the sampling for text completions

func (*SamplingConfig) OptimizeForImageGeneration added in v1.2.0

func (c *SamplingConfig) OptimizeForImageGeneration() (*SamplingConfig, error)

OptimizeForImageGeneration configures the sampling for image generation

func (*SamplingConfig) OptimizeForStreamingChat added in v1.2.0

func (c *SamplingConfig) OptimizeForStreamingChat() *SamplingConfig

OptimizeForStreamingChat configures the sampling for streaming chat

func (*SamplingConfig) ValidateForVersion added in v1.2.0

func (c *SamplingConfig) ValidateForVersion(version string) error

ValidateForVersion validates the configuration against a protocol version

func (*SamplingConfig) WithChunkSizeRange added in v1.2.0

func (c *SamplingConfig) WithChunkSizeRange(min, max, defaultSize int) *SamplingConfig

WithChunkSizeRange sets the min, max, and default chunk sizes for streaming

func (*SamplingConfig) WithMaxSystemPrompt added in v1.2.0

func (c *SamplingConfig) WithMaxSystemPrompt(maxLength int) *SamplingConfig

WithMaxSystemPrompt sets the maximum system prompt length

func (*SamplingConfig) WithMaxTokens added in v1.2.0

func (c *SamplingConfig) WithMaxTokens(maxTokens int) *SamplingConfig

WithMaxTokens sets the maximum number of tokens for the configuration

func (*SamplingConfig) WithModelNameMaxLength added in v1.2.0

func (c *SamplingConfig) WithModelNameMaxLength(maxLength int) *SamplingConfig

WithModelNameMaxLength sets the maximum length for model names

func (*SamplingConfig) WithRequestTimeout added in v1.2.0

func (c *SamplingConfig) WithRequestTimeout(timeout time.Duration) *SamplingConfig

WithRequestTimeout sets the request timeout duration

func (*SamplingConfig) WithRetryConfig added in v1.2.0

func (c *SamplingConfig) WithRetryConfig(retryConfig RetryConfig) *SamplingConfig

WithRetryConfig sets the retry configuration

func (*SamplingConfig) WithStreamingSupport added in v1.2.0

func (c *SamplingConfig) WithStreamingSupport(supported bool) *SamplingConfig

WithStreamingSupport enables or disables streaming support

func (*SamplingConfig) WithSupportedContentType added in v1.2.0

func (c *SamplingConfig) WithSupportedContentType(contentType string, supported bool) *SamplingConfig

WithSupportedContentType adds or removes a content type from supported types

type SamplingContentHandler added in v1.2.0

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

SamplingContentHandler is the interface for all sampling content handlers

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"`
	ProtocolVersion  string                   `json:"-"` // Internal field for version tracking
}

SamplingCreateMessageParams represents the parameters for a sampling/createMessage request.

func CreateSamplingCreateMessageParams added in v1.2.0

func CreateSamplingCreateMessageParams(
	messages []SamplingMessage,
	prefs SamplingModelPreferences,
	systemPrompt string,
	maxTokens int,
	protocolVersion string,
) (SamplingCreateMessageParams, error)

CreateSamplingCreateMessageParams creates parameters for a sampling/createMessage request

type SamplingError added in v1.2.0

type SamplingError struct {
	ErrorType        string // Category of error (network, parsing, validation, server)
	Message          string
	RetryRecommended bool
	OriginalError    error
}

SamplingError represents a sampling-specific error

func NewSamplingError added in v1.2.0

func NewSamplingError(errorType, message string, retry bool, originalErr error) *SamplingError

NewSamplingError creates a new sampling error

func (*SamplingError) Error added in v1.2.0

func (e *SamplingError) Error() string

Error returns the error message

func (*SamplingError) IsRetryable added in v1.2.0

func (e *SamplingError) IsRetryable() bool

IsRetryable returns whether the error is retryable

type SamplingHandler added in v1.2.0

type SamplingHandler func(params SamplingCreateMessageParams) (SamplingResponse, error)

SamplingHandler is a function that handles sampling/createMessage requests.

type SamplingMessage added in v1.2.0

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

SamplingMessage represents a message in a sampling conversation.

func CreateAudioSamplingMessage added in v1.2.0

func CreateAudioSamplingMessage(role, audioData, mimeType string) SamplingMessage

CreateAudioSamplingMessage creates a sampling message with audio content.

func CreateImageSamplingMessage added in v1.2.0

func CreateImageSamplingMessage(role, imageData, mimeType string) SamplingMessage

CreateImageSamplingMessage creates a sampling message with image content.

func CreateSamplingMessage added in v1.2.0

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

CreateSamplingMessage creates a sampling message with the provided content handler

func CreateTextSamplingMessage added in v1.2.0

func CreateTextSamplingMessage(role, text string) SamplingMessage

CreateTextSamplingMessage creates a sampling message with text content.

type SamplingMessageContent added in v1.2.0

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

SamplingMessageContent represents the content of a sampling message.

func (*SamplingMessageContent) IsValidForVersion added in v1.2.0

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

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

type SamplingModelHint added in v1.2.0

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

SamplingModelHint represents a hint for model selection in sampling requests.

type SamplingModelPreferences added in v1.2.0

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

SamplingModelPreferences represents the model preferences for a sampling request.

type SamplingOptimizationOptions added in v1.2.0

type SamplingOptimizationOptions struct {
	CacheCapacity int
	CacheTTL      time.Duration
	LogWarnings   bool
	MaxTextBytes  int
	MaxImageBytes int
	MaxAudioBytes int
	ImageMaxDim   int
	ImageQuality  int
}

SamplingOptimizationOptions holds configuration for sampling optimizations

func DefaultSamplingOptimizationOptions added in v1.2.0

func DefaultSamplingOptimizationOptions() *SamplingOptimizationOptions

DefaultSamplingOptimizationOptions returns default optimization options

type SamplingPerformanceMetrics added in v1.2.0

type SamplingPerformanceMetrics struct {
	RequestCount      int64         // Total requests sent
	SuccessCount      int64         // Successful requests
	ErrorCount        int64         // Failed requests
	TotalResponseTime time.Duration // Total time spent on responses
	MaxResponseTime   time.Duration // Maximum response time
	MinResponseTime   time.Duration // Minimum response time
	CacheHits         int64         // Number of cache hits
	CacheMisses       int64         // Number of cache misses
	BytesSent         int64         // Total bytes sent
	BytesReceived     int64         // Total bytes received
	// contains filtered or unexported fields
}

SamplingPerformanceMetrics tracks performance metrics for sampling operations.

func NewSamplingPerformanceMetrics added in v1.2.0

func NewSamplingPerformanceMetrics() *SamplingPerformanceMetrics

NewSamplingPerformanceMetrics creates a new performance metrics tracker.

func (*SamplingPerformanceMetrics) GetAverageResponseTime added in v1.2.0

func (m *SamplingPerformanceMetrics) GetAverageResponseTime() time.Duration

GetAverageResponseTime returns the average response time.

func (*SamplingPerformanceMetrics) GetMetrics added in v1.2.0

func (m *SamplingPerformanceMetrics) GetMetrics() map[string]interface{}

GetMetrics returns a map of all metrics.

func (*SamplingPerformanceMetrics) RecordRequest added in v1.2.0

func (m *SamplingPerformanceMetrics) RecordRequest(
	success bool,
	responseTime time.Duration,
	cacheHit bool,
	bytesSent int,
	bytesReceived int)

RecordRequest records metrics for a sampling request.

func (*SamplingPerformanceMetrics) Reset added in v1.2.0

func (m *SamplingPerformanceMetrics) Reset()

Reset clears all metrics.

type SamplingRequest added in v1.2.0

type SamplingRequest struct {
	// Core request parameters
	Messages         []SamplingMessage
	ModelPreferences SamplingModelPreferences
	SystemPrompt     string
	MaxTokens        int

	// Context and options
	Context              context.Context
	Timeout              time.Duration
	RetryConfig          RetryConfig
	ProtocolVersion      string
	FormatAsNotification bool
}

SamplingRequest represents a request to the sampling API. It contains all the necessary information to construct a properly formatted request for any protocol version.

func CreateChatRequest added in v1.2.0

func CreateChatRequest(messages []SamplingMessage, systemPrompt string, version string) (*SamplingRequest, error)

CreateChatRequest creates a request for a chat conversation

func CreateImageGenerationRequest added in v1.2.0

func CreateImageGenerationRequest(prompt string, version string) (*SamplingRequest, error)

CreateImageGenerationRequest creates a request for image generation

func CreateTextCompletionRequest added in v1.2.0

func CreateTextCompletionRequest(prompt string, version string) (*SamplingRequest, error)

CreateTextCompletionRequest creates a request optimized for text completion

func NewSamplingRequest added in v1.2.0

func NewSamplingRequest(messages []SamplingMessage, prefs SamplingModelPreferences) *SamplingRequest

NewSamplingRequest creates a new sampling request with the given parameters

func (*SamplingRequest) AddAudioMessage added in v1.2.0

func (req *SamplingRequest) AddAudioMessage(role, audioData, mimeType string) *SamplingRequest

AddAudioMessage adds an audio message to the request

func (*SamplingRequest) AddImageMessage added in v1.2.0

func (req *SamplingRequest) AddImageMessage(role, imageData, mimeType string) *SamplingRequest

AddImageMessage adds an image message to the request

func (*SamplingRequest) AddTextMessage added in v1.2.0

func (req *SamplingRequest) AddTextMessage(role, text string) *SamplingRequest

AddTextMessage adds a text message to the request

func (*SamplingRequest) AsNotification added in v1.2.0

func (req *SamplingRequest) AsNotification() *SamplingRequest

AsNotification formats the request as a notification instead of a request

func (*SamplingRequest) BuildCreateMessageRequest added in v1.2.0

func (req *SamplingRequest) BuildCreateMessageRequest(id int) ([]byte, error)

BuildCreateMessageRequest builds a JSON-RPC request for sampling/createMessage

func (*SamplingRequest) Validate added in v1.2.0

func (req *SamplingRequest) Validate() error

Validate checks if the request is valid

func (*SamplingRequest) WithContext added in v1.2.0

func (req *SamplingRequest) WithContext(ctx context.Context) *SamplingRequest

WithContext sets the context for the request

func (*SamplingRequest) WithMaxTokens added in v1.2.0

func (req *SamplingRequest) WithMaxTokens(maxTokens int) *SamplingRequest

WithMaxTokens sets the maximum number of tokens for the request

func (*SamplingRequest) WithProtocolVersion added in v1.2.0

func (req *SamplingRequest) WithProtocolVersion(version string) *SamplingRequest

WithProtocolVersion sets the protocol version for the request This is normally set automatically when the request is sent

func (*SamplingRequest) WithRetryConfig added in v1.2.0

func (req *SamplingRequest) WithRetryConfig(config RetryConfig) *SamplingRequest

WithRetryConfig sets the retry configuration for the request

func (*SamplingRequest) WithSystemPrompt added in v1.2.0

func (req *SamplingRequest) WithSystemPrompt(prompt string) *SamplingRequest

WithSystemPrompt sets the system prompt for the request

func (*SamplingRequest) WithTimeout added in v1.2.0

func (req *SamplingRequest) WithTimeout(timeout time.Duration) *SamplingRequest

WithTimeout sets the timeout for the request

type SamplingResponse added in v1.2.0

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

SamplingResponse represents the response to a sampling/createMessage request.

func ParseSamplingResponseForTest added in v1.2.0

func ParseSamplingResponseForTest(data []byte) (*SamplingResponse, error)

ParseSamplingResponseForTest exposes parseSamplingResponse for testing

func (*SamplingResponse) GetAudioData added in v1.2.0

func (r *SamplingResponse) GetAudioData() (string, string, error)

GetAudioData returns the audio data and MIME type if available

func (*SamplingResponse) GetContent added in v1.2.0

func (r *SamplingResponse) GetContent() string

GetContent returns the text content of a sampling response

func (*SamplingResponse) GetContentType added in v1.2.0

func (r *SamplingResponse) GetContentType() string

GetContentType returns the content type of a sampling response

func (*SamplingResponse) GetImageData added in v1.2.0

func (r *SamplingResponse) GetImageData() (string, string, error)

GetImageData returns the image data and MIME type if available

type SamplingResponseError added in v1.2.0

type SamplingResponseError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    string `json:"data,omitempty"`
}

SamplingResponseError represents an error in a sampling response

func (*SamplingResponseError) Error added in v1.2.0

func (e *SamplingResponseError) Error() string

Error returns the error message

type ServerConfig added in v1.0.9

type ServerConfig struct {
	MCPServers map[string]ServerDefinition `json:"mcpServers"`
}

ServerConfig represents a complete MCP server configuration file

type ServerDefinition added in v1.2.0

type ServerDefinition struct {
	Command string            `json:"command"`
	Args    []string          `json:"args"`
	Env     map[string]string `json:"env,omitempty"`
	URL     string            `json:"url,omitempty"`
}

ServerDefinition defines how to launch and connect to an MCP server

type ServerRegistry added in v1.2.0

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

ServerRegistry manages a collection of MCP servers loaded from configuration

func NewServerRegistry added in v1.2.0

func NewServerRegistry() *ServerRegistry

NewServerRegistry creates a new empty server registry

func (*ServerRegistry) ApplyConfig added in v1.2.0

func (r *ServerRegistry) ApplyConfig(config ServerConfig) error

ApplyConfig applies a server configuration by starting servers and connecting clients

func (*ServerRegistry) GetClient added in v1.2.0

func (r *ServerRegistry) GetClient(name string) (Client, error)

GetClient returns the client for a named server

func (*ServerRegistry) GetServerNames added in v1.2.0

func (r *ServerRegistry) GetServerNames() ([]string, error)

GetServerNames returns a list of all server names in the registry

func (*ServerRegistry) LoadConfig added in v1.2.0

func (r *ServerRegistry) LoadConfig(path string) error

LoadConfig loads a server configuration from a file

func (*ServerRegistry) StartServer added in v1.2.0

func (r *ServerRegistry) StartServer(name string, def ServerDefinition) error

StartServer starts a server from its definition and connects a client to it

func (*ServerRegistry) StopAll added in v1.2.0

func (r *ServerRegistry) StopAll() error

StopAll stops all servers

func (*ServerRegistry) StopServer added in v1.2.0

func (r *ServerRegistry) StopServer(name string) error

StopServer stops a server by name

type StreamingResponseHandler added in v1.2.0

type StreamingResponseHandler func(response *StreamingSamplingResponse) error

StreamingResponseHandler is a function that handles streaming responses

type StreamingSamplingRequest added in v1.2.0

type StreamingSamplingRequest struct {
	// Base sampling request
	SamplingRequest

	// Streaming-specific options
	ChunkSize      int  // Maximum size of text chunks (applicable for text streaming)
	MaxChunks      int  // Maximum number of chunks to receive (0 for unlimited)
	StopOnComplete bool // Whether to stop streaming when isComplete=true is received
}

StreamingSamplingRequest represents a request for streaming sampling operations

func CreateStreamingChatRequest added in v1.2.0

func CreateStreamingChatRequest(messages []SamplingMessage, systemPrompt string, version string) (*StreamingSamplingRequest, error)

CreateStreamingChatRequest creates a request for streaming chat responses

func NewStreamingSamplingRequest added in v1.2.0

func NewStreamingSamplingRequest(messages []SamplingMessage, prefs SamplingModelPreferences) *StreamingSamplingRequest

NewStreamingSamplingRequest creates a new streaming sampling request

func (*StreamingSamplingRequest) BuildStreamingCreateMessageRequest added in v1.2.0

func (req *StreamingSamplingRequest) BuildStreamingCreateMessageRequest(id int) ([]byte, error)

BuildStreamingCreateMessageRequest builds a JSON-RPC request for streaming sampling

func (*StreamingSamplingRequest) WithChunkSize added in v1.2.0

func (req *StreamingSamplingRequest) WithChunkSize(size int) *StreamingSamplingRequest

WithChunkSize sets the maximum chunk size for text streaming

func (*StreamingSamplingRequest) WithMaxChunks added in v1.2.0

func (req *StreamingSamplingRequest) WithMaxChunks(maxChunks int) *StreamingSamplingRequest

WithMaxChunks sets the maximum number of chunks to receive

func (*StreamingSamplingRequest) WithStopOnComplete added in v1.2.0

func (req *StreamingSamplingRequest) WithStopOnComplete(stop bool) *StreamingSamplingRequest

WithStopOnComplete sets whether to stop streaming when isComplete=true is received

type StreamingSamplingResponse added in v1.2.0

type StreamingSamplingResponse struct {
	// Base response fields
	Role       string                 `json:"role"`
	Content    SamplingMessageContent `json:"content"`
	Model      string                 `json:"model,omitempty"`
	StopReason string                 `json:"stopReason,omitempty"`

	// Streaming-specific fields
	IsComplete bool   `json:"isComplete"`
	ChunkID    string `json:"chunkId,omitempty"`
}

StreamingSamplingResponse represents a streaming response from a sampling operation

func ParseStreamingSamplingResponseForTest added in v1.2.0

func ParseStreamingSamplingResponseForTest(data []byte) (*StreamingSamplingResponse, error)

ParseStreamingSamplingResponseForTest exposes parseStreamingSamplingResponse for testing

type StreamingSamplingSession added in v1.2.0

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

StreamingSamplingSession represents an active streaming sampling session

func (*StreamingSamplingSession) GetCombinedResponse added in v1.2.0

func (s *StreamingSamplingSession) GetCombinedResponse() *SamplingResponse

GetCombinedResponse returns a combined response from all chunks

func (*StreamingSamplingSession) GetResponses added in v1.2.0

GetResponses returns all received responses

func (*StreamingSamplingSession) IsComplete added in v1.2.0

func (s *StreamingSamplingSession) IsComplete() bool

IsComplete returns whether the streaming session is complete

func (*StreamingSamplingSession) Stop added in v1.2.0

func (s *StreamingSamplingSession) Stop()

Stop stops the streaming session

type TextSamplingContent added in v1.2.0

type TextSamplingContent struct {
	Text string
}

TextSamplingContent creates a text content struct for sampling messages

func (*TextSamplingContent) ToMessageContent added in v1.2.0

func (t *TextSamplingContent) ToMessageContent() SamplingMessageContent

ToMessageContent converts TextSamplingContent to a SamplingMessageContent

func (*TextSamplingContent) Validate added in v1.2.0

func (t *TextSamplingContent) Validate() error

Validate ensures the text content is valid

type Transport added in v1.2.0

type Transport interface {
	// Connect establishes a connection to the server.
	Connect() error

	// ConnectWithContext establishes a connection to the server with context for timeout/cancellation.
	ConnectWithContext(ctx context.Context) error

	// Disconnect closes the connection to the server.
	Disconnect() error

	// Send sends a message to the server and waits for a response.
	Send(message []byte) ([]byte, error)

	// SendWithContext sends a message with context for timeout/cancellation.
	SendWithContext(ctx context.Context, message []byte) ([]byte, error)

	// SetRequestTimeout sets the default timeout for request operations.
	SetRequestTimeout(timeout time.Duration)

	// SetConnectionTimeout sets the default timeout for connection operations.
	SetConnectionTimeout(timeout time.Duration)

	// RegisterNotificationHandler registers a handler for server-initiated messages.
	RegisterNotificationHandler(handler func(method string, params []byte))
}

Transport represents a transport layer for client communication. It handles the communication between the client and the server.

Directories

Path Synopsis
Package test provides test utilities for the client package.
Package test provides test utilities for the client package.
draft
Package draft provides test utilities specific to the draft protocol version.
Package draft provides test utilities specific to the draft protocol version.

Jump to

Keyboard shortcuts

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