Documentation
¶
Overview ¶
Package client provides MCP (Model Context Protocol) client implementations.
Index ¶
- Variables
- func GetEndpoint(c *Client) *url.URL
- func GetOAuthHandler(err error) *transport.OAuthHandler
- func GetResourceMetadataURL(err error) string
- func GetStderr(c *Client) (io.Reader, bool)
- func IsAuthorizationRequiredError(err error) bool
- func IsOAuthAuthorizationRequiredError(err error) bool
- func WithHTTPClient(httpClient *http.Client) transport.ClientOption
- func WithHTTPHost(host string) transport.ClientOption
- func WithHeaderFunc(headerFunc transport.HTTPHeaderFunc) transport.ClientOption
- func WithHeaders(headers map[string]string) transport.ClientOption
- type AuthorizationRequiredError
- type Client
- func NewClient(transport transport.Interface, options ...ClientOption) *Client
- func NewInProcessClient(server *server.MCPServer) (*Client, error)
- func NewInProcessClientWithSamplingHandler(server *server.MCPServer, handler SamplingHandler) (*Client, error)
- func NewOAuthSSEClient(baseURL string, oauthConfig OAuthConfig, options ...transport.ClientOption) (*Client, error)
- func NewOAuthStreamableHttpClient(baseURL string, oauthConfig OAuthConfig, ...) (*Client, error)
- func NewSSEMCPClient(baseURL string, options ...transport.ClientOption) (*Client, error)
- func NewStdioMCPClient(command string, env []string, args ...string) (*Client, error)
- func NewStdioMCPClientWithOptions(command string, env []string, args []string, opts ...transport.StdioOption) (*Client, error)
- func NewStreamableHttpClient(baseURL string, options ...transport.StreamableHTTPCOption) (*Client, error)
- func (c *Client) CallTool(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error)
- func (c *Client) CancelTask(ctx context.Context, request mcp.CancelTaskRequest) (*mcp.CancelTaskResult, error)
- func (c *Client) Close() error
- func (c *Client) Complete(ctx context.Context, request mcp.CompleteRequest) (*mcp.CompleteResult, error)
- func (c *Client) Discover(ctx context.Context, request mcp.DiscoverRequest) (*mcp.DiscoverResult, error)
- func (c *Client) GetClientCapabilities() mcp.ClientCapabilities
- func (c *Client) GetPrompt(ctx context.Context, request mcp.GetPromptRequest) (*mcp.GetPromptResult, error)
- func (c *Client) GetServerCapabilities() mcp.ServerCapabilities
- func (c *Client) GetSessionId() string
- func (c *Client) GetTask(ctx context.Context, request mcp.GetTaskRequest) (*mcp.GetTaskResult, error)
- func (c *Client) GetTransport() transport.Interface
- func (c *Client) Initialize(ctx context.Context, request mcp.InitializeRequest) (*mcp.InitializeResult, error)
- func (c *Client) IsInitialized() bool
- func (c *Client) IterPrompts(ctx context.Context, request mcp.ListPromptsRequest) iter.Seq2[mcp.Prompt, error]
- func (c *Client) IterResourceTemplates(ctx context.Context, request mcp.ListResourceTemplatesRequest) iter.Seq2[mcp.ResourceTemplate, error]
- func (c *Client) IterResources(ctx context.Context, request mcp.ListResourcesRequest) iter.Seq2[mcp.Resource, error]
- func (c *Client) IterTools(ctx context.Context, request mcp.ListToolsRequest) iter.Seq2[mcp.Tool, error]
- func (c *Client) ListPrompts(ctx context.Context, request mcp.ListPromptsRequest) (*mcp.ListPromptsResult, error)
- func (c *Client) ListPromptsByPage(ctx context.Context, request mcp.ListPromptsRequest) (*mcp.ListPromptsResult, error)
- func (c *Client) ListResourceTemplates(ctx context.Context, request mcp.ListResourceTemplatesRequest) (*mcp.ListResourceTemplatesResult, error)
- func (c *Client) ListResourceTemplatesByPage(ctx context.Context, request mcp.ListResourceTemplatesRequest) (*mcp.ListResourceTemplatesResult, error)
- func (c *Client) ListResources(ctx context.Context, request mcp.ListResourcesRequest) (*mcp.ListResourcesResult, error)
- func (c *Client) ListResourcesByPage(ctx context.Context, request mcp.ListResourcesRequest) (*mcp.ListResourcesResult, error)
- func (c *Client) ListTasks(ctx context.Context, request mcp.ListTasksRequest) (*mcp.ListTasksResult, error)
- func (c *Client) ListTools(ctx context.Context, request mcp.ListToolsRequest) (*mcp.ListToolsResult, error)
- func (c *Client) ListToolsByPage(ctx context.Context, request mcp.ListToolsRequest) (*mcp.ListToolsResult, error)
- func (c *Client) Listen(ctx context.Context, filter mcp.SubscriptionFilter) error
- func (c *Client) ListenAsync(ctx context.Context, filter mcp.SubscriptionFilter, onError func(error)) (stop func(), err error)
- func (c *Client) OnConnectionLost(handler func(error))
- func (c *Client) OnNotification(handler func(notification mcp.JSONRPCNotification))
- func (c *Client) PendingSubscriptionFilter() mcp.SubscriptionFilter
- func (c *Client) Ping(ctx context.Context) errordeprecated
- func (c *Client) ProtocolVersion() string
- func (c *Client) ReadResource(ctx context.Context, request mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error)
- func (c *Client) RootListChanges(ctx context.Context) error
- func (c *Client) SetLevel(ctx context.Context, request mcp.SetLevelRequest) errordeprecated
- func (c *Client) Start(ctx context.Context) error
- func (c *Client) Subscribe(ctx context.Context, request mcp.SubscribeRequest) errordeprecated
- func (c *Client) TaskResult(ctx context.Context, request mcp.TaskResultRequest) (*mcp.TaskResultResult, error)
- func (c *Client) Unsubscribe(ctx context.Context, request mcp.UnsubscribeRequest) errordeprecated
- type ClientOption
- func WithClientCapabilities(capabilities mcp.ClientCapabilities) ClientOption
- func WithDiscoverTimeout(timeout time.Duration) ClientOption
- func WithElicitationHandler(handler ElicitationHandler) ClientOption
- func WithLegacyProtocolOnly() ClientOptiondeprecated
- func WithMaxInputRoundTrips(limit int) ClientOption
- func WithMetaPropagator(p tracing.MetaPropagator) ClientOption
- func WithPropagator(p tracing.Propagator) ClientOption
- func WithProtocolVersion(version string) ClientOption
- func WithRootsHandler(handler RootsHandler) ClientOption
- func WithSamplingHandler(handler SamplingHandler) ClientOption
- func WithSession() ClientOption
- func WithTracer(tracer tracing.Tracer) ClientOption
- type ElicitationHandler
- type MCPClient
- type MemoryTokenStore
- type OAuthAuthorizationRequiredError
- type OAuthConfig
- type RootsHandler
- type SamplingHandler
- type Token
- type TokenStore
Constants ¶
This section is empty.
Variables ¶
var ErrMaxInputRoundTripsExceeded = errors.New("multi round-trip: exceeded maximum retries")
ErrMaxInputRoundTripsExceeded is returned when a server keeps asking for more input past the configured limit.
var GenerateCodeChallenge = transport.GenerateCodeChallenge
GenerateCodeChallenge generates a code challenge from a code verifier
var GenerateCodeVerifier = transport.GenerateCodeVerifier
GenerateCodeVerifier generates a code verifier for PKCE
var GenerateState = transport.GenerateState
GenerateState generates a state parameter for OAuth
var NewMemoryTokenStore = transport.NewMemoryTokenStore
NewMemoryTokenStore is a convenience function that wraps transport.NewMemoryTokenStore
Functions ¶
func GetEndpoint ¶ added in v0.21.0
GetEndpoint returns the current endpoint URL for the SSE connection.
Note: This method only works with SSE transport, or it will panic.
func GetOAuthHandler ¶ added in v0.30.0
func GetOAuthHandler(err error) *transport.OAuthHandler
GetOAuthHandler extracts the OAuthHandler from an OAuthAuthorizationRequiredError
func GetResourceMetadataURL ¶ added in v0.49.0
GetResourceMetadataURL extracts the protected resource metadata URL from an authorization error. This URL is extracted from the WWW-Authenticate header per RFC9728 Section 5.1. Works with both AuthorizationRequiredError and OAuthAuthorizationRequiredError. Returns empty string if no metadata URL was discovered.
func GetStderr ¶ added in v0.21.0
GetStderr returns a reader for the stderr output of the subprocess. This can be used to capture error messages or logs from the subprocess.
It works with any transport that exposes a Stderr() io.Reader method, including *transport.Stdio and *transport.CommandTransport.
func IsAuthorizationRequiredError ¶ added in v0.49.0
IsAuthorizationRequiredError checks if an error is an AuthorizationRequiredError
func IsOAuthAuthorizationRequiredError ¶ added in v0.30.0
IsOAuthAuthorizationRequiredError checks if an error is an OAuthAuthorizationRequiredError
func WithHTTPClient ¶ added in v0.25.0
func WithHTTPClient(httpClient *http.Client) transport.ClientOption
WithHTTPClient sets a custom HTTP client for the SSE transport.
func WithHTTPHost ¶ added in v0.44.0
func WithHTTPHost(host string) transport.ClientOption
WithHTTPHost sets a custom Host header for the SSE client, enabling manual DNS resolution. This allows connecting to an IP address while sending a specific Host header to the server. For example, connecting to "http://192.168.1.100:8080/sse" but sending Host: "api.example.com"
func WithHeaderFunc ¶ added in v0.30.0
func WithHeaderFunc(headerFunc transport.HTTPHeaderFunc) transport.ClientOption
WithHeaderFunc sets a function that returns headers for each SSE request.
func WithHeaders ¶ added in v0.17.0
func WithHeaders(headers map[string]string) transport.ClientOption
WithHeaders sets static headers for the SSE client.
Types ¶
type AuthorizationRequiredError ¶ added in v0.49.0
type AuthorizationRequiredError = transport.AuthorizationRequiredError
AuthorizationRequiredError is returned when a 401 Unauthorized response is received
type Client ¶ added in v0.21.0
type Client struct {
// contains filtered or unexported fields
}
Client implements the MCP client.
func NewClient ¶ added in v0.21.0
func NewClient(transport transport.Interface, options ...ClientOption) *Client
NewClient creates a new MCP client with the given transport. Usage:
stdio := transport.NewStdio("./mcp_server", nil, "xxx")
client, err := NewClient(stdio)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
func NewInProcessClient ¶ added in v0.23.0
NewInProcessClient connect directly to a mcp server object in the same process
func NewInProcessClientWithSamplingHandler ¶ added in v0.34.0
func NewInProcessClientWithSamplingHandler(server *server.MCPServer, handler SamplingHandler) (*Client, error)
NewInProcessClientWithSamplingHandler creates an in-process client with sampling support
func NewOAuthSSEClient ¶ added in v0.32.0
func NewOAuthSSEClient(baseURL string, oauthConfig OAuthConfig, options ...transport.ClientOption) (*Client, error)
NewOAuthStreamableHttpClient creates a new streamable-http-based MCP client with OAuth support. Returns an error if the URL is invalid.
func NewOAuthStreamableHttpClient ¶ added in v0.30.0
func NewOAuthStreamableHttpClient(baseURL string, oauthConfig OAuthConfig, options ...transport.StreamableHTTPCOption) (*Client, error)
NewOAuthStreamableHttpClient creates a new streamable-http-based MCP client with OAuth support. Returns an error if the URL is invalid.
func NewSSEMCPClient ¶ added in v0.2.0
func NewSSEMCPClient(baseURL string, options ...transport.ClientOption) (*Client, error)
NewSSEMCPClient creates a new SSE-based MCP client with the given base URL. Returns an error if the URL is invalid.
Example:
c, err := client.NewSSEMCPClient("http://localhost:8080/mcp/sse")
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
defer c.Close()
Note: Use a variable name other than "client" (e.g., "c", "mcpClient") to avoid shadowing the package name.
func NewStdioMCPClient ¶
NewStdioMCPClient creates a new stdio-based MCP client that communicates with a subprocess. It launches the specified command with given arguments and sets up stdin/stdout pipes for communication. Returns an error if the subprocess cannot be started or the pipes cannot be created.
NOTICE: NewStdioMCPClient will start the connection automatically. This is for backward compatibility.
func NewStdioMCPClientWithOptions ¶ added in v0.33.0
func NewStdioMCPClientWithOptions( command string, env []string, args []string, opts ...transport.StdioOption, ) (*Client, error)
NewStdioMCPClientWithOptions creates a new stdio-based MCP client that communicates with a subprocess. It launches the specified command with given arguments and sets up stdin/stdout pipes for communication. Optional configuration functions can be provided to customize the transport before it starts, such as setting a custom command function.
NOTICE: NewStdioMCPClientWithOptions automatically starts the underlying transport. This is for backward compatibility.
func NewStreamableHttpClient ¶ added in v0.22.0
func NewStreamableHttpClient(baseURL string, options ...transport.StreamableHTTPCOption) (*Client, error)
NewStreamableHttpClient is a convenience method that creates a new streamable-http-based MCP client with the given base URL. Returns an error if the URL is invalid.
func (*Client) CallTool ¶ added in v0.21.0
func (c *Client) CallTool( ctx context.Context, request mcp.CallToolRequest, ) (*mcp.CallToolResult, error)
CallTool invokes a tool on the server.
func (*Client) CancelTask ¶ added in v0.47.0
func (c *Client) CancelTask( ctx context.Context, request mcp.CancelTaskRequest, ) (*mcp.CancelTaskResult, error)
CancelTask returns canceled task result
func (*Client) Complete ¶ added in v0.21.0
func (c *Client) Complete( ctx context.Context, request mcp.CompleteRequest, ) (*mcp.CompleteResult, error)
Complete requests completion suggestions from the server.
func (*Client) Discover ¶ added in v1.0.0
func (c *Client) Discover(ctx context.Context, request mcp.DiscoverRequest) (*mcp.DiscoverResult, error)
Discover asks the server which protocol versions it supports, what its capabilities are, and who it is, without performing the legacy initialize handshake (SEP-2575).
Servers implementing protocol version 2026-07-28 or later must support this method. Against an older server it fails, which is how Client.Initialize detects that it must fall back to the handshake.
func (*Client) GetClientCapabilities ¶ added in v0.23.0
func (c *Client) GetClientCapabilities() mcp.ClientCapabilities
GetClientCapabilities returns the client capabilities.
func (*Client) GetPrompt ¶ added in v0.21.0
func (c *Client) GetPrompt( ctx context.Context, request mcp.GetPromptRequest, ) (*mcp.GetPromptResult, error)
GetPrompt gets a prompt and renders it with the provided arguments.
func (*Client) GetServerCapabilities ¶ added in v0.23.0
func (c *Client) GetServerCapabilities() mcp.ServerCapabilities
GetServerCapabilities returns the server capabilities.
func (*Client) GetSessionId ¶ added in v0.33.0
GetSessionId returns the session ID of the transport. If the transport does not support sessions, it returns an empty string.
func (*Client) GetTask ¶ added in v0.47.0
func (c *Client) GetTask( ctx context.Context, request mcp.GetTaskRequest, ) (*mcp.GetTaskResult, error)
GetTask returns task with current status
func (*Client) GetTransport ¶ added in v0.21.0
GetTransport gives access to the underlying transport layer. Cast it to the specific transport type and obtain the other helper methods.
func (*Client) Initialize ¶ added in v0.21.0
func (c *Client) Initialize( ctx context.Context, request mcp.InitializeRequest, ) (*mcp.InitializeResult, error)
Initialize establishes the connection with the server.
It must be called after Start, and before any request methods.
Protocol version 2026-07-28 removed the initialize handshake (SEP-2575), so this method first probes the server with server/discover. When the probe succeeds the connection is stateless and every subsequent request carries its own protocol metadata; the returned InitializeResult is rendered from the discovery response so that callers observe the same value in both eras.
When the probe fails with anything other than a recognized modern error the server is taken to be legacy, and the classic initialize handshake is performed instead.
func (*Client) IsInitialized ¶ added in v0.33.0
IsInitialized returns true if the client has been initialized.
func (*Client) IterPrompts ¶ added in v0.51.0
func (c *Client) IterPrompts( ctx context.Context, request mcp.ListPromptsRequest, ) iter.Seq2[mcp.Prompt, error]
IterPrompts returns an iterator that lazily fetches pages of prompts from the server. Pages are fetched on demand as the iterator is consumed; breaking out of the loop stops further requests.
If an error occurs while fetching a page, the iterator yields a single (zero-value, error) pair and then stops.
func (*Client) IterResourceTemplates ¶ added in v0.51.0
func (c *Client) IterResourceTemplates( ctx context.Context, request mcp.ListResourceTemplatesRequest, ) iter.Seq2[mcp.ResourceTemplate, error]
IterResourceTemplates returns an iterator that lazily fetches pages of resource templates from the server. Pages are fetched on demand as the iterator is consumed; breaking out of the loop stops further requests.
If an error occurs while fetching a page, the iterator yields a single (zero-value, error) pair and then stops.
func (*Client) IterResources ¶ added in v0.51.0
func (c *Client) IterResources( ctx context.Context, request mcp.ListResourcesRequest, ) iter.Seq2[mcp.Resource, error]
IterResources returns an iterator that lazily fetches pages of resources from the server. Pages are fetched on demand as the iterator is consumed; breaking out of the loop stops further requests.
If an error occurs while fetching a page, the iterator yields a single (zero-value, error) pair and then stops.
func (*Client) IterTools ¶ added in v0.51.0
func (c *Client) IterTools( ctx context.Context, request mcp.ListToolsRequest, ) iter.Seq2[mcp.Tool, error]
IterTools returns an iterator that lazily fetches pages of tools from the server. Pages are fetched on demand as the iterator is consumed; breaking out of the loop stops further requests.
If an error occurs while fetching a page, the iterator yields a single (zero-value, error) pair and then stops.
Example:
for tool, err := range client.IterTools(ctx, mcp.ListToolsRequest{}) {
if err != nil {
return err
}
fmt.Println(tool.Name)
}
func (*Client) ListPrompts ¶ added in v0.21.0
func (c *Client) ListPrompts( ctx context.Context, request mcp.ListPromptsRequest, ) (*mcp.ListPromptsResult, error)
ListPrompts lists all prompts by following paginated responses.
func (*Client) ListPromptsByPage ¶ added in v0.21.0
func (c *Client) ListPromptsByPage( ctx context.Context, request mcp.ListPromptsRequest, ) (*mcp.ListPromptsResult, error)
ListPromptsByPage manually lists prompts by page.
func (*Client) ListResourceTemplates ¶ added in v0.21.0
func (c *Client) ListResourceTemplates( ctx context.Context, request mcp.ListResourceTemplatesRequest, ) (*mcp.ListResourceTemplatesResult, error)
ListResourceTemplates lists all resource templates by following paginated responses.
func (*Client) ListResourceTemplatesByPage ¶ added in v0.21.0
func (c *Client) ListResourceTemplatesByPage( ctx context.Context, request mcp.ListResourceTemplatesRequest, ) (*mcp.ListResourceTemplatesResult, error)
ListResourceTemplatesByPage manually lists resource templates by page.
func (*Client) ListResources ¶ added in v0.21.0
func (c *Client) ListResources( ctx context.Context, request mcp.ListResourcesRequest, ) (*mcp.ListResourcesResult, error)
ListResources lists all resources by following paginated responses.
func (*Client) ListResourcesByPage ¶ added in v0.21.0
func (c *Client) ListResourcesByPage( ctx context.Context, request mcp.ListResourcesRequest, ) (*mcp.ListResourcesResult, error)
ListResourcesByPage manually list resources by page.
func (*Client) ListTasks ¶ added in v0.47.0
func (c *Client) ListTasks( ctx context.Context, request mcp.ListTasksRequest, ) (*mcp.ListTasksResult, error)
ListTasks returns the list of tasks
func (*Client) ListTools ¶ added in v0.21.0
func (c *Client) ListTools( ctx context.Context, request mcp.ListToolsRequest, ) (*mcp.ListToolsResult, error)
ListTools lists all tools by following paginated responses.
func (*Client) ListToolsByPage ¶ added in v0.21.0
func (c *Client) ListToolsByPage( ctx context.Context, request mcp.ListToolsRequest, ) (*mcp.ListToolsResult, error)
ListToolsByPage manually lists tools by page.
func (*Client) Listen ¶ added in v1.0.0
Listen opens a subscriptions/listen stream for the given notification types and blocks until the context is cancelled or the server closes the stream.
Notifications are delivered to the handlers registered with Client.OnNotification, exactly as they were on earlier protocol versions.
Listen is only available on connections using protocol version 2026-07-28 or later. On a legacy connection it returns an error: notifications arrive on the transport's own stream there, with no opt-in required.
func (*Client) ListenAsync ¶ added in v1.0.0
func (c *Client) ListenAsync( ctx context.Context, filter mcp.SubscriptionFilter, onError func(error), ) (stop func(), err error)
ListenAsync opens a subscriptions/listen stream in the background and returns a function that closes it.
It is the convenient form of Client.Listen for callers that only want the notifications to start flowing. Errors from the stream are reported to onError, which may be nil.
func (*Client) OnConnectionLost ¶ added in v0.37.0
OnConnectionLost registers a handler function to be called when the connection is lost. This is useful for handling HTTP2 idle timeout disconnections that should not be treated as errors.
func (*Client) OnNotification ¶ added in v0.21.0
func (c *Client) OnNotification( handler func(notification mcp.JSONRPCNotification), )
OnNotification registers a handler function to be called when notifications are received. Multiple handlers can be registered and will be called in the order they were added.
func (*Client) PendingSubscriptionFilter ¶ added in v1.0.0
func (c *Client) PendingSubscriptionFilter() mcp.SubscriptionFilter
PendingSubscriptionFilter returns the filter that the next Client.Listen call would use, accumulated from Client.Subscribe calls.
func (*Client) Ping
deprecated
added in
v0.21.0
func (*Client) ProtocolVersion ¶ added in v1.0.0
ProtocolVersion returns the protocol version in effect for this client, or "" before the connection has been established.
func (*Client) ReadResource ¶ added in v0.21.0
func (c *Client) ReadResource( ctx context.Context, request mcp.ReadResourceRequest, ) (*mcp.ReadResourceResult, error)
ReadResource reads the contents of a resource from the server.
func (*Client) RootListChanges ¶ added in v0.43.0
RootListChanges sends a roots list-changed notification to the server.
func (*Client) SetLevel
deprecated
added in
v0.21.0
SetLevel sets the minimum severity of log messages the server should send.
Protocol version 2026-07-28 removed the logging/setLevel RPC: the level is declared per request, in _meta (SEP-2575). On a modern connection this method records the level locally, and every subsequent request carries it.
Deprecated: the Logging feature is deprecated as of protocol version 2026-07-28 (SEP-2577). Log to stderr or use OpenTelemetry instead.
func (*Client) Start ¶ added in v0.21.0
Start initiates the connection to the server. Must be called before using the client.
func (*Client) Subscribe
deprecated
added in
v0.21.0
Subscribe subscribes to updates for a resource.
Protocol version 2026-07-28 removed the resources/subscribe RPC: resource subscriptions are declared in the filter of a subscriptions/listen request (SEP-2575). On a modern connection this method records the URI so that the next Client.Listen call includes it; it does not open the stream itself.
Deprecated: use Client.Listen with a filter naming the resources of interest.
func (*Client) TaskResult ¶ added in v0.47.0
func (c *Client) TaskResult( ctx context.Context, request mcp.TaskResultRequest, ) (*mcp.TaskResultResult, error)
TaskResult returns finished task result
func (*Client) Unsubscribe
deprecated
added in
v0.21.0
Unsubscribe removes a resource update subscription.
Protocol version 2026-07-28 removed the resources/unsubscribe RPC. On a modern connection this method drops the URI from the filter used by the next Client.Listen call.
Deprecated: close the Client.Listen stream, or reopen it with a narrower filter.
type ClientOption ¶ added in v0.17.0
type ClientOption func(*Client)
ClientOption configures a Client during construction.
func WithClientCapabilities ¶ added in v0.23.0
func WithClientCapabilities(capabilities mcp.ClientCapabilities) ClientOption
WithClientCapabilities sets the client capabilities for the client.
func WithDiscoverTimeout ¶ added in v1.0.0
func WithDiscoverTimeout(timeout time.Duration) ClientOption
WithDiscoverTimeout bounds how long Initialize waits for a server/discover reply before concluding that the server predates protocol version 2026-07-28 and falling back to the initialize handshake.
The default is five seconds. A negative value disables the bound.
func WithElicitationHandler ¶ added in v0.40.0
func WithElicitationHandler(handler ElicitationHandler) ClientOption
WithElicitationHandler sets the elicitation handler for the client. When set, the client will declare elicitation capability during initialization.
func WithLegacyProtocolOnly
deprecated
added in
v1.0.0
func WithLegacyProtocolOnly() ClientOption
WithLegacyProtocolOnly keeps the client on the initialize handshake, skipping the server/discover probe.
Deprecated: the initialize handshake was removed in protocol version 2026-07-28. This option exists for deployments that depend on protocol-level session state and will be removed once the deprecation window closes.
func WithMaxInputRoundTrips ¶ added in v1.0.0
func WithMaxInputRoundTrips(limit int) ClientOption
WithMaxInputRoundTrips bounds how many times the client will fulfil a server's input requests and retry the original call before giving up.
The default is 10. See the multi round-trip request pattern (SEP-2322).
func WithMetaPropagator ¶ added in v0.55.0
func WithMetaPropagator(p tracing.MetaPropagator) ClientOption
WithMetaPropagator installs a propagator that injects trace context into the MCP _meta property bag of outgoing requests (per SEP-414). It covers all transports including stdio, where HTTP headers are unavailable. A nil propagator is treated as a no-op.
func WithPropagator ¶ added in v0.54.0
func WithPropagator(p tracing.Propagator) ClientOption
WithPropagator installs a propagator that injects trace context into outgoing request headers. A nil propagator is treated as a no-op.
func WithProtocolVersion ¶ added in v1.0.0
func WithProtocolVersion(version string) ClientOption
WithProtocolVersion pins the protocol version the client negotiates.
By default the client prefers the newest version this SDK implements and negotiates down when the server asks it to. Pinning a version earlier than 2026-07-28 keeps the client on the initialize handshake.
func WithRootsHandler ¶ added in v0.43.0
func WithRootsHandler(handler RootsHandler) ClientOption
WithRootsHandler sets the roots handler for the client. WithRootsHandler returns a ClientOption that sets the client's RootsHandler. When provided, the client will declare the roots capability (ListChanged) during initialization.
func WithSamplingHandler ¶ added in v0.33.0
func WithSamplingHandler(handler SamplingHandler) ClientOption
WithSamplingHandler sets the sampling handler for the client. When set, the client will declare sampling capability during initialization.
func WithSession ¶ added in v0.33.0
func WithSession() ClientOption
WithSession assumes a MCP Session has already been initialized
func WithTracer ¶ added in v0.54.0
func WithTracer(tracer tracing.Tracer) ClientOption
WithTracer installs a tracer on the client. The tracer starts a client-kind span around every outgoing JSON-RPC method ("mcp.<method>"). For end-to-end propagation install a Propagator with WithPropagator as well. A nil tracer is treated as a no-op.
type ElicitationHandler ¶ added in v0.40.0
type ElicitationHandler interface {
// Elicit handles an elicitation request from the server and returns the user's response.
// The implementation should:
// 1. Present the request message to the user (and URL if in URL mode)
// 2. Validate input against the requested schema (for form mode)
// 3. Allow the user to accept, decline, or cancel
// 4. Return the appropriate response
Elicit(ctx context.Context, request mcp.ElicitationRequest) (*mcp.ElicitationResult, error)
}
ElicitationHandler defines the interface for handling elicitation requests from servers. Clients can implement this interface to request additional information from users.
type MCPClient ¶
type MCPClient interface {
// Initialize sends the initial connection request to the server
Initialize(
ctx context.Context,
request mcp.InitializeRequest,
) (*mcp.InitializeResult, error)
// Ping checks if the server is alive
Ping(ctx context.Context) error
// ListResourcesByPage manually list resources by page.
ListResourcesByPage(
ctx context.Context,
request mcp.ListResourcesRequest,
) (*mcp.ListResourcesResult, error)
// ListResources requests a list of available resources from the server
ListResources(
ctx context.Context,
request mcp.ListResourcesRequest,
) (*mcp.ListResourcesResult, error)
// ListResourceTemplatesByPage manually list resource templates by page.
ListResourceTemplatesByPage(
ctx context.Context,
request mcp.ListResourceTemplatesRequest,
) (*mcp.ListResourceTemplatesResult,
error)
// ListResourceTemplates requests a list of available resource templates from the server
ListResourceTemplates(
ctx context.Context,
request mcp.ListResourceTemplatesRequest,
) (*mcp.ListResourceTemplatesResult,
error)
// ReadResource reads a specific resource from the server
ReadResource(
ctx context.Context,
request mcp.ReadResourceRequest,
) (*mcp.ReadResourceResult, error)
// Subscribe requests notifications for changes to a specific resource
Subscribe(ctx context.Context, request mcp.SubscribeRequest) error
// Unsubscribe cancels notifications for a specific resource
Unsubscribe(ctx context.Context, request mcp.UnsubscribeRequest) error
// ListPromptsByPage manually list prompts by page.
ListPromptsByPage(
ctx context.Context,
request mcp.ListPromptsRequest,
) (*mcp.ListPromptsResult, error)
// ListPrompts requests a list of available prompts from the server
ListPrompts(
ctx context.Context,
request mcp.ListPromptsRequest,
) (*mcp.ListPromptsResult, error)
// GetPrompt retrieves a specific prompt from the server
GetPrompt(
ctx context.Context,
request mcp.GetPromptRequest,
) (*mcp.GetPromptResult, error)
// ListToolsByPage manually list tools by page.
ListToolsByPage(
ctx context.Context,
request mcp.ListToolsRequest,
) (*mcp.ListToolsResult, error)
// ListTools requests a list of available tools from the server
ListTools(
ctx context.Context,
request mcp.ListToolsRequest,
) (*mcp.ListToolsResult, error)
// CallTool invokes a specific tool on the server
CallTool(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error)
// SetLevel sets the logging level for the server
SetLevel(ctx context.Context, request mcp.SetLevelRequest) error
// Complete requests completion options for a given argument
Complete(
ctx context.Context,
request mcp.CompleteRequest,
) (*mcp.CompleteResult, error)
// Close client connection and cleanup resources
Close() error
// OnNotification registers a handler for notifications
OnNotification(handler func(notification mcp.JSONRPCNotification))
}
MCPClient represents an MCP client interface
type MemoryTokenStore ¶ added in v0.30.0
type MemoryTokenStore = transport.MemoryTokenStore
MemoryTokenStore is a convenience type that wraps transport.MemoryTokenStore
type OAuthAuthorizationRequiredError ¶ added in v0.30.0
type OAuthAuthorizationRequiredError = transport.OAuthAuthorizationRequiredError
OAuthAuthorizationRequiredError is returned when OAuth authorization is required
type OAuthConfig ¶ added in v0.30.0
type OAuthConfig = transport.OAuthConfig
OAuthConfig is a convenience type that wraps transport.OAuthConfig
type RootsHandler ¶ added in v0.43.0
type RootsHandler interface {
// ListRoots handles a list root request from the server and returns the roots list.
// The implementation should:
// 1. Validate input against the requested schema
// 2. Return the appropriate response
ListRoots(ctx context.Context, request mcp.ListRootsRequest) (*mcp.ListRootsResult, error)
}
RootsHandler defines the interface for handling roots requests from servers. Clients can implement this interface to provide roots list to servers.
type SamplingHandler ¶ added in v0.33.0
type SamplingHandler interface {
// CreateMessage handles a sampling request from the server and returns the generated message.
// The implementation should:
// 1. Validate the request parameters
// 2. Optionally prompt the user for approval (human-in-the-loop)
// 3. Select an appropriate model based on preferences
// 4. Generate the response using the selected model
// 5. Return the result with model information and stop reason
CreateMessage(ctx context.Context, request mcp.CreateMessageRequest) (*mcp.CreateMessageResult, error)
}
SamplingHandler defines the interface for handling sampling requests from servers. Clients can implement this interface to provide LLM sampling capabilities to servers.
type TokenStore ¶ added in v0.30.0
type TokenStore = transport.TokenStore
TokenStore is a convenience type that wraps transport.TokenStore