client

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: May 29, 2025 License: MIT Imports: 30 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.

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 DefaultGRPCClientOptions added in v1.2.1

func DefaultGRPCClientOptions() []grpc.Option

DefaultGRPCClientOptions returns a set of default options for gRPC client.

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

func WithGRPCKeepAlive added in v1.2.1

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

WithGRPCKeepAlive configures keepalive parameters for the gRPC transport.

func WithGRPCMaxMessageSize added in v1.2.1

func WithGRPCMaxMessageSize(size int) grpc.Option

WithGRPCMaxMessageSize sets the maximum message size for the gRPC transport.

func WithGRPCTLS added in v1.2.1

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

WithGRPCTLS configures TLS for the gRPC transport.

func WithGRPCTimeout added in v1.2.1

func WithGRPCTimeout(timeout time.Duration) grpc.Option

WithGRPCTimeout sets the connection timeout for the gRPC transport.

Types

type 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 GRPCTransport added in v1.2.1

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

GRPCTransport wraps a grpc.Transport to implement the client.Transport interface

func (*GRPCTransport) Connect added in v1.2.1

func (t *GRPCTransport) Connect() error

Connect establishes a connection to the server

func (*GRPCTransport) ConnectWithContext added in v1.2.1

func (t *GRPCTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext establishes a connection to the server with context

func (*GRPCTransport) Disconnect added in v1.2.1

func (t *GRPCTransport) Disconnect() error

Disconnect closes the connection to the server

func (*GRPCTransport) RegisterNotificationHandler added in v1.2.1

func (t *GRPCTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler registers a handler for server-initiated messages

func (*GRPCTransport) Send added in v1.2.1

func (t *GRPCTransport) Send(message []byte) ([]byte, error)

Send sends a message to the server and waits for a response

func (*GRPCTransport) SendWithContext added in v1.2.1

func (t *GRPCTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext sends a message with context for timeout/cancellation

func (*GRPCTransport) SetConnectionTimeout added in v1.2.1

func (t *GRPCTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout sets the default timeout for connection operations

func (*GRPCTransport) SetRequestTimeout added in v1.2.1

func (t *GRPCTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout sets the default timeout for request operations

type HTTPOption added in v1.2.2

type HTTPOption func(*httpConfig)

HTTPOption is a function that configures an HTTP transport. These options allow customizing the behavior of the HTTP client connection.

func WithHTTPClient added in v0.1.11

func WithHTTPClient(client *http.Client) HTTPOption

WithHTTPClient sets a custom HTTP client for the HTTP transport.

func WithHTTPHeader added in v1.2.2

func WithHTTPHeader(key, value string) HTTPOption

WithHTTPHeader adds a custom header to HTTP requests.

func WithHTTPHeaders added in v1.2.2

func WithHTTPHeaders(headers map[string]string) HTTPOption

WithHTTPHeaders sets multiple custom headers for HTTP requests.

func WithHTTPPollInterval added in v1.2.2

func WithHTTPPollInterval(interval time.Duration) HTTPOption

WithHTTPPollInterval sets the interval for long-polling in HTTP transport.

func WithHTTPRetry added in v1.2.2

func WithHTTPRetry(attempts int, delay time.Duration) HTTPOption

WithHTTPRetry configures retry behavior for HTTP requests.

func WithHTTPTimeout added in v1.2.2

func WithHTTPTimeout(timeout time.Duration) HTTPOption

WithHTTPTimeout sets a specific timeout for HTTP operations.

type HTTPTransportAdapter added in v1.2.2

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

HTTPTransportAdapter adapts the HTTP transport to the client Transport interface.

func NewHTTPTransportAdapter added in v1.2.2

func NewHTTPTransportAdapter(url string) *HTTPTransportAdapter

NewHTTPTransportAdapter creates a new HTTP transport adapter.

func (*HTTPTransportAdapter) AddHeader added in v1.2.2

func (t *HTTPTransportAdapter) AddHeader(key, value string)

AddHeader adds a custom header to all HTTP requests.

func (*HTTPTransportAdapter) Connect added in v1.2.2

func (t *HTTPTransportAdapter) Connect() error

Connect implements the Transport interface Connect method.

func (*HTTPTransportAdapter) ConnectWithContext added in v1.2.2

func (t *HTTPTransportAdapter) ConnectWithContext(ctx context.Context) error

ConnectWithContext implements the Transport interface ConnectWithContext method.

func (*HTTPTransportAdapter) Disconnect added in v1.2.2

func (t *HTTPTransportAdapter) Disconnect() error

Disconnect implements the Transport interface Disconnect method.

func (*HTTPTransportAdapter) GetAddr added in v1.2.2

func (t *HTTPTransportAdapter) GetAddr() string

GetAddr returns the transport's address.

func (*HTTPTransportAdapter) RegisterNotificationHandler added in v1.2.2

func (t *HTTPTransportAdapter) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler implements the Transport interface.

func (*HTTPTransportAdapter) Send added in v1.2.2

func (t *HTTPTransportAdapter) Send(message []byte) ([]byte, error)

Send implements the Transport interface Send method.

func (*HTTPTransportAdapter) SendWithContext added in v1.2.2

func (t *HTTPTransportAdapter) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext implements the Transport interface SendWithContext method.

func (*HTTPTransportAdapter) SetClient added in v1.2.2

func (t *HTTPTransportAdapter) SetClient(client *http.Client)

SetClient sets a custom HTTP client.

func (*HTTPTransportAdapter) SetConnectionTimeout added in v1.2.2

func (t *HTTPTransportAdapter) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout implements the Transport interface.

func (*HTTPTransportAdapter) SetPollInterval added in v1.2.2

func (t *HTTPTransportAdapter) SetPollInterval(interval time.Duration)

SetPollInterval sets the interval for HTTP long-polling.

func (*HTTPTransportAdapter) SetRequestTimeout added in v1.2.2

func (t *HTTPTransportAdapter) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout implements the Transport interface.

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 MQTTTransport added in v1.2.1

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

MQTTTransport implements the Transport interface for MQTT.

func NewMQTTTransport added in v1.2.1

func NewMQTTTransport(brokerURL string, options ...MQTTTransportOption) *MQTTTransport

NewMQTTTransport creates a new MQTT transport.

func (*MQTTTransport) Connect added in v1.2.1

func (t *MQTTTransport) Connect() error

Connect implements the Transport.Connect method.

func (*MQTTTransport) ConnectWithContext added in v1.2.1

func (t *MQTTTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext implements the Transport.ConnectWithContext method.

func (*MQTTTransport) Disconnect added in v1.2.1

func (t *MQTTTransport) Disconnect() error

Disconnect implements the Transport.Disconnect method.

func (*MQTTTransport) RegisterNotificationHandler added in v1.2.1

func (t *MQTTTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler implements the Transport.RegisterNotificationHandler method.

func (*MQTTTransport) Send added in v1.2.1

func (t *MQTTTransport) Send(message []byte) ([]byte, error)

Send implements the Transport.Send method.

func (*MQTTTransport) SendWithContext added in v1.2.1

func (t *MQTTTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext implements the Transport.SendWithContext method.

func (*MQTTTransport) SetConnectionTimeout added in v1.2.1

func (t *MQTTTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout implements the Transport.SetConnectionTimeout method.

func (*MQTTTransport) SetRequestTimeout added in v1.2.1

func (t *MQTTTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout implements the Transport.SetRequestTimeout method.

type MQTTTransportOption added in v1.2.1

type MQTTTransportOption func(*MQTTTransport)

MQTTTransportOption represents a configuration option for the MQTT transport

func WithMQTTClientID added in v1.2.1

func WithMQTTClientID(clientID string) MQTTTransportOption

WithMQTTClientID sets the client ID

func WithMQTTCredentials added in v1.2.1

func WithMQTTCredentials(username, password string) MQTTTransportOption

WithMQTTCredentials sets the username and password for MQTT broker authentication

func WithMQTTQoS added in v1.2.1

func WithMQTTQoS(qos byte) MQTTTransportOption

WithMQTTQoS sets the MQTT Quality of Service level

func WithMQTTTLS added in v1.2.1

func WithMQTTTLS(config *mqtt.TLSConfig) MQTTTransportOption

WithMQTTTLS sets TLS configuration for secure MQTT connections

func WithMQTTTopicPrefix added in v1.2.1

func WithMQTTTopicPrefix(prefix string) MQTTTransportOption

WithMQTTTopicPrefix sets the topic prefix for MQTT messages

type NATSTransport added in v1.2.1

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

NATSTransport implements the Transport interface for NATS.

func NewNATSTransport added in v1.2.1

func NewNATSTransport(serverURL string, options ...NATSTransportOption) *NATSTransport

NewNATSTransport creates a new NATS transport.

func (*NATSTransport) Connect added in v1.2.1

func (t *NATSTransport) Connect() error

Connect implements the Transport.Connect method.

func (*NATSTransport) ConnectWithContext added in v1.2.1

func (t *NATSTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext implements the Transport.ConnectWithContext method.

func (*NATSTransport) Disconnect added in v1.2.1

func (t *NATSTransport) Disconnect() error

Disconnect implements the Transport.Disconnect method.

func (*NATSTransport) RegisterNotificationHandler added in v1.2.1

func (t *NATSTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler implements the Transport.RegisterNotificationHandler method.

func (*NATSTransport) Send added in v1.2.1

func (t *NATSTransport) Send(message []byte) ([]byte, error)

Send implements the Transport.Send method.

func (*NATSTransport) SendWithContext added in v1.2.1

func (t *NATSTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext implements the Transport.SendWithContext method.

func (*NATSTransport) SetConnectionTimeout added in v1.2.1

func (t *NATSTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout implements the Transport.SetConnectionTimeout method.

func (*NATSTransport) SetRequestTimeout added in v1.2.1

func (t *NATSTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout implements the Transport.SetRequestTimeout method.

type NATSTransportOption added in v1.2.1

type NATSTransportOption func(*NATSTransport)

NATSTransportOption represents a configuration option for the NATS transport

func WithNATSClientID added in v1.2.1

func WithNATSClientID(clientID string) NATSTransportOption

WithNATSClientID sets the client ID for the NATS transport

func WithNATSCredentials added in v1.2.1

func WithNATSCredentials(username, password string) NATSTransportOption

WithNATSCredentials sets the username and password for the NATS transport

func WithNATSSubjectPrefix added in v1.2.1

func WithNATSSubjectPrefix(prefix string) NATSTransportOption

WithNATSSubjectPrefix sets the subject prefix for the NATS transport

func WithNATSTLS added in v1.2.1

func WithNATSTLS(config *natst.TLSConfig) NATSTransportOption

WithNATSTLS sets the TLS configuration for the NATS transport

func WithNATSToken added in v1.2.1

func WithNATSToken(token string) NATSTransportOption

WithNATSToken sets the token for the NATS transport

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 WithGRPC added in v1.2.1

func WithGRPC(address string, options ...grpc.Option) Option

WithGRPC returns a client configuration option that uses gRPC transport. The gRPC transport provides bi-directional streaming and high-performance communication.

Parameters:

  • address: The server address to connect to (e.g., "localhost:50051")
  • options: Optional configuration options for the gRPC transport

Returns:

  • A client configuration option

func WithHTTP added in v1.2.2

func WithHTTP(url string, options ...HTTPOption) Option

WithHTTP configures the client to use HTTP transport for communication.

Parameters: - url: The endpoint URL (e.g., "http://localhost:8080/mcp") - options: Optional configuration settings

Example:

client.New(
    client.WithHTTP("http://localhost:8080/mcp"),
    // or with options:
    client.WithHTTP("http://localhost:8080/mcp",
        client.WithHTTPHeader("Authorization", "Bearer token"),
        client.WithHTTPTimeout(10 * time.Second))
)

func WithLogger added in v0.1.11

func WithLogger(logger *slog.Logger) Option

WithLogger sets the client's logger.

func WithMQTT added in v1.2.1

func WithMQTT(brokerURL string, options ...MQTTTransportOption) Option

WithMQTT configures the client to use MQTT for communication with optional configuration options.

Parameters: - brokerURL: The MQTT broker URL (e.g., "tcp://broker.example.com:1883") - options: Optional configuration settings (QoS, credentials, topics, etc.)

Example:

client, err := gomcp.NewClient("test-service",
    client.WithMQTT("tcp://broker.example.com:1883"),
    // or with options:
    client.WithMQTT("tcp://broker.example.com:1883",
        client.WithMQTTClientID("my-client"),
        client.WithMQTTQoS(1),
        client.WithMQTTCredentials("username", "password")),
)

func WithNATS added in v1.2.1

func WithNATS(serverURL string, options ...NATSTransportOption) Option

WithNATS configures the client to use NATS for communication with optional configuration options.

Parameters: - serverURL: The NATS server URL (e.g., "nats://localhost:4222") - options: Optional configuration settings (credentials, token, subjects, etc.)

Example:

client, err := gomcp.NewClient("test-service",
    client.WithNATS("nats://localhost:4222"),
    // or with options:
    client.WithNATS("nats://localhost:4222",
        client.WithNATSClientID("my-client"),
        client.WithNATSCredentials("username", "password")),
)

func WithOldestProtocolVersion added in v1.2.2

func WithOldestProtocolVersion() Option

WithOldestProtocolVersion sets the client to use the oldest supported protocol version. This is useful for maximum compatibility with servers that might not support newer versions.

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 a specific protocol version for the client to use. This bypasses the normal negotiation process and forces the client to use this version. This is useful for testing or when you know exactly which version the server expects.

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 WithSSE added in v1.2.2

func WithSSE(url string) Option

WithSSE returns a client configuration option that uses SSE transport. The SSE transport provides server-sent events for real-time updates from server to client. By default, it uses the oldest protocol version for maximum compatibility unless the user has explicitly set a different protocol version.

Parameters:

Returns:

  • A client configuration option

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 WithStdio added in v1.2.2

func WithStdio(options ...StdioOption) Option

WithStdio configures the client to use Standard I/O for communication with optional configuration options.

This is particularly useful for CLI applications or when communicating with child processes.

Parameters: - options: Optional configuration settings (custom I/O, timeout, etc.)

Example:

client.New(
    client.WithStdio(),
    // or with options:
    client.WithStdio(
        client.WithStdioInput(customInput),
        client.WithStdioOutput(customOutput),
        client.WithStdioNewline(false))
)

func WithTransport added in v1.2.0

func WithTransport(transport Transport) Option

WithTransport sets the client's transport.

func WithUDP added in v1.2.1

func WithUDP(address string, options ...UDPOption) Option

WithUDP configures the client to use UDP for communication with optional configuration options.

UDP provides low-latency communication with minimal overhead, suitable for high-throughput scenarios where occasional packet loss is acceptable.

Parameters: - address: The UDP address in the format "host:port" - options: Optional configuration settings (buffering, timeouts, etc.)

Example:

client.New(
    client.WithUDP("example.com:8080"),
    // or with options:
    client.WithUDP("example.com:8080",
        client.WithReadTimeout(5*time.Second),
        client.WithReliability(true))
)

func WithUnixSocket added in v1.2.1

func WithUnixSocket(socketPath string, options ...UnixSocketOption) Option

WithUnixSocket configures the client to use Unix Domain Sockets for communication with optional configuration options.

Parameters: - socketPath: The path to the Unix socket file - options: Optional configuration settings (timeouts, reconnection, etc.)

Example:

client.New(
    client.WithUnixSocket("/tmp/mcp.sock"),
    // or with options:
    client.WithUnixSocket("/tmp/mcp.sock",
        unix.WithTimeout(time.Second*5),
        unix.WithReconnect(true))
)

func WithVersionDetector added in v1.2.0

func WithVersionDetector(detector *mcp.VersionDetector) Option

WithVersionDetector sets the client's version detector.

func WithWSPath added in v1.2.2

func WithWSPath(path string) Option

WithWSPath configures the WebSocket path for the WebSocket connection.

func WithWSPathPrefix added in v1.2.2

func WithWSPathPrefix(prefix string) Option

WithWSPathPrefix configures the path prefix for the WebSocket connection.

func WithWebsocket added in v1.2.2

func WithWebsocket(url string) Option

WithWebsocket returns a client configuration option that uses WebSocket transport. The WebSocket transport provides a persistent connection for communication with a server.

Parameters:

  • url: The WebSocket server URL to connect to (e.g., "ws://localhost:8080/ws")

Returns:

  • A client configuration option

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 SSETransport added in v1.2.2

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

SSETransport adapts the sse.Transport to implement the client.Transport interface

func NewSSETransport added in v0.1.11

func NewSSETransport(url string, logger *slog.Logger) *SSETransport

NewSSETransport creates a new SSE transport adapter.

func (*SSETransport) Connect added in v1.2.2

func (t *SSETransport) Connect() error

Connect establishes a connection to the server.

func (*SSETransport) ConnectWithContext added in v1.2.2

func (t *SSETransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext establishes a connection to the server with context for timeout/cancellation.

func (*SSETransport) Disconnect added in v1.2.2

func (t *SSETransport) Disconnect() error

Disconnect closes the connection to the server.

func (*SSETransport) RegisterNotificationHandler added in v1.2.2

func (t *SSETransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler registers a handler for server-initiated messages.

func (*SSETransport) Send added in v1.2.2

func (t *SSETransport) Send(message []byte) ([]byte, error)

Send sends a message to the server and waits for a response.

func (*SSETransport) SendWithContext added in v1.2.2

func (t *SSETransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext sends a message with context for timeout/cancellation.

func (*SSETransport) SetConnectionTimeout added in v1.2.2

func (t *SSETransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout sets the default timeout for connection operations.

func (*SSETransport) SetDebugEnabled added in v1.2.2

func (t *SSETransport) SetDebugEnabled(enabled bool)

SetDebugEnabled enables or disables debug logging

func (*SSETransport) SetRequestTimeout added in v1.2.2

func (t *SSETransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout sets the default timeout for request operations.

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 StdioOption added in v1.2.2

type StdioOption func(*stdioConfig)

StdioOption is a function that configures a Stdio transport. These options allow customizing the behavior of the Stdio client connection.

func WithStdioInput added in v1.2.2

func WithStdioInput(in io.Reader) StdioOption

WithStdioInput sets a custom input reader for the Stdio transport.

func WithStdioNewline added in v1.2.2

func WithStdioNewline(appendNewline bool) StdioOption

WithStdioNewline configures whether to append a newline character to messages.

func WithStdioOutput added in v1.2.2

func WithStdioOutput(out io.Writer) StdioOption

WithStdioOutput sets a custom output writer for the Stdio transport.

func WithStdioTimeout added in v1.2.2

func WithStdioTimeout(timeout time.Duration) StdioOption

WithStdioTimeout sets the timeout for Stdio operations.

type StdioTransport added in v1.2.2

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

StdioTransport adapts the stdio transport to the client Transport interface.

func NewStdioTransport added in v0.1.11

func NewStdioTransport() *StdioTransport

NewStdioTransport creates a new stdio transport adapter.

func NewStdioTransportWithIO added in v1.2.2

func NewStdioTransportWithIO(in io.Reader, out io.Writer) *StdioTransport

NewStdioTransportWithIO creates a new stdio transport adapter with custom IO.

func (*StdioTransport) Connect added in v1.2.2

func (t *StdioTransport) Connect() error

Connect establishes a connection to the server.

func (*StdioTransport) ConnectWithContext added in v1.2.2

func (t *StdioTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext establishes a connection to the server with context for timeout/cancellation.

func (*StdioTransport) Disconnect added in v1.2.2

func (t *StdioTransport) Disconnect() error

Disconnect closes the connection to the server.

func (*StdioTransport) RegisterNotificationHandler added in v1.2.2

func (t *StdioTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler registers a handler for server-initiated messages.

func (*StdioTransport) Send added in v1.2.2

func (t *StdioTransport) Send(message []byte) ([]byte, error)

Send sends a message to the server and waits for a response.

func (*StdioTransport) SendWithContext added in v1.2.2

func (t *StdioTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext sends a message with context for timeout/cancellation.

func (*StdioTransport) SetConnectionTimeout added in v1.2.2

func (t *StdioTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout sets the default timeout for connection operations.

func (*StdioTransport) SetRequestTimeout added in v1.2.2

func (t *StdioTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout sets the default timeout for request operations.

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.

type UDPOption added in v1.2.1

type UDPOption func(*udpConfig)

UDPOption is a function that configures a UDP transport. These options allow customizing the behavior of the UDP client connection.

func WithFragmentTTL added in v1.2.1

func WithFragmentTTL(ttl time.Duration) UDPOption

WithFragmentTTL sets the time-to-live for message fragments.

func WithMaxPacketSize added in v1.2.1

func WithMaxPacketSize(size int) UDPOption

WithMaxPacketSize sets the maximum UDP packet size.

func WithReadBufferSize added in v1.2.1

func WithReadBufferSize(size int) UDPOption

WithReadBufferSize sets the read buffer size.

func WithReadTimeout added in v0.1.11

func WithReadTimeout(timeout time.Duration) UDPOption

WithReadTimeout sets the read timeout.

func WithReliability added in v1.2.1

func WithReliability(enabled bool) UDPOption

WithReliability enables or disables reliability mechanisms.

func WithUDPMaxRetries added in v1.2.1

func WithUDPMaxRetries(retries int) UDPOption

WithMaxRetries sets the maximum number of reconnection attempts.

func WithUDPReconnect added in v1.2.1

func WithUDPReconnect(enabled bool) UDPOption

WithReconnect enables automatic reconnection for UDP transport.

func WithUDPReconnectDelay added in v1.2.1

func WithUDPReconnectDelay(delay time.Duration) UDPOption

WithReconnectDelay sets the delay between reconnection attempts.

func WithWriteBufferSize added in v1.2.1

func WithWriteBufferSize(size int) UDPOption

WithWriteBufferSize sets the write buffer size.

func WithWriteTimeout added in v0.1.11

func WithWriteTimeout(timeout time.Duration) UDPOption

WithWriteTimeout sets the write timeout.

type UnixSocketOption added in v1.2.1

type UnixSocketOption func(*unixConfig)

UnixSocketOption is a function that configures a Unix Domain Socket transport. These options allow customizing the behavior of the Unix Domain Socket client connection.

func WithBufferSize added in v1.2.1

func WithBufferSize(size int) UnixSocketOption

WithBufferSize sets the buffer size for socket I/O operations

func WithMaxRetries added in v1.2.1

func WithMaxRetries(maxRetries int) UnixSocketOption

WithMaxRetries sets the maximum number of reconnection attempts

func WithPermissions added in v1.2.1

func WithPermissions(permissions uint32) UnixSocketOption

WithPermissions sets the permissions for the socket file (server-side only)

func WithReconnect added in v1.2.1

func WithReconnect(enabled bool) UnixSocketOption

WithReconnect enables automatic reconnection for Unix Domain Socket transport

func WithReconnectDelay added in v1.2.1

func WithReconnectDelay(delay time.Duration) UnixSocketOption

WithReconnectDelay sets the delay between reconnection attempts

func WithTimeout added in v0.1.11

func WithTimeout(timeout time.Duration) UnixSocketOption

WithTimeout sets the timeout for Unix Domain Socket operations

type WSTransport added in v1.2.2

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

WSTransport wraps a ws.Transport to implement the client.Transport interface

func (*WSTransport) Connect added in v1.2.2

func (t *WSTransport) Connect() error

Connect establishes a connection to the server

func (*WSTransport) ConnectWithContext added in v1.2.2

func (t *WSTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext establishes a connection to the server with context

func (*WSTransport) Disconnect added in v1.2.2

func (t *WSTransport) Disconnect() error

Disconnect closes the connection to the server

func (*WSTransport) RegisterNotificationHandler added in v1.2.2

func (t *WSTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler registers a handler for server-initiated messages

func (*WSTransport) Send added in v1.2.2

func (t *WSTransport) Send(message []byte) ([]byte, error)

Send sends a message to the server and waits for a response

func (*WSTransport) SendWithContext added in v1.2.2

func (t *WSTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext sends a message with context for timeout/cancellation

func (*WSTransport) SetConnectionTimeout added in v1.2.2

func (t *WSTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout sets the default timeout for connection operations

func (*WSTransport) SetRequestTimeout added in v1.2.2

func (t *WSTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout sets the default timeout for request operations

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