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.
Index ¶
- func DefaultGRPCClientOptions() []grpc.Option
- func NewDefaultLogger() *slog.Logger
- func WithGRPCKeepAlive(time, timeout time.Duration) grpc.Option
- func WithGRPCMaxMessageSize(size int) grpc.Option
- func WithGRPCTLS(certFile, keyFile, caFile string) grpc.Option
- func WithGRPCTimeout(timeout time.Duration) grpc.Option
- type BatchError
- type BatchRequest
- type BatchRequestBuilder
- type BatchResponse
- type Client
- type ClientCapabilities
- type GRPCTransport
- func (t *GRPCTransport) Connect() error
- func (t *GRPCTransport) ConnectWithContext(ctx context.Context) error
- func (t *GRPCTransport) Disconnect() error
- func (t *GRPCTransport) RegisterNotificationHandler(handler func(method string, params []byte))
- func (t *GRPCTransport) Send(message []byte) ([]byte, error)
- func (t *GRPCTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)
- func (t *GRPCTransport) SetConnectionTimeout(timeout time.Duration)
- func (t *GRPCTransport) SetRequestTimeout(timeout time.Duration)
- type HTTPOption
- func WithHTTPClient(client *http.Client) HTTPOption
- func WithHTTPHeader(key, value string) HTTPOption
- func WithHTTPHeaders(headers map[string]string) HTTPOption
- func WithHTTPPollInterval(interval time.Duration) HTTPOption
- func WithHTTPRetry(attempts int, delay time.Duration) HTTPOption
- func WithHTTPTimeout(timeout time.Duration) HTTPOption
- type HTTPTransportAdapter
- func (t *HTTPTransportAdapter) AddHeader(key, value string)
- func (t *HTTPTransportAdapter) Connect() error
- func (t *HTTPTransportAdapter) ConnectWithContext(ctx context.Context) error
- func (t *HTTPTransportAdapter) Disconnect() error
- func (t *HTTPTransportAdapter) GetAddr() string
- func (t *HTTPTransportAdapter) RegisterNotificationHandler(handler func(method string, params []byte))
- func (t *HTTPTransportAdapter) Send(message []byte) ([]byte, error)
- func (t *HTTPTransportAdapter) SendWithContext(ctx context.Context, message []byte) ([]byte, error)
- func (t *HTTPTransportAdapter) SetClient(client *http.Client)
- func (t *HTTPTransportAdapter) SetConnectionTimeout(timeout time.Duration)
- func (t *HTTPTransportAdapter) SetPollInterval(interval time.Duration)
- func (t *HTTPTransportAdapter) SetRequestTimeout(timeout time.Duration)
- type MCPServer
- type MQTTTransport
- func (t *MQTTTransport) Connect() error
- func (t *MQTTTransport) ConnectWithContext(ctx context.Context) error
- func (t *MQTTTransport) Disconnect() error
- func (t *MQTTTransport) RegisterNotificationHandler(handler func(method string, params []byte))
- func (t *MQTTTransport) Send(message []byte) ([]byte, error)
- func (t *MQTTTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)
- func (t *MQTTTransport) SetConnectionTimeout(timeout time.Duration)
- func (t *MQTTTransport) SetRequestTimeout(timeout time.Duration)
- type MQTTTransportOption
- type NATSTransport
- func (t *NATSTransport) Connect() error
- func (t *NATSTransport) ConnectWithContext(ctx context.Context) error
- func (t *NATSTransport) Disconnect() error
- func (t *NATSTransport) RegisterNotificationHandler(handler func(method string, params []byte))
- func (t *NATSTransport) Send(message []byte) ([]byte, error)
- func (t *NATSTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)
- func (t *NATSTransport) SetConnectionTimeout(timeout time.Duration)
- func (t *NATSTransport) SetRequestTimeout(timeout time.Duration)
- type NATSTransportOption
- func WithNATSClientID(clientID string) NATSTransportOption
- func WithNATSCredentials(username, password string) NATSTransportOption
- func WithNATSSubjectPrefix(prefix string) NATSTransportOption
- func WithNATSTLS(config *natst.TLSConfig) NATSTransportOption
- func WithNATSToken(token string) NATSTransportOption
- type Option
- func WithConnectionTimeout(timeout time.Duration) Option
- func WithExperimentalCapability(name string, config interface{}) Option
- func WithGRPC(address string, options ...grpc.Option) Option
- func WithHTTP(url string, options ...HTTPOption) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMQTT(brokerURL string, options ...MQTTTransportOption) Option
- func WithNATS(serverURL string, options ...NATSTransportOption) Option
- func WithOldestProtocolVersion() Option
- func WithProtocolNegotiation(enabled bool) Option
- func WithProtocolVersion(version string) Option
- func WithRequestTimeout(timeout time.Duration) Option
- func WithRoots(roots []Root) Option
- func WithRootsCapability(enabled bool, listChanged bool) Option
- func WithSSE(url string) Option
- func WithSamplingCapability(enabled bool, config map[string]interface{}) Option
- func WithServerConfig(configPath string, serverName string) Option
- func WithServers(config ServerConfig, serverName string) Option
- func WithStdio(options ...StdioOption) Option
- func WithTransport(transport Transport) Option
- func WithUDP(address string, options ...UDPOption) Option
- func WithUnixSocket(socketPath string, options ...UnixSocketOption) Option
- func WithVersionDetector(detector *mcp.VersionDetector) Option
- func WithWSPath(path string) Option
- func WithWSPathPrefix(prefix string) Option
- func WithWebsocket(url string) Option
- type RequestOption
- type RequestOptions
- type Root
- type RootsCapability
- type SSETransport
- func (t *SSETransport) Connect() error
- func (t *SSETransport) ConnectWithContext(ctx context.Context) error
- func (t *SSETransport) Disconnect() error
- func (t *SSETransport) RegisterNotificationHandler(handler func(method string, params []byte))
- func (t *SSETransport) Send(message []byte) ([]byte, error)
- func (t *SSETransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)
- func (t *SSETransport) SetConnectionTimeout(timeout time.Duration)
- func (t *SSETransport) SetDebugEnabled(enabled bool)
- func (t *SSETransport) SetRequestTimeout(timeout time.Duration)
- type SamplingCreateMessageParams
- type SamplingHandler
- type SamplingMessage
- type SamplingMessageContent
- type SamplingModelHint
- type SamplingModelPreferences
- type SamplingOptions
- func (opts *SamplingOptions) Validate() error
- func (opts *SamplingOptions) WithChunkSize(size int) *SamplingOptions
- func (opts *SamplingOptions) WithContext(ctx context.Context) *SamplingOptions
- func (opts *SamplingOptions) WithMaxTokens(maxTokens int) *SamplingOptions
- func (opts *SamplingOptions) WithStreaming(handler func(*SamplingResponse) error) *SamplingOptions
- func (opts *SamplingOptions) WithSystemPrompt(prompt string) *SamplingOptions
- func (opts *SamplingOptions) WithTimeout(timeout time.Duration) *SamplingOptions
- type SamplingResponse
- type ServerConfig
- type ServerDefinition
- type ServerRegistry
- func (r *ServerRegistry) ApplyConfig(config ServerConfig) error
- func (r *ServerRegistry) GetClient(name string) (Client, error)
- func (r *ServerRegistry) GetServerNames() ([]string, error)
- func (r *ServerRegistry) LoadConfig(path string) error
- func (r *ServerRegistry) StartServer(name string, def ServerDefinition) error
- func (r *ServerRegistry) StopAll() error
- func (r *ServerRegistry) StopServer(name string) error
- type StdioOption
- type StdioTransport
- func (t *StdioTransport) Connect() error
- func (t *StdioTransport) ConnectWithContext(ctx context.Context) error
- func (t *StdioTransport) Disconnect() error
- func (t *StdioTransport) RegisterNotificationHandler(handler func(method string, params []byte))
- func (t *StdioTransport) Send(message []byte) ([]byte, error)
- func (t *StdioTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)
- func (t *StdioTransport) SetConnectionTimeout(timeout time.Duration)
- func (t *StdioTransport) SetRequestTimeout(timeout time.Duration)
- type TimeoutOption
- type Tool
- type Transport
- type UDPOption
- func WithFragmentTTL(ttl time.Duration) UDPOption
- func WithMaxPacketSize(size int) UDPOption
- func WithReadBufferSize(size int) UDPOption
- func WithReadTimeout(timeout time.Duration) UDPOption
- func WithReliability(enabled bool) UDPOption
- func WithUDPMaxRetries(retries int) UDPOption
- func WithUDPReconnect(enabled bool) UDPOption
- func WithUDPReconnectDelay(delay time.Duration) UDPOption
- func WithWriteBufferSize(size int) UDPOption
- func WithWriteTimeout(timeout time.Duration) UDPOption
- type UnixSocketOption
- func WithBufferSize(size int) UnixSocketOption
- func WithMaxRetries(maxRetries int) UnixSocketOption
- func WithPermissions(permissions uint32) UnixSocketOption
- func WithReconnect(enabled bool) UnixSocketOption
- func WithReconnectDelay(delay time.Duration) UnixSocketOption
- func WithTimeout(timeout time.Duration) UnixSocketOption
- type WSTransport
- func (t *WSTransport) Connect() error
- func (t *WSTransport) ConnectWithContext(ctx context.Context) error
- func (t *WSTransport) Disconnect() error
- func (t *WSTransport) RegisterNotificationHandler(handler func(method string, params []byte))
- func (t *WSTransport) Send(message []byte) ([]byte, error)
- func (t *WSTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)
- func (t *WSTransport) SetConnectionTimeout(timeout time.Duration)
- func (t *WSTransport) SetRequestTimeout(timeout time.Duration)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultGRPCClientOptions ¶ added in v1.2.1
DefaultGRPCClientOptions returns a set of default options for gRPC client.
func NewDefaultLogger ¶ added in v1.2.0
NewDefaultLogger creates a simple logger suitable for MCP clients
func WithGRPCKeepAlive ¶ added in v1.2.1
WithGRPCKeepAlive configures keepalive parameters for the gRPC transport.
func WithGRPCMaxMessageSize ¶ added in v1.2.1
WithGRPCMaxMessageSize sets the maximum message size for the gRPC transport.
func WithGRPCTLS ¶ added in v1.2.1
WithGRPCTLS configures TLS for the gRPC transport.
Types ¶
type BatchError ¶ added in v1.5.0
type BatchError struct {
// Code is the JSON-RPC error code
Code int `json:"code"`
// Message is a human-readable error message
Message string `json:"message"`
// Data contains additional error information
Data interface{} `json:"data,omitempty"`
}
BatchError represents an error within a batch response.
type BatchRequest ¶ added in v1.5.0
type BatchRequest struct {
// Method is the JSON-RPC method to call (e.g., "tools/call", "resources/read")
Method string `json:"method"`
// Params contains the parameters for the method call
Params map[string]interface{} `json:"params,omitempty"`
// ID is the request identifier. If nil, this is treated as a notification.
// Notifications do not generate responses.
ID interface{} `json:"id,omitempty"`
}
BatchRequest represents a single request within a batch operation.
type BatchRequestBuilder ¶ added in v1.5.0
type BatchRequestBuilder struct {
// contains filtered or unexported fields
}
BatchRequestBuilder provides a fluent interface for constructing batch requests.
func (*BatchRequestBuilder) AddRequest ¶ added in v1.5.0
func (b *BatchRequestBuilder) AddRequest(method string, params map[string]interface{}, id interface{}) *BatchRequestBuilder
AddRequest adds a request to the batch. For requests that expect a response, provide an ID. For notifications, set ID to nil.
func (*BatchRequestBuilder) Execute ¶ added in v1.5.0
func (b *BatchRequestBuilder) Execute(opts ...RequestOption) ([]BatchResponse, error)
Execute sends the batch request and returns the responses.
type BatchResponse ¶ added in v1.5.0
type BatchResponse struct {
// ID is the request identifier that this response corresponds to
ID interface{} `json:"id"`
// Result contains the successful result of the method call
Result interface{} `json:"result,omitempty"`
// Error contains error information if the method call failed
Error *BatchError `json:"error,omitempty"`
}
BatchResponse represents a single response within a batch operation.
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",
// })
//
// For timeout support:
// result, err := client.CallTool("translate", map[string]interface{}{
// "text": "Hello world",
// "target_language": "Spanish",
// }, client.WithRequestTimeoutOption(10*time.Second))
CallTool(name string, args map[string]interface{}, opts ...RequestOption) (interface{}, error)
// GetResource retrieves a resource from the server.
//
// The path parameter specifies the resource URI to retrieve.
//
// Example:
// resource, err := client.GetResource("/files/readme.txt")
//
// For timeout support:
// resource, err := client.GetResource("/files/readme.txt",
// client.WithRequestTimeoutOption(5*time.Second))
GetResource(path string, opts ...RequestOption) (interface{}, error)
// GetPrompt retrieves a prompt from the server.
//
// The name parameter specifies the prompt to retrieve. The variables parameter
// contains any variables to substitute in the prompt template.
//
// Example:
// prompt, err := client.GetPrompt("greeting", map[string]interface{}{
// "name": "Alice",
// })
//
// For timeout support:
// prompt, err := client.GetPrompt("greeting", map[string]interface{}{
// "name": "Alice",
// }, client.WithRequestTimeoutOption(3*time.Second))
GetPrompt(name string, variables map[string]interface{}, opts ...RequestOption) (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)
// ListTools retrieves the list of available tools from the server.
//
// This method calls the tools/list endpoint as specified in the MCP protocol.
// It automatically handles pagination internally and returns all available tools.
// The returned slice contains all available tools with their names, descriptions,
// and input schemas, which can be used for tool discovery and proxy patterns.
//
// Example:
// tools, err := client.ListTools()
// for _, tool := range tools {
// fmt.Printf("Tool: %s - %s\n", tool.Name, tool.Description)
// fmt.Printf("Schema: %+v\n", tool.InputSchema)
// }
ListTools() ([]Tool, 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
// Events returns the events subject for subscribing to client events.
//
// This provides access to the event system for monitoring client lifecycle,
// errors, and other significant events. Subscribers can listen for specific
// event types such as initialization, connection changes, and errors.
//
// Example:
// events := client.Events()
// events.Subscribe(events.TopicClientError, func(event events.ClientErrorEvent) {
// log.Printf("Client error: %s", event.Error)
// })
Events() *events.Subject
// RequestSampling initiates a sampling request to the server.
//
// This is the unified method for all sampling operations, supporting both
// regular and streaming modes through options configuration.
//
// Example:
// opts := client.NewSamplingOptions(messages, prefs).
// WithSystemPrompt("You are a helpful assistant").
// WithMaxTokens(1000)
// response, err := client.RequestSampling(opts)
//
// For streaming (protocol version 2025-03-26 only):
// opts := client.NewSamplingOptions(messages, prefs).
// WithStreaming(func(chunk *SamplingResponse) error {
// fmt.Printf("Received chunk: %s\n", chunk.Content.Text)
// return nil
// })
// response, err := client.RequestSampling(opts)
RequestSampling(opts *SamplingOptions) (*SamplingResponse, error)
// SendBatch sends multiple requests to the server in a single batch operation.
//
// This method implements JSON-RPC 2.0 batch requests, allowing multiple operations
// to be sent together for improved efficiency. The requests parameter contains
// the individual requests to include in the batch.
//
// The method returns a slice of BatchResponse objects, where each response
// corresponds to a request in the batch (excluding notifications). The order
// of responses matches the order of requests.
//
// Example:
// requests := []BatchRequest{
// {Method: "tools/call", Params: map[string]interface{}{"name": "calculator", "arguments": map[string]interface{}{"op": "add", "a": 1, "b": 2}}},
// {Method: "resources/read", Params: map[string]interface{}{"uri": "/config.json"}},
// {Method: "prompts/get", Params: map[string]interface{}{"name": "greeting", "arguments": map[string]interface{}{"name": "Alice"}}},
// }
// responses, err := client.SendBatch(requests)
// for i, response := range responses {
// if response.Error != nil {
// fmt.Printf("Request %d failed: %v\n", i, response.Error)
// } else {
// fmt.Printf("Request %d result: %v\n", i, response.Result)
// }
// }
//
// For timeout support:
// responses, err := client.SendBatch(requests, client.WithRequestTimeoutOption(30*time.Second))
SendBatch(requests []BatchRequest, opts ...RequestOption) ([]BatchResponse, error)
// BatchBuilder creates a new batch builder for constructing batch requests.
//
// The batch builder provides a fluent interface for adding multiple requests
// to a batch operation. Use AddRequest to add individual requests.
//
// Example:
// responses, err := client.BatchBuilder().
// AddRequest("tools/call", map[string]interface{}{
// "name": "calculator",
// "arguments": map[string]interface{}{"op": "add", "a": 1, "b": 2}
// }, 1).
// AddRequest("resources/read", map[string]interface{}{"uri": "/config.json"}, 2).
// AddRequest("prompts/get", map[string]interface{}{
// "name": "greeting",
// "arguments": map[string]interface{}{"name": "Alice"}
// }, 3).
// Execute()
BatchBuilder() *BatchRequestBuilder
}
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 ¶
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),
)
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 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
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
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 MCPServer ¶ added in v1.2.0
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
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
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
WithConnectionTimeout sets the client's connection timeout.
func WithExperimentalCapability ¶ added in v1.2.0
WithExperimentalCapability adds an experimental capability.
func WithGRPC ¶ added in v1.2.1
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
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
WithProtocolNegotiation enables or disables protocol version negotiation.
func WithProtocolVersion ¶ added in v1.2.0
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
WithRequestTimeout sets the client's request timeout.
func WithRootsCapability ¶ added in v1.2.0
WithRootsCapability enables or disables the roots capability.
func WithSSE ¶ added in v1.2.2
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:
- url: The SSE server URL to connect to (e.g., "sse://localhost:8080", "http://localhost:8080")
Returns:
- A client configuration option
func WithSamplingCapability ¶ added in v1.2.0
WithSamplingCapability enables or disables the sampling capability.
func WithServerConfig ¶ added in v1.2.0
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
WithTransport sets the client's transport.
func WithUDP ¶ added in v1.2.1
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
WithWSPath configures the WebSocket path for the WebSocket connection.
func WithWSPathPrefix ¶ added in v1.2.2
WithWSPathPrefix configures the path prefix for the WebSocket connection.
func WithWebsocket ¶ added in v1.2.2
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 RequestOption ¶ added in v1.5.0
type RequestOption interface {
// contains filtered or unexported methods
}
RequestOption represents an option that can be passed to client methods.
type RequestOptions ¶ added in v1.5.0
type RequestOptions struct {
// Timeout specifies the timeout for this specific request
// If not set, uses the client's default timeout
Timeout *time.Duration
// MaxTimeout specifies the maximum timeout regardless of progress notifications
// If not set, uses 2x the regular timeout as the maximum
MaxTimeout *time.Duration
// AllowProgressReset indicates whether progress notifications should reset the timeout clock
// Default is true as per MCP specification
AllowProgressReset bool
}
RequestOptions contains options for configuring individual requests
func DefaultRequestOptions ¶ added in v1.5.0
func DefaultRequestOptions() *RequestOptions
DefaultRequestOptions returns default request options
func (*RequestOptions) WithMaxTimeout ¶ added in v1.5.0
func (opts *RequestOptions) WithMaxTimeout(maxTimeout time.Duration) *RequestOptions
WithMaxTimeout sets the maximum timeout for this request
func (*RequestOptions) WithProgressReset ¶ added in v1.5.0
func (opts *RequestOptions) WithProgressReset(allow bool) *RequestOptions
WithProgressReset configures whether progress notifications reset the timeout
func (*RequestOptions) WithTimeout ¶ added in v1.5.0
func (opts *RequestOptions) WithTimeout(timeout time.Duration) *RequestOptions
WithTimeout sets the timeout for this request
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
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 SamplingCreateMessageParams ¶ added in v1.2.0
type SamplingCreateMessageParams struct {
Messages []SamplingMessage `json:"messages"`
ModelPreferences SamplingModelPreferences `json:"modelPreferences"`
SystemPrompt string `json:"systemPrompt,omitempty"`
MaxTokens int `json:"maxTokens,omitempty"`
}
SamplingCreateMessageParams represents the parameters for a sampling/createMessage request.
type SamplingHandler ¶ added in v1.2.0
type SamplingHandler func(params SamplingCreateMessageParams) (SamplingResponse, error)
SamplingHandler is a function that handles sampling/createMessage requests from the server.
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 CreateAudioMessage ¶ added in v1.5.0
func CreateAudioMessage(role, audioData, mimeType string) SamplingMessage
func CreateImageMessage ¶ added in v1.5.0
func CreateImageMessage(role, imageData, mimeType string) SamplingMessage
func CreateTextMessage ¶ added in v1.5.0
func CreateTextMessage(role, text string) SamplingMessage
Convenience functions for creating messages
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 SamplingOptions ¶ added in v1.5.0
type SamplingOptions struct {
// Core request parameters
Messages []SamplingMessage
ModelPreferences SamplingModelPreferences
SystemPrompt string
MaxTokens int
// Request configuration
Context context.Context
Timeout time.Duration
ProtocolVersion string
// Streaming options (only for protocol version 2025-03-26)
Streaming bool
StreamHandler func(*SamplingResponse) error // Called for each chunk when streaming
ChunkSize int // Maximum size of text chunks
MaxChunks int // Maximum number of chunks (0 for unlimited)
StopOnComplete bool // Stop streaming when isComplete=true
// Retry configuration
MaxRetries int
RetryInterval time.Duration
RetryMultiplier float64
MaxInterval time.Duration
}
SamplingOptions configures how sampling requests are made.
func DefaultSamplingOptions ¶ added in v1.5.0
func DefaultSamplingOptions() *SamplingOptions
DefaultSamplingOptions returns default sampling options.
func NewSamplingOptions ¶ added in v1.5.0
func NewSamplingOptions(messages []SamplingMessage, prefs SamplingModelPreferences) *SamplingOptions
NewSamplingOptions creates new sampling options with the given messages and preferences.
func (*SamplingOptions) Validate ¶ added in v1.5.0
func (opts *SamplingOptions) Validate() error
Validate validates the sampling options.
func (*SamplingOptions) WithChunkSize ¶ added in v1.5.0
func (opts *SamplingOptions) WithChunkSize(size int) *SamplingOptions
WithChunkSize sets the chunk size for streaming (only for streaming mode).
func (*SamplingOptions) WithContext ¶ added in v1.5.0
func (opts *SamplingOptions) WithContext(ctx context.Context) *SamplingOptions
WithContext sets the context for the sampling request.
func (*SamplingOptions) WithMaxTokens ¶ added in v1.5.0
func (opts *SamplingOptions) WithMaxTokens(maxTokens int) *SamplingOptions
WithMaxTokens sets the maximum tokens for the sampling request.
func (*SamplingOptions) WithStreaming ¶ added in v1.5.0
func (opts *SamplingOptions) WithStreaming(handler func(*SamplingResponse) error) *SamplingOptions
WithStreaming enables streaming mode (only available in protocol version 2025-03-26).
func (*SamplingOptions) WithSystemPrompt ¶ added in v1.5.0
func (opts *SamplingOptions) WithSystemPrompt(prompt string) *SamplingOptions
WithSystemPrompt sets the system prompt for the sampling request.
func (*SamplingOptions) WithTimeout ¶ added in v1.5.0
func (opts *SamplingOptions) WithTimeout(timeout time.Duration) *SamplingOptions
WithTimeout sets the timeout for the sampling 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"`
// Streaming fields
IsComplete bool `json:"isComplete,omitempty"` // Only for streaming responses
ChunkIndex int `json:"chunkIndex,omitempty"` // Only for streaming responses
}
SamplingResponse represents the response to a sampling request.
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
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 TimeoutOption ¶ added in v1.5.0
TimeoutOption creates a request option that sets a timeout for the request.
func WithRequestTimeoutOption ¶ added in v1.5.0
func WithRequestTimeoutOption(d time.Duration) TimeoutOption
WithRequestTimeoutOption creates a TimeoutOption from a duration.
type Tool ¶ added in v1.3.1
Tool is an alias to the shared mcp.Tool type for backward compatibility.
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
WithFragmentTTL sets the time-to-live for message fragments.
func WithMaxPacketSize ¶ added in v1.2.1
WithMaxPacketSize sets the maximum UDP packet size.
func WithReadBufferSize ¶ added in v1.2.1
WithReadBufferSize sets the read buffer size.
func WithReadTimeout ¶ added in v0.1.11
WithReadTimeout sets the read timeout.
func WithReliability ¶ added in v1.2.1
WithReliability enables or disables reliability mechanisms.
func WithUDPMaxRetries ¶ added in v1.2.1
WithMaxRetries sets the maximum number of reconnection attempts.
func WithUDPReconnect ¶ added in v1.2.1
WithReconnect enables automatic reconnection for UDP transport.
func WithUDPReconnectDelay ¶ added in v1.2.1
WithReconnectDelay sets the delay between reconnection attempts.
func WithWriteBufferSize ¶ added in v1.2.1
WithWriteBufferSize sets the write buffer size.
func WithWriteTimeout ¶ added in v0.1.11
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
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
Source Files
¶
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. |