client

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: May 12, 2025 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package client provides a high-level client API for interacting with MCP servers. It builds on the existing transport and hooks infrastructure to provide a simple, fluent interface for client applications.

Index

Constants

View Source
const (
	ProtocolVersion2024   = "2024-11-05"
	ProtocolVersion2025   = "2025-03-26"
	LatestProtocolVersion = ProtocolVersion2025
)

Protocol version constants

Variables

View Source
var (
	ErrNotConnected     = errors.New("client is not connected")
	ErrAlreadyConnected = errors.New("client is already connected")
	ErrRequestTimeout   = errors.New("request timed out")
	ErrVersionMismatch  = errors.New("protocol version mismatch")
	ErrAuthFailure      = errors.New("authentication failed")
	ErrTransportFailure = errors.New("transport failure")
	ErrInvalidResponse  = errors.New("invalid response from server")
	ErrServerError      = errors.New("server reported error")
	ErrCancelled        = errors.New("operation was cancelled")
)

Standard error types that can be used with errors.Is()

View Source
var ErrServerNotFound = fmt.Errorf("server not found")

ErrServerNotFound is returned when a specified server is not found

Functions

func IsConnectionError added in v0.1.11

func IsConnectionError(err error) bool

IsConnectionError checks if an error is a connection error

func IsServerError added in v0.1.11

func IsServerError(err error) bool

IsServerError checks if an error is a server-reported error

func IsTimeoutError added in v0.1.11

func IsTimeoutError(err error) bool

IsTimeoutError checks if an error is a timeout error

func IsTransportError added in v0.1.11

func IsTransportError(err error) bool

IsTransportError checks if an error is a transport error

func NewAuthError added in v0.1.11

func NewAuthError(message, serverMessage string, cause error) error

NewAuthError creates a new authentication error

func NewClientError added in v0.1.11

func NewClientError(message string, code int, cause error) error

NewClientError creates a new ClientError

func NewConnectionError added in v0.1.11

func NewConnectionError(endpoint, message string, cause error) error

NewConnectionError creates a new ConnectionError

func NewServerError added in v0.1.11

func NewServerError(method, serverID string, code int, message string, cause error) error

NewServerError creates a new ServerError

func NewTimeoutError added in v0.1.11

func NewTimeoutError(operation string, timeout time.Duration, cause error) error

NewTimeoutError creates a new TimeoutError

func NewTransportError added in v0.1.11

func NewTransportError(transport, message string, cause error) error

NewTransportError creates a new TransportError

Types

type AuthProvider added in v0.1.11

type AuthProvider interface {
	GetAuthHeaders() map[string]string
	GetAuthToken() string
}

AuthProvider supplies authentication information

func NewBasicAuth added in v0.1.11

func NewBasicAuth(username, password string) AuthProvider

NewBasicAuth creates a new Basic auth provider

func NewBearerAuth added in v0.1.11

func NewBearerAuth(token string) AuthProvider

NewBearerAuth creates a new Bearer token auth provider

func NewCustomHeaderAuth added in v0.1.11

func NewCustomHeaderAuth(headers map[string]string, token string) AuthProvider

NewCustomHeaderAuth creates a new custom header auth provider

func NewNoAuth added in v0.1.11

func NewNoAuth() AuthProvider

NewNoAuth creates a new no-auth provider

type BackoffStrategy added in v0.1.11

type BackoffStrategy interface {
	NextDelay(attempt int) time.Duration
	MaxAttempts() int
}

BackoffStrategy defines how to handle retries and delays

type Client

type Client interface {
	// Connection Management
	Connect(ctx context.Context) error
	Close() error
	IsConnected() bool
	Run(ctx context.Context) error
	Cleanup() // New method for explicit graceful cleanup

	// MCP Methods - High-level API
	ListTools(ctx context.Context) ([]protocol.Tool, error)
	CallTool(ctx context.Context, name string, args map[string]interface{}, progressCh chan<- protocol.ProgressParams) ([]protocol.Content, error)
	ListResources(ctx context.Context) ([]protocol.Resource, error)
	ReadResource(ctx context.Context, uri string) ([]protocol.ResourceContents, error)
	ListPrompts(ctx context.Context) ([]protocol.Prompt, error)
	GetPrompt(ctx context.Context, name string, args map[string]interface{}) ([]protocol.PromptMessage, error)

	// Server Information
	ServerInfo() protocol.Implementation
	ServerCapabilities() protocol.ServerCapabilities

	// Raw Protocol Access
	SendRequest(ctx context.Context, method string, params interface{}) (*protocol.JSONRPCResponse, error)

	// Configuration methods (fluent interface)
	WithTimeout(timeout time.Duration) Client
	WithRetry(maxAttempts int, backoff BackoffStrategy) Client
	WithMiddleware(middleware ClientMiddleware) Client
	WithAuth(auth AuthProvider) Client
	WithLogger(logger logx.Logger) Client

	// Notification registration methods
	OnNotification(method string, handler NotificationHandler) Client
	OnProgress(handler ProgressHandler) Client
	OnResourceUpdate(uri string, handler ResourceUpdateHandler) Client
	OnLog(handler LogHandler) Client
	OnConnectionStatus(handler ConnectionStatusHandler) Client
}

Client is the interface for a single MCP server connection

func CreateClient added in v0.1.11

func CreateClient(nameOrURL string, logger logx.Logger, options ...ClientOption) (Client, error)

CreateClient creates a new client with automatic transport detection

func CreateInMemoryClient added in v0.1.11

func CreateInMemoryClient(server interface{}, logger logx.Logger, options ...ClientOption) (Client, error)

CreateInMemoryClient creates a client that connects to an in-memory server

func CreateSSEClient added in v0.1.11

func CreateSSEClient(baseURL, basePath string, logger logx.Logger, options ...ClientOption) (Client, error)

CreateSSEClient creates a client that connects via HTTP/SSE

func CreateStdioClient added in v0.1.11

func CreateStdioClient(name string, logger logx.Logger, options ...ClientOption) (Client, error)

CreateStdioClient creates a client that connects via stdio

func CreateWebSocketClient added in v0.1.11

func CreateWebSocketClient(serverURL string, logger logx.Logger, options ...ClientOption) (Client, error)

CreateWebSocketClient creates a client that connects via WebSocket

func NewClient

func NewClient(nameOrURL string, options ...ClientOption) (Client, error)

NewClient creates a new client with automatic transport detection

func NewClientFromConfig added in v0.1.11

func NewClientFromConfig(config *McpConfig, serverName string, options ...ClientOption) (Client, error)

NewClientFromConfig creates a new MCP client from a named server in the config

func NewClientFromJSON added in v0.1.11

func NewClientFromJSON(jsonData []byte, serverName string, processor ConfigProcessor, options ...ClientOption) (Client, error)

NewClientFromJSON creates a client directly from JSON configuration

func NewClientFromServer added in v0.1.11

func NewClientFromServer(server McpServer, options ...ClientOption) (Client, error)

NewClientFromServer creates a new MCP client from a server configuration

func NewClientFromServerName added in v0.1.11

func NewClientFromServerName(serverName string, processor ConfigProcessor, options ...ClientOption) (Client, error)

Quick helper to create a client from the default config and server name

func NewInMemoryClient added in v0.1.11

func NewInMemoryClient(name string, server interface{}, options ...ClientOption) (Client, error)

NewInMemoryClient creates a client that connects to an in-memory server

func NewSSEClient added in v0.1.11

func NewSSEClient(name, baseURL, basePath string, options ...ClientOption) (Client, error)

NewSSEClient creates a client that connects via HTTP/SSE

func NewStdioClient added in v0.1.11

func NewStdioClient(name string, options ...ClientOption) (Client, error)

NewStdioClient creates a client that connects via stdio

func NewWebSocketClient added in v0.1.11

func NewWebSocketClient(name, serverURL string, options ...ClientOption) (Client, error)

NewWebSocketClient creates a client that connects via WebSocket

type ClientConfig added in v0.1.11

type ClientConfig struct {
	Name                     string
	Logger                   logx.Logger
	Capabilities             protocol.ClientCapabilities
	PreferredProtocolVersion string
	TransportOptions         types.TransportOptions
	DefaultTimeout           time.Duration
	RetryStrategy            BackoffStrategy
	Middleware               []ClientMiddleware
	Hooks                    ClientHooks
	AuthProvider             AuthProvider
	Endpoint                 string
	ServerName               string
}

ClientConfig holds the configuration for a client

type ClientError added in v0.1.11

type ClientError struct {
	Message string
	Code    int
	Cause   error
}

ClientError is the base error type for client errors

func (*ClientError) Error added in v0.1.11

func (e *ClientError) Error() string

Error implements the error interface

func (*ClientError) Unwrap added in v0.1.11

func (e *ClientError) Unwrap() error

Unwrap returns the underlying cause

type ClientHooks added in v0.1.11

type ClientHooks struct {
	BeforeSendRequest        []hooks.ClientBeforeSendRequestHook
	BeforeSendNotification   []hooks.ClientBeforeSendNotificationHook
	OnReceiveRawMessage      []hooks.OnReceiveRawMessageHook
	BeforeHandleResponse     []hooks.ClientBeforeHandleResponseHook
	BeforeHandleNotification []hooks.ClientBeforeHandleNotificationHook
	BeforeHandleRequest      []hooks.ClientBeforeHandleRequestHook
}

ClientHooks holds the various hook functions for the client

type ClientMiddleware added in v0.1.11

type ClientMiddleware interface {
	BeforeSendRequest(ctx context.Context, req *protocol.JSONRPCRequest) (*protocol.JSONRPCRequest, error)
	AfterReceiveResponse(ctx context.Context, resp *protocol.JSONRPCResponse) (*protocol.JSONRPCResponse, error)
}

ClientMiddleware intercepts client operations

func NewAuthMiddleware added in v0.1.11

func NewAuthMiddleware(authProvider AuthProvider) ClientMiddleware

NewAuthMiddleware creates a new authentication middleware

func NewLoggingMiddleware added in v0.1.11

func NewLoggingMiddleware(logger logx.Logger) ClientMiddleware

NewLoggingMiddleware creates a new logging middleware

func NewMiddlewareChain added in v0.1.11

func NewMiddlewareChain(middleware ...ClientMiddleware) ClientMiddleware

NewMiddlewareChain creates a new middleware chain

func NewRetryMiddleware added in v0.1.11

func NewRetryMiddleware(backoff BackoffStrategy) ClientMiddleware

NewRetryMiddleware creates a new retry middleware

func NewTimeoutMiddleware added in v0.1.11

func NewTimeoutMiddleware(timeout time.Duration) ClientMiddleware

NewTimeoutMiddleware creates a new timeout middleware

type ClientOption added in v0.1.11

type ClientOption func(*ClientConfig)

ClientOption is a function that configures a ClientConfig

func WithAuth added in v0.1.11

func WithAuth(auth AuthProvider) ClientOption

WithAuth sets the auth provider for the client

func WithEndpoint added in v0.1.11

func WithEndpoint(endpoint string) ClientOption

WithEndpoint sets the endpoint for the client

func WithFollowRedirects added in v0.1.11

func WithFollowRedirects(follow bool) ClientOption

WithFollowRedirects configures whether to follow HTTP redirects for SSE connections. This is especially useful when the server redirects from the base path to the SSE endpoint.

func WithLogger added in v0.1.11

func WithLogger(logger logx.Logger) ClientOption

WithLogger sets the logger for the client

func WithMiddleware added in v0.1.11

func WithMiddleware(middleware ClientMiddleware) ClientOption

WithMiddleware adds middleware to the client

func WithPreferredProtocolVersion added in v0.1.11

func WithPreferredProtocolVersion(version string) ClientOption

WithPreferredProtocolVersion sets the preferred protocol version for the client

func WithRetryStrategy added in v0.1.11

func WithRetryStrategy(strategy BackoffStrategy) ClientOption

WithRetryStrategy sets the retry strategy for the client

func WithServer added in v0.1.11

func WithServer(serverName string) ClientOption

WithServer sets the server name to connect to from the config file

func WithStdioArgs added in v0.1.11

func WithStdioArgs(args []string) ClientOption

WithStdioArgs is a helper option for stdio clients

func WithTimeout added in v0.1.11

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the default timeout for requests

type ClientTransport added in v0.1.11

type ClientTransport interface {
	// Connection management
	Connect(ctx context.Context) error
	Close() error
	IsConnected() bool

	// Synchronous request/response
	SendRequest(ctx context.Context, req *protocol.JSONRPCRequest) (*protocol.JSONRPCResponse, error)

	// Asynchronous request/response and notification handling
	SendRequestAsync(ctx context.Context, req *protocol.JSONRPCRequest, responseCh chan<- *protocol.JSONRPCResponse) error
	SetNotificationHandler(handler NotificationHandler)

	// Transport-specific properties
	GetTransportType() TransportType
	GetTransportInfo() map[string]interface{}
}

ClientTransport handles the actual communication with the server

func NewInMemoryTransport added in v0.1.11

func NewInMemoryTransport(logger logx.Logger, serverHandler ServerRequestHandler, options ...TransportOption) (ClientTransport, error)

NewInMemoryTransport creates a new in-memory transport

func NewSSETransport added in v0.1.11

func NewSSETransport(baseURL, basePath string, logger logx.Logger, options ...TransportOption) (ClientTransport, error)

NewSSETransport creates a new SSE transport

func NewStdioTransport added in v0.1.11

func NewStdioTransport(command string, args []string, logger logx.Logger, options ...TransportOption) (ClientTransport, error)

NewStdioTransport creates a new stdio transport

func NewTCPTransport added in v0.1.11

func NewTCPTransport(addr string, logger logx.Logger, options ...TransportOption) (ClientTransport, error)

NewTCPTransport creates a new TCP transport

func NewWebSocketTransport added in v0.1.11

func NewWebSocketTransport(baseURL, basePath string, logger logx.Logger, options ...TransportOption) (ClientTransport, error)

NewWebSocketTransport creates a new WebSocket transport

type ConfigProcessor added in v0.1.11

type ConfigProcessor func(*McpConfig) error

ConfigProcessor is a function that can modify or extend a McpConfig after loading

type ConnectionError added in v0.1.11

type ConnectionError struct {
	ClientError
	Endpoint string
}

ConnectionError indicates a connection issue

func (*ConnectionError) Error added in v0.1.11

func (e *ConnectionError) Error() string

Error implements the error interface

type ConnectionStatusHandler added in v0.1.11

type ConnectionStatusHandler func(connected bool) error

ConnectionStatusHandler processes connection status changes

type ConstantBackoff added in v0.1.11

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

ConstantBackoff implements BackoffStrategy with fixed delay between attempts

func NewConstantBackoff added in v0.1.11

func NewConstantBackoff(delay time.Duration, maxAttempts int) *ConstantBackoff

NewConstantBackoff creates a new constant backoff strategy

func (*ConstantBackoff) MaxAttempts added in v0.1.11

func (b *ConstantBackoff) MaxAttempts() int

MaxAttempts implements BackoffStrategy.MaxAttempts

func (*ConstantBackoff) NextDelay added in v0.1.11

func (b *ConstantBackoff) NextDelay(attempt int) time.Duration

NextDelay implements BackoffStrategy.NextDelay

func (*ConstantBackoff) WithJitter added in v0.1.11

func (b *ConstantBackoff) WithJitter(jitter float64) *ConstantBackoff

WithJitter sets the jitter factor to randomize delays (default 0.1 - 10%)

type ExponentialBackoff added in v0.1.11

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

ExponentialBackoff implements BackoffStrategy with exponential delay between attempts

func NewExponentialBackoff added in v0.1.11

func NewExponentialBackoff(initialDelay, maxDelay time.Duration, maxAttempts int) *ExponentialBackoff

NewExponentialBackoff creates a new exponential backoff strategy

func (*ExponentialBackoff) MaxAttempts added in v0.1.11

func (b *ExponentialBackoff) MaxAttempts() int

MaxAttempts implements BackoffStrategy.MaxAttempts

func (*ExponentialBackoff) NextDelay added in v0.1.11

func (b *ExponentialBackoff) NextDelay(attempt int) time.Duration

NextDelay implements BackoffStrategy.NextDelay

func (*ExponentialBackoff) WithFactor added in v0.1.11

func (b *ExponentialBackoff) WithFactor(factor float64) *ExponentialBackoff

WithFactor sets the exponential factor (default 2.0)

func (*ExponentialBackoff) WithJitter added in v0.1.11

func (b *ExponentialBackoff) WithJitter(jitter float64) *ExponentialBackoff

WithJitter sets the jitter factor to randomize delays (default 0.2 - 20%)

func (*ExponentialBackoff) WithResetOnPause added in v0.1.11

func (b *ExponentialBackoff) WithResetOnPause(reset bool) *ExponentialBackoff

WithResetOnPause controls whether the backoff resets after a long pause

type LogHandler added in v0.1.11

type LogHandler func(level protocol.LoggingLevel, message string) error

LogHandler processes log messages

type MCP added in v0.1.11

type MCP struct {
	Servers map[string]Client
	// contains filtered or unexported fields
}

MCP provides a simple interface for working with multiple MCP servers

func New added in v0.1.11

func New(config *McpConfig, options ...ClientOption) (*MCP, error)

New creates a new MCP client manager from a config

Example:

config, err := client.LoadFromFile(configPath, nil)
mcp, err := client.New(config, client.WithTimeout(30*time.Second))

// Configure with fluent interface
mcp.Roots([]string{"./path1", "./path2"}).
	Logger(logx.NewDefaultLogger()).
	WithContext(ctx)

// Connect and use
mcp.Connect()
tools := mcp.ListTools()

func (*MCP) CallTool added in v0.1.11

func (m *MCP) CallTool(serverName, toolName string, args map[string]interface{}) ([]protocol.Content, error)

CallTool calls a tool on a specific server

func (*MCP) CheckConnectionStatus added in v0.1.11

func (m *MCP) CheckConnectionStatus()

CheckConnectionStatus logs detailed information about the connection status of all servers

func (*MCP) Close added in v0.1.11

func (m *MCP) Close()

Close disconnects from all servers

func (*MCP) Connect added in v0.1.11

func (m *MCP) Connect() error

Connect connects to all servers This is now non-blocking and will attempt connections in the background

func (*MCP) ConnectionErrors added in v0.1.11

func (m *MCP) ConnectionErrors() <-chan ServerConnectionError

ConnectionErrors returns a read-only channel that receives connection errors Callers can use this to monitor which servers failed to connect

func (*MCP) IsConnected added in v0.1.11

func (m *MCP) IsConnected() bool

IsConnected returns true if at least one server is connected

func (*MCP) ListResources added in v0.1.11

func (m *MCP) ListResources() map[string][]protocol.Resource

ListResources returns all resources from all servers This is a convenience method that calls ListResources on each server

func (*MCP) ListTools added in v0.1.11

func (m *MCP) ListTools() map[string][]protocol.Tool

ListTools returns all tools from all servers This is a convenience method that calls ListTools on each server

func (*MCP) ListToolsAsync added in v0.1.11

func (m *MCP) ListToolsAsync(resultCh chan<- map[string][]protocol.Tool, timeout time.Duration)

ListToolsAsync lists tools from all servers asynchronously It returns immediately with an empty map and pushes results to the provided channel as they arrive

func (*MCP) ListToolsWithTimeout added in v0.1.11

func (m *MCP) ListToolsWithTimeout(timeout time.Duration) map[string][]protocol.Tool

ListToolsWithTimeout returns all tools from all servers with a timeout This is a convenience method that calls ListTools on each server with a timeout

func (*MCP) Logger added in v0.1.11

func (m *MCP) Logger(logger logx.Logger) *MCP

Logger sets the logger for the MCP

func (*MCP) ReadResource added in v0.1.11

func (m *MCP) ReadResource(serverName, uri string) ([]protocol.ResourceContents, error)

ReadResource reads a resource from a specific server

func (*MCP) Roots added in v0.1.11

func (m *MCP) Roots(paths []string) *MCP

Roots sets the root directories for the MCP

func (*MCP) WaitForConnections added in v0.1.11

func (m *MCP) WaitForConnections(timeout time.Duration) bool

WaitForConnections blocks until all servers have attempted to connect with an optional timeout. Returns true if all servers connected successfully, false if there were errors or the timeout was reached.

func (*MCP) WithContext added in v0.1.11

func (m *MCP) WithContext(ctx context.Context) *MCP

WithContext sets the context for all operations

type MCPConfig added in v0.1.11

type MCPConfig struct {
	MCPServers map[string]MCPServerConfig `json:"mcpServers"`
}

Configuration file structure

type MCPServerConfig added in v0.1.11

type MCPServerConfig struct {
	Command string   `json:"command"`
	Args    []string `json:"args"`
}

Server configuration from config file

type McpConfig added in v0.1.11

type McpConfig struct {
	McpServers map[string]McpServer `json:"mcpServers"`
	// Custom properties for extension
	CustomProperties map[string]interface{} `json:"customProperties,omitempty"`
}

McpConfig is the top-level configuration structure

func LoadDefaultConfig added in v0.1.11

func LoadDefaultConfig(processor ConfigProcessor) (*McpConfig, error)

LoadDefaultConfig looks for and loads the default configuration file (~/.cursor/mcp.json) The optional processor callback can be used to customize the loaded config

func LoadFromFile added in v0.1.11

func LoadFromFile(path string, processor ConfigProcessor) (*McpConfig, error)

LoadFromFile loads an MCP configuration from a file path The optional processor callback can be used to customize the loaded config

func LoadFromJSON added in v0.1.11

func LoadFromJSON(data []byte, processor ConfigProcessor) (*McpConfig, error)

LoadFromJSON parses MCP configuration from JSON data The optional processor callback can be used to customize the loaded config

func (*McpConfig) AddServer added in v0.1.11

func (c *McpConfig) AddServer(name string, server McpServer)

AddServer adds a server to the configuration

func (*McpConfig) GetServer added in v0.1.11

func (c *McpConfig) GetServer(name string) (McpServer, error)

GetServer retrieves a server configuration by name

func (*McpConfig) RemoveServer added in v0.1.11

func (c *McpConfig) RemoveServer(name string) bool

RemoveServer removes a server from the configuration

type McpServer added in v0.1.11

type McpServer struct {
	// Connection can be established either via a command or URL
	Command string   `json:"command,omitempty"`
	Args    []string `json:"args,omitempty"`
	URL     string   `json:"url,omitempty"`

	// Optional server identity
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`

	// Transport specific options
	Transport string `json:"transport,omitempty"` // Can be "websocket", "sse", "stdio", "auto"
	BasePath  string `json:"basePath,omitempty"`  // For URL-based transports
	Timeout   int    `json:"timeout,omitempty"`   // Connection timeout in seconds

	// Allow extensions by embedding arbitrary JSON properties
	Properties map[string]interface{} `json:"properties,omitempty"`
}

McpServer defines a server configuration

func CreateSSEServerConfig added in v0.1.11

func CreateSSEServerConfig(name, url string, basePath string) McpServer

CreateSSEServerConfig creates a McpServer configuration for an SSE/HTTP server

func CreateStdioServerConfig added in v0.1.11

func CreateStdioServerConfig(name, command string, args []string) McpServer

CreateStdioServerConfig creates a McpServer configuration for a stdio server

func CreateWebSocketServerConfig added in v0.1.11

func CreateWebSocketServerConfig(name, url string, basePath string) McpServer

CreateWebSocketServerConfig creates a McpServer configuration for a WebSocket server

type MiddlewareChain added in v0.1.11

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

MiddlewareChain chains multiple middleware together

func (*MiddlewareChain) AfterReceiveResponse added in v0.1.11

func (c *MiddlewareChain) AfterReceiveResponse(ctx context.Context, resp *protocol.JSONRPCResponse) (*protocol.JSONRPCResponse, error)

AfterReceiveResponse implements ClientMiddleware.AfterReceiveResponse

func (*MiddlewareChain) BeforeSendRequest added in v0.1.11

func (c *MiddlewareChain) BeforeSendRequest(ctx context.Context, req *protocol.JSONRPCRequest) (*protocol.JSONRPCRequest, error)

BeforeSendRequest implements ClientMiddleware.BeforeSendRequest

type NoBackoff added in v0.1.11

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

NoBackoff implements BackoffStrategy with no delay between attempts

func NewNoBackoff added in v0.1.11

func NewNoBackoff(maxAttempts int) *NoBackoff

NewNoBackoff creates a new no-backoff strategy

func (*NoBackoff) MaxAttempts added in v0.1.11

func (b *NoBackoff) MaxAttempts() int

MaxAttempts implements BackoffStrategy.MaxAttempts

func (*NoBackoff) NextDelay added in v0.1.11

func (b *NoBackoff) NextDelay(attempt int) time.Duration

NextDelay implements BackoffStrategy.NextDelay

type NotificationHandler added in v0.1.11

type NotificationHandler func(notification *protocol.JSONRPCNotification) error

NotificationHandler processes incoming notifications

type ProgressHandler added in v0.1.11

type ProgressHandler func(progress *protocol.ProgressParams) error

ProgressHandler processes progress updates

type ProtocolHandler added in v0.1.11

type ProtocolHandler interface {
	// Common operations with version-specific implementations
	FormatRequest(method string, params interface{}) (*protocol.JSONRPCRequest, error)
	ParseResponse(resp *protocol.JSONRPCResponse) (interface{}, error)
	FormatCallToolRequest(name string, args map[string]interface{}) (interface{}, error)
	ParseCallToolResult(result interface{}) ([]protocol.Content, error)
}

ProtocolHandler abstracts version-specific behavior

type ResourceUpdateHandler added in v0.1.11

type ResourceUpdateHandler func(uri string) error

ResourceUpdateHandler processes resource update notifications

type ServerConnectionError added in v0.1.11

type ServerConnectionError struct {
	ServerName string
	Err        error // Changed from Error to Err to avoid conflict
}

ServerConnectionError represents an error connecting to a specific server

type ServerError added in v0.1.11

type ServerError struct {
	ClientError
	Method   string
	ServerID string
}

ServerError represents an error returned by the server

func (*ServerError) Error added in v0.1.11

func (e *ServerError) Error() string

Error implements the error interface

type ServerRequestHandler added in v0.1.11

type ServerRequestHandler func(req *protocol.JSONRPCRequest) *protocol.JSONRPCResponse

ServerRequestHandler defines a function that handles requests sent to the in-memory server

func DefaultServerHandler added in v0.1.11

func DefaultServerHandler(tools []protocol.Tool, resources []protocol.Resource, prompts []protocol.Prompt) ServerRequestHandler

DefaultServerHandler returns a default server handler that processes common MCP requests

type TimeoutError added in v0.1.11

type TimeoutError struct {
	ClientError
	Operation string
	Timeout   time.Duration
}

TimeoutError indicates a timeout

func (*TimeoutError) Error added in v0.1.11

func (e *TimeoutError) Error() string

Error implements the error interface

type TransportError added in v0.1.11

type TransportError struct {
	ClientError
	Transport string
}

TransportError indicates a problem with the transport layer

func (*TransportError) Error added in v0.1.11

func (e *TransportError) Error() string

Error implements the error interface

type TransportOption added in v0.1.11

type TransportOption func(options *TransportOptions)

TransportOption configures a transport

func WithConnectTimeout added in v0.1.11

func WithConnectTimeout(timeout time.Duration) TransportOption

WithConnectTimeout sets the connection timeout for the transport

func WithHTTPClient added in v0.1.11

func WithHTTPClient(client *http.Client) TransportOption

WithHTTPClient sets the HTTP client for the transport

func WithHeaders added in v0.1.11

func WithHeaders(headers http.Header) TransportOption

WithHeaders sets the HTTP headers for the transport

func WithInMemoryServer added in v0.1.11

func WithInMemoryServer(server interface{}) TransportOption

WithInMemoryServer sets the server for the in-memory transport

func WithKeepAlive added in v0.1.11

func WithKeepAlive(keepAlive bool) TransportOption

WithKeepAlive sets whether to use keep-alive for the transport

func WithReadTimeout added in v0.1.11

func WithReadTimeout(timeout time.Duration) TransportOption

WithReadTimeout sets the read timeout for the transport

func WithRequestTimeout added in v0.1.11

func WithRequestTimeout(timeout time.Duration) TransportOption

WithRequestTimeout sets the request timeout for the transport

func WithSSELastEventID added in v0.1.11

func WithSSELastEventID(id string) TransportOption

WithSSELastEventID sets the last event ID for the SSE transport

func WithStdioReaderWriter added in v0.1.11

func WithStdioReaderWriter(reader io.Reader, writer io.Writer, closeFunc func() error) TransportOption

WithStdioReaderWriter sets the reader and writer for the stdio transport

func WithTransportAuth added in v0.1.11

func WithTransportAuth(authProvider AuthProvider) TransportOption

WithTransportAuth sets the authentication provider for the transport

func WithTransportRetryStrategy added in v0.1.11

func WithTransportRetryStrategy(strategy BackoffStrategy) TransportOption

WithTransportRetryStrategy sets the retry strategy for the transport

func WithWebSocketCompression added in v0.1.11

func WithWebSocketCompression(compression bool) TransportOption

WithWebSocketCompression enables or disables WebSocket compression

func WithWebSocketProtocols added in v0.1.11

func WithWebSocketProtocols(protocols []string) TransportOption

WithWebSocketProtocols sets the WebSocket protocols

func WithWriteTimeout added in v0.1.11

func WithWriteTimeout(timeout time.Duration) TransportOption

WithWriteTimeout sets the write timeout for the transport

type TransportOptions added in v0.1.11

type TransportOptions struct {
	Headers        http.Header
	AuthProvider   AuthProvider
	HTTPClient     *http.Client
	RequestTimeout time.Duration
	ReadTimeout    time.Duration
	WriteTimeout   time.Duration
	KeepAlive      bool
	ConnectTimeout time.Duration
	RetryStrategy  BackoffStrategy

	// SSE-specific options
	SSELastEventID string

	// WebSocket-specific options
	WebSocketProtocols   []string
	WebSocketCompression bool

	// Stdio-specific options
	StdioReader    io.Reader
	StdioWriter    io.Writer
	StdioCloseFunc func() error

	// InMemory-specific options
	InMemoryServer interface{} // Will be *server.Server in real usage
}

TransportOptions holds configuration for transports

func DefaultTransportOptions added in v0.1.11

func DefaultTransportOptions() *TransportOptions

DefaultTransportOptions returns the default transport options

type TransportType added in v0.1.11

type TransportType string

TransportType represents the type of transport

const (
	TransportTypeSSE       TransportType = "sse"
	TransportTypeWebSocket TransportType = "websocket"
	TransportTypeStdio     TransportType = "stdio"
	TransportTypeInMemory  TransportType = "inmemory"
	TransportTypeTCP       TransportType = "tcp"
)

Transport types

Jump to

Keyboard shortcuts

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