client

package
v0.0.0-...-0d9909e Latest Latest
Warning

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

Go to latest
Published: May 5, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package client provides client implementations for the Model Context Protocol.

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultRequestTimeout        = 30 * time.Second
	DefaultInitializationTimeout = 60 * time.Second
	DefaultClientInfo            = spec.Implementation{
		Name:    "Go MCP Client",
		Version: "1.0.0",
	}
)

Default configuration values

View Source
var (
	// ErrSessionClosed is returned when attempting to use a closed session
	ErrSessionClosed = errors.New("session is closed")

	// ErrResponseWithoutID is returned when receiving a response without an ID
	ErrResponseWithoutID = errors.New("response without ID")

	// ErrResponseWithoutResultOrError is returned when receiving a response without a result or error
	ErrResponseWithoutResultOrError = errors.New("response without result or error")

	// ErrTimeout is returned when a request times out
	ErrTimeout = errors.New("request timed out")
)

Functions

func NewClientSession

func NewClientSession(transport spec.McpClientTransport, defaultTimeout time.Duration) (spec.McpClientSession, error)

NewClientSession creates a new client session with the given transport

Types

type AsyncBuilder

type AsyncBuilder interface {
	Builder

	// WithSampling sets the sampling handler.
	WithSampling(handler AsyncSamplingHandler) AsyncBuilder

	// Build creates a new McpAsyncClient with the configured settings.
	Build() McpAsyncClient
}

AsyncBuilder extends Builder with asynchronous client specific methods

func NewAsync

func NewAsync(transport spec.McpClientTransport) AsyncBuilder

NewAsync creates a new asynchronous client builder.

type AsyncSamplingHandler

type AsyncSamplingHandler interface {
	CreateMessageAsync(request *spec.CreateMessageRequest) (chan *spec.CreateMessageResult, chan error)
}

AsyncSamplingHandler is called to handle asynchronous sampling operations

type Builder

type Builder interface {
	// WithRequestTimeout sets the timeout for all requests.
	WithRequestTimeout(timeout time.Duration) Builder

	// WithInitializationTimeout sets the timeout for initialization.
	WithInitializationTimeout(timeout time.Duration) Builder

	// WithCapabilities sets the client capabilities.
	WithCapabilities(capabilities spec.ClientCapabilities) Builder

	// WithClientInfo sets the client implementation information.
	WithClientInfo(clientInfo spec.Implementation) Builder

	// WithRoots sets the resource roots the client can access.
	WithRoots(roots ...spec.Root) Builder

	// WithToolsChangeHandler adds a handler for tool changes.
	WithToolsChangeHandler(handler ToolsChangeHandler) Builder

	// WithResourcesChangeHandler adds a handler for resource changes.
	WithResourcesChangeHandler(handler ResourcesChangeHandler) Builder

	// WithPromptsChangeHandler adds a handler for prompt changes.
	WithPromptsChangeHandler(handler PromptsChangeHandler) Builder

	// WithLoggingHandler adds a handler for logging messages.
	WithLoggingHandler(handler LoggingHandler) Builder
}

Builder interface for creating clients

type ClientFeatures

type ClientFeatures struct {
	// ClientInfo contains information about the client implementation.
	ClientInfo spec.Implementation

	// Capabilities defines what features this client supports.
	Capabilities spec.ClientCapabilities

	// Roots defines the resource roots this client can access.
	Roots map[string]spec.Root

	// ToolsChangeHandlers are called when the available tools list changes.
	ToolsChangeHandlers []ToolsChangeHandler

	// ResourcesChangeHandlers are called when the available resources list changes.
	ResourcesChangeHandlers []ResourcesChangeHandler

	// ResourceChangeHandlers are called when a specific resource changes.
	ResourceChangeHandlers []ResourceChangeHandler

	// PromptsChangeHandlers are called when the available prompts list changes.
	PromptsChangeHandlers []PromptsChangeHandler

	// LoggingHandlers are called when a logging message is received.
	LoggingHandlers []LoggingHandler

	// SamplingHandler processes message creation requests before they are sent.
	SamplingHandler SamplingHandler

	// RootsChangeHandlers are called when the available roots list changes.
	RootsChangeHandlers []RootsChangeHandler
}

ClientFeatures encapsulates the feature set and capabilities of an MCP client. It defines how the client interacts with an MCP server, including supported capabilities, identity information, and event handlers.

func NewDefaultClientFeatures

func NewDefaultClientFeatures() *ClientFeatures

NewDefaultClientFeatures creates a new ClientFeatures instance with default settings.

func (*ClientFeatures) AddLoggingHandler

func (f *ClientFeatures) AddLoggingHandler(handler LoggingHandler) *ClientFeatures

AddLoggingHandler adds a handler for logging messages.

func (*ClientFeatures) AddPromptsChangeHandler

func (f *ClientFeatures) AddPromptsChangeHandler(handler PromptsChangeHandler) *ClientFeatures

AddPromptsChangeHandler adds a handler for prompt changes.

func (*ClientFeatures) AddResourceChangeHandler

func (f *ClientFeatures) AddResourceChangeHandler(uri string, handler func([]spec.ResourceContents)) *ClientFeatures

AddResourceChangeHandler adds a handler for a specific resource change.

func (*ClientFeatures) AddResourcesChangeHandler

func (f *ClientFeatures) AddResourcesChangeHandler(handler ResourcesChangeHandler) *ClientFeatures

AddResourcesChangeHandler adds a handler for resource changes.

func (*ClientFeatures) AddRoot

func (f *ClientFeatures) AddRoot(root spec.Root) *ClientFeatures

AddRoot adds a resource root to the client features.

func (*ClientFeatures) AddRootsChangeHandler

func (f *ClientFeatures) AddRootsChangeHandler(handler RootsChangeHandler) *ClientFeatures

AddRootsChangeHandler adds a handler for root changes.

func (*ClientFeatures) AddToolsChangeHandler

func (f *ClientFeatures) AddToolsChangeHandler(handler ToolsChangeHandler) *ClientFeatures

AddToolsChangeHandler adds a handler for tool changes.

func (*ClientFeatures) GetLoggingHandlers

func (f *ClientFeatures) GetLoggingHandlers() []LoggingHandler

GetLoggingHandlers returns the logging handlers.

func (*ClientFeatures) GetPromptsChangeHandlers

func (f *ClientFeatures) GetPromptsChangeHandlers() []PromptsChangeHandler

GetPromptsChangeHandlers returns the prompts change handlers.

func (*ClientFeatures) GetResourceChangeHandlers

func (f *ClientFeatures) GetResourceChangeHandlers() []ResourceChangeHandler

GetResourceChangeHandlers returns the resource change handlers.

func (*ClientFeatures) GetResourcesChangeHandlers

func (f *ClientFeatures) GetResourcesChangeHandlers() []ResourcesChangeHandler

GetResourcesChangeHandlers returns the resources change handlers.

func (*ClientFeatures) GetRoots

func (f *ClientFeatures) GetRoots() map[string]spec.Root

GetRoots returns the resource roots.

func (*ClientFeatures) GetRootsChangeHandlers

func (f *ClientFeatures) GetRootsChangeHandlers() []RootsChangeHandler

GetRootsChangeHandlers returns the roots change handlers.

func (*ClientFeatures) GetSamplingHandler

func (f *ClientFeatures) GetSamplingHandler() SamplingHandler

GetSamplingHandler returns the sampling handler.

func (*ClientFeatures) GetToolsChangeHandlers

func (f *ClientFeatures) GetToolsChangeHandlers() []ToolsChangeHandler

GetToolsChangeHandlers returns the tools change handlers.

func (*ClientFeatures) HasPromptsSupport

func (f *ClientFeatures) HasPromptsSupport() bool

HasPromptsSupport returns true if the client supports prompt access.

func (*ClientFeatures) HasResourcesSubscription

func (f *ClientFeatures) HasResourcesSubscription() bool

HasResourcesSubscription returns true if the client supports resource subscription.

func (*ClientFeatures) HasResourcesSupport

func (f *ClientFeatures) HasResourcesSupport() bool

HasResourcesSupport returns true if the client supports resource access.

func (*ClientFeatures) HasSamplingSupport

func (f *ClientFeatures) HasSamplingSupport() bool

HasSamplingSupport returns true if the client supports sampling capabilities.

func (*ClientFeatures) HasToolsSupport

func (f *ClientFeatures) HasToolsSupport() bool

HasToolsSupport returns true if the client supports tool execution.

func (*ClientFeatures) WithExperimental

func (f *ClientFeatures) WithExperimental(experimental map[string]interface{}) *ClientFeatures

WithExperimental adds experimental capabilities

func (*ClientFeatures) WithMaxMessageParts

func (f *ClientFeatures) WithMaxMessageParts(maxParts int) *ClientFeatures

WithMaxMessageParts sets the maximum message parts

func (*ClientFeatures) WithMaxToolParallelism

func (f *ClientFeatures) WithMaxToolParallelism(parallelism int) *ClientFeatures

WithMaxToolParallelism sets the maximum tool parallelism

func (*ClientFeatures) WithProtocolVersion

func (f *ClientFeatures) WithProtocolVersion(version string) *ClientFeatures

WithProtocolVersion sets the protocol version

func (*ClientFeatures) WithSamplingHandler

func (f *ClientFeatures) WithSamplingHandler(handler SamplingHandler) *ClientFeatures

WithSamplingHandler sets the sampling handler.

func (*ClientFeatures) WithSupportedContentTypes

func (f *ClientFeatures) WithSupportedContentTypes(types []string) *ClientFeatures

WithSupportedContentTypes sets the supported content types

func (*ClientFeatures) WithToolTimeout

func (f *ClientFeatures) WithToolTimeout(timeout int) *ClientFeatures

WithToolTimeout sets the tool timeout value

type LoggingHandler

type LoggingHandler func(spec.LoggingMessage)

LoggingHandler is called when a log message is received

type McpAsyncClient

type McpAsyncClient interface {
	McpClient

	// GetToolsAsync returns the list of tools provided by the server asynchronously.
	GetToolsAsync(ctx context.Context) (chan []spec.Tool, chan error)

	// ExecuteToolAsync executes a tool on the server asynchronously.
	ExecuteToolAsync(ctx context.Context, name string, params interface{}, resultType interface{}) (chan interface{}, chan error)

	// ExecuteToolsParallelAsync executes multiple tools on the server in parallel asynchronously.
	// The toolCalls parameter is a map where keys are tool names and values are the parameters to pass to each tool.
	// Returns two channels: one for results (map of tool names to results) and one for errors.
	ExecuteToolsParallelAsync(ctx context.Context, toolCalls map[string]interface{}, resultTypes map[string]interface{}) (chan map[string]interface{}, chan error)

	// GetResourcesAsync returns the list of resources provided by the server asynchronously.
	GetResourcesAsync(ctx context.Context) (chan []spec.Resource, chan error)

	// ReadResourceAsync reads a resource from the server asynchronously.
	ReadResourceAsync(ctx context.Context, uri string) (chan []spec.ResourceContents, chan error)

	// CreateResourceAsync creates a new resource on the server asynchronously.
	CreateResourceAsync(ctx context.Context, resource spec.Resource, contents []byte) chan error

	// UpdateResourceAsync updates an existing resource on the server asynchronously.
	UpdateResourceAsync(ctx context.Context, resource spec.Resource, contents []byte) chan error

	// DeleteResourceAsync deletes a resource from the server asynchronously.
	DeleteResourceAsync(ctx context.Context, uri string) chan error

	// GetResourceTemplatesAsync returns the list of resource templates provided by the server asynchronously.
	GetResourceTemplatesAsync(ctx context.Context) (chan []spec.ResourceTemplate, chan error)

	// SubscribeToResourceAsync subscribes to changes in a resource asynchronously.
	SubscribeToResourceAsync(ctx context.Context, uri string) chan error

	// UnsubscribeFromResourceAsync unsubscribes from changes in a resource asynchronously.
	UnsubscribeFromResourceAsync(ctx context.Context, uri string) chan error

	// GetPromptsAsync returns the list of prompts provided by the server asynchronously.
	GetPromptsAsync(ctx context.Context) (chan []spec.Prompt, chan error)

	// GetPromptAsync gets a prompt from the server with the given arguments asynchronously.
	GetPromptAsync(ctx context.Context, name string, args map[string]interface{}) (chan *spec.GetPromptResult, chan error)

	// CreatePromptAsync creates a new prompt on the server asynchronously.
	CreatePromptAsync(ctx context.Context, prompt spec.Prompt, messages []spec.PromptMessage) chan error

	// UpdatePromptAsync updates an existing prompt on the server asynchronously.
	UpdatePromptAsync(ctx context.Context, prompt spec.Prompt, messages []spec.PromptMessage) chan error

	// DeletePromptAsync deletes a prompt from the server asynchronously.
	DeletePromptAsync(ctx context.Context, name string) chan error

	// CreateMessageAsync sends a create message request to the server asynchronously.
	CreateMessageAsync(ctx context.Context, request *spec.CreateMessageRequest) (chan *spec.CreateMessageResult, chan error)

	// CreateMessageStreamAsync sends a create message request to the server and streams the responses asynchronously.
	// The returned channels will receive partial results and errors as they become available.
	CreateMessageStreamAsync(ctx context.Context, request *spec.CreateMessageRequest) (chan *spec.CreateMessageResult, chan error)

	// SetLoggingLevelAsync sets the minimum level for logs from the server asynchronously.
	SetLoggingLevelAsync(ctx context.Context, level spec.LogLevel) chan error

	// PingAsync sends a ping to the server to check connectivity asynchronously.
	PingAsync(ctx context.Context) chan error

	// GetRootsAsync returns the list of roots available on the server asynchronously.
	GetRootsAsync(ctx context.Context) (chan []spec.Root, chan error)

	// CreateRootAsync creates a new root on the server asynchronously.
	CreateRootAsync(ctx context.Context, root spec.Root) (chan *spec.Root, chan error)

	// UpdateRootAsync updates an existing root on the server asynchronously.
	UpdateRootAsync(ctx context.Context, root spec.Root) (chan *spec.Root, chan error)

	// DeleteRootAsync deletes a root from the server asynchronously.
	DeleteRootAsync(ctx context.Context, uri string) chan error

	// CancelOperation cancels a specific operation by ID
	CancelOperation(operationID string) bool

	// CancelCreateMessage cancels an ongoing message creation operation
	CancelCreateMessage(messageID string) bool

	// CancelToolExecution cancels an ongoing tool execution operation
	CancelToolExecution(toolID string) bool

	// GetOngoingOperations returns the IDs of all ongoing operations
	GetOngoingOperations() []string
}

McpAsyncClient defines the interface for an asynchronous MCP client.

type McpClient

type McpClient interface {
	// Initialize initializes the client and connects to the server.
	Initialize() error

	// InitializeAsync initializes the client and connects to the server asynchronously.
	InitializeAsync() chan error

	// Close closes the client and releases any resources.
	Close() error

	// CloseGracefully closes the client gracefully, waiting for pending operations to complete.
	CloseGracefully(ctx context.Context) error

	// GetProtocolVersion returns the protocol version used by the server.
	GetProtocolVersion() string

	// GetServerInfo returns information about the server.
	GetServerInfo() spec.Implementation

	// GetServerCapabilities returns the capabilities of the server.
	GetServerCapabilities() spec.ServerCapabilities

	// GetClientCapabilities returns the capabilities of the client.
	GetClientCapabilities() spec.ClientCapabilities

	// GetTools returns the list of tools provided by the server.
	GetTools() ([]spec.Tool, error)

	// ExecuteTool executes a tool on the server.
	ExecuteTool(name string, params interface{}, resultPtr interface{}) error

	// ExecuteToolsParallel executes multiple tools on the server in parallel.
	// The toolCalls parameter is a map where keys are tool names and values are the parameters to pass to each tool.
	// The results parameter is a map where keys are tool names and values are pointers to store the results.
	// Returns a map of tool names to errors for any failed tool executions.
	ExecuteToolsParallel(ctx context.Context, toolCalls map[string]interface{}, results map[string]interface{}) map[string]error

	// ExecuteToolStream executes a tool on the server with streaming support.
	// It returns a channel that receives content as it becomes available and a channel for errors.
	// The contents channel will be closed when streaming is complete.
	ExecuteToolStream(ctx context.Context, name string, params interface{}) (chan []spec.Content, chan error)

	// GetResources returns the list of resources provided by the server.
	GetResources() ([]spec.Resource, error)

	// ReadResource reads a resource from the server.
	ReadResource(uri string) ([]spec.ResourceContents, error)

	// CreateResource creates a new resource on the server.
	CreateResource(resource spec.Resource, contents []byte) error

	// UpdateResource updates an existing resource on the server.
	UpdateResource(resource spec.Resource, contents []byte) error

	// DeleteResource deletes a resource from the server.
	DeleteResource(uri string) error

	// GetResourceTemplates returns the list of resource templates provided by the server.
	GetResourceTemplates() ([]spec.ResourceTemplate, error)

	// SubscribeToResource subscribes to changes in a resource.
	SubscribeToResource(uri string) error

	// UnsubscribeFromResource unsubscribes from changes in a resource.
	UnsubscribeFromResource(uri string) error

	// GetPrompts returns the list of prompts provided by the server.
	GetPrompts() ([]spec.Prompt, error)

	// GetPrompt gets a prompt from the server with the given arguments.
	GetPrompt(name string, args map[string]interface{}) (*spec.GetPromptResult, error)

	// CreatePrompt creates a new prompt on the server.
	CreatePrompt(prompt spec.Prompt, messages []spec.PromptMessage) error

	// UpdatePrompt updates an existing prompt on the server.
	UpdatePrompt(prompt spec.Prompt, messages []spec.PromptMessage) error

	// DeletePrompt deletes a prompt from the server.
	DeletePrompt(name string) error

	// CreateMessage sends a create message request to the server.
	CreateMessage(request *spec.CreateMessageRequest) (*spec.CreateMessageResult, error)

	// CreateMessageStream sends a create message request to the server and streams the responses.
	// The returned channel will receive partial results as they become available.
	CreateMessageStream(ctx context.Context, request *spec.CreateMessageRequest) (<-chan *spec.CreateMessageResult, <-chan error)

	// CreateMessageWithModelPreferences creates a new message with specified model preferences
	CreateMessageWithModelPreferences(content string, modelPreferences *spec.ModelPreferences) (*spec.CreateMessageResult, error)

	// CreateMessageWithModel creates a new message with a specific model hint
	CreateMessageWithModel(content string, modelName string) (*spec.CreateMessageResult, error)

	// SetLoggingLevel sets the minimum level for logs from the server.
	SetLoggingLevel(level spec.LogLevel) error

	// GetTransport returns the underlying transport used by the client.
	GetTransport() spec.McpClientTransport

	// Ping sends a ping to the server to check connectivity.
	Ping() error

	// GetRoots returns the list of roots available on the server.
	GetRoots() ([]spec.Root, error)

	// CreateRoot creates a new root on the server.
	CreateRoot(root spec.Root) (*spec.Root, error)

	// UpdateRoot updates an existing root on the server.
	UpdateRoot(root spec.Root) (*spec.Root, error)

	// DeleteRoot deletes a root from the server.
	DeleteRoot(uri string) error

	// OnRootsChanged registers a callback to be notified when roots change.
	OnRootsChanged(callback func([]spec.Root))
}

McpClient defines the common interface for MCP clients.

type McpClientConfig

type McpClientConfig struct {
	RequestTimeout         time.Duration
	InitializationTimeout  time.Duration
	ClientCapabilities     spec.ClientCapabilities
	ClientInfo             spec.Implementation
	Roots                  []spec.Root
	ToolsChangeHandler     ToolsChangeHandler
	ResourcesChangeHandler ResourcesChangeHandler
	PromptsChangeHandler   PromptsChangeHandler
	LoggingHandler         LoggingHandler
}

McpClientConfig holds the configuration for an MCP client

type McpClientFeatures

type McpClientFeatures interface {
	// ListRoots lists the available filesystem roots.
	ListRoots(ctx context.Context) ([]spec.Root, error)

	// OnRootsChanged registers a callback to be notified when roots change.
	OnRootsChanged(callback func([]spec.Root))

	// OnToolsChanged registers a callback to be notified when tools change.
	OnToolsChanged(callback func([]spec.Tool))

	// OnResourcesChanged registers a callback to be notified when resources change.
	OnResourcesChanged(callback func([]spec.Resource))

	// OnPromptsChanged registers a callback to be notified when prompts change.
	OnPromptsChanged(callback func([]spec.Prompt))

	// OnResourceChanged registers a callback to be notified when a specific resource changes.
	OnResourceChanged(uri string, callback func([]spec.ResourceContents))

	// OnLogMessage registers a callback to be notified when a log message is received.
	OnLogMessage(callback func(spec.LoggingMessage))
}

McpClientFeatures defines optional features that can be implemented by clients.

type McpSyncClient

type McpSyncClient interface {
	McpClient
}

McpSyncClient defines the interface for a synchronous MCP client.

type PromptsChangeHandler

type PromptsChangeHandler func([]spec.Prompt)

PromptsChangeHandler is called when the available prompts change

type ResourceChangeHandler

type ResourceChangeHandler struct {
	URI      string
	Callback func([]spec.ResourceContents)
}

ResourceChangeHandler defines a callback for a specific resource URI

type ResourcesChangeHandler

type ResourcesChangeHandler func([]spec.Resource)

ResourcesChangeHandler is called when the available resources change

type RootsChangeHandler

type RootsChangeHandler func([]spec.Root)

RootsChangeHandler is called when the list of roots changes

type SamplingHandler

type SamplingHandler interface {
	CreateMessage(request *spec.CreateMessageRequest) (*spec.CreateMessageResult, error)
}

SamplingHandler is called to handle sampling operations

type SyncBuilder

type SyncBuilder interface {
	Builder

	// WithSampling sets the sampling handler.
	WithSampling(handler SamplingHandler) SyncBuilder

	// Build creates a new McpSyncClient with the configured settings.
	Build() McpSyncClient
}

SyncBuilder extends Builder with synchronous client specific methods

func NewSync

func NewSync(transport spec.McpClientTransport) SyncBuilder

NewSync creates a new synchronous client builder.

type ToolsChangeHandler

type ToolsChangeHandler func([]spec.Tool)

ToolsChangeHandler is called when the available tools change

Directories

Path Synopsis
Package stream provides implementations for streaming message creation
Package stream provides implementations for streaming message creation

Jump to

Keyboard shortcuts

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