client

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package client provides MCP (Model Context Protocol) client implementations.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidFallbackPollInterval is returned when WaitForTask receives a
	// non-positive fallback polling interval.
	ErrInvalidFallbackPollInterval = errors.New("fallback poll interval must be greater than zero")
	// ErrServerPollIntervalOverflow is returned when a server-provided polling
	// interval cannot be represented by time.Duration.
	ErrServerPollIntervalOverflow = errors.New("server poll interval exceeds time.Duration")
)
View Source
var ErrAuthorizationServerChanged = transport.ErrAuthorizationServerChanged

ErrAuthorizationServerChanged indicates credentials or tokens belong to another issuer.

View Source
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.

View Source
var ErrRepeatedListCursor = errors.New("list cursor did not advance")

ErrRepeatedListCursor is returned when a paginated list repeats a cursor that was already requested. Following it would request the same page again.

View Source
var ErrRepeatedTaskListCursor = errors.New("tasks/list cursor did not advance")

ErrRepeatedTaskListCursor is returned when tasks/list repeats a cursor that was already requested. Following it would request the same page again.

View Source
var GenerateCodeChallenge = transport.GenerateCodeChallenge

GenerateCodeChallenge generates a code challenge from a code verifier

View Source
var GenerateCodeVerifier = transport.GenerateCodeVerifier

GenerateCodeVerifier generates a code verifier for PKCE

View Source
var GenerateState = transport.GenerateState

GenerateState generates a state parameter for OAuth

View Source
var NewMemoryTokenStore = transport.NewMemoryTokenStore

NewMemoryTokenStore is a convenience function that wraps transport.NewMemoryTokenStore

Functions

func GetEndpoint

func GetEndpoint(c *Client) *url.URL

GetEndpoint returns the current endpoint URL for the SSE connection.

Note: This method only works with SSE transport, or it will panic.

func GetOAuthHandler

func GetOAuthHandler(err error) *transport.OAuthHandler

GetOAuthHandler extracts the OAuthHandler from an OAuthAuthorizationRequiredError

func GetResourceMetadataURL

func GetResourceMetadataURL(err error) string

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

func GetStderr(c *Client) (io.Reader, bool)

GetStderr returns a reader for the stderr output of the subprocess. This can be used to capture error messages or logs from the subprocess.

The stdio transport drains the subprocess's stderr into a bounded buffer so the OS pipe never fills up and deadlocks the child. The returned reader yields the most recent output; older output is dropped once the buffer is full. To capture the full, real-time stream, use transport.WithCommandStderrWriter instead.

It works with any transport that exposes a Stderr() io.Reader method, including *transport.Stdio and *transport.CommandTransport.

func IsAuthorizationRequiredError

func IsAuthorizationRequiredError(err error) bool

IsAuthorizationRequiredError checks if an error is an AuthorizationRequiredError

func IsOAuthAuthorizationRequiredError

func IsOAuthAuthorizationRequiredError(err error) bool

IsOAuthAuthorizationRequiredError checks if an error is an OAuthAuthorizationRequiredError

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) transport.ClientOption

WithHTTPClient sets a custom HTTP client for the SSE transport.

func WithHTTPHost

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

func WithHeaderFunc(headerFunc transport.HTTPHeaderFunc) transport.ClientOption

WithHeaderFunc sets a function that returns headers for each SSE request.

func WithHeaders

func WithHeaders(headers map[string]string) transport.ClientOption

WithHeaders sets static headers for the SSE client.

Types

type AuthorizationRequiredError

type AuthorizationRequiredError = transport.AuthorizationRequiredError

AuthorizationRequiredError is returned when a 401 Unauthorized response is received

type Client

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

Client implements the MCP client.

func NewClient

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

func NewInProcessClient(server *server.MCPServer) (*Client, error)

NewInProcessClient connect directly to a mcp server object in the same process

func NewInProcessClientWithOptions

func NewInProcessClientWithOptions(mcpServer *server.MCPServer, options ...ClientOption) (*Client, error)

NewInProcessClientWithOptions connects directly to an MCP server and applies client options, including sampling, elicitation, and roots handlers, to the in-process transport.

func NewInProcessClientWithSamplingHandler

func NewInProcessClientWithSamplingHandler(server *server.MCPServer, handler SamplingHandler) (*Client, error)

NewInProcessClientWithSamplingHandler creates an in-process client with sampling support

func NewOAuthSSEClient

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

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

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

func NewStdioMCPClient(
	command string,
	env []string,
	args ...string,
) (*Client, error)

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

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

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

func (c *Client) CallTool(
	ctx context.Context,
	request mcp.CallToolRequest,
) (*mcp.CallToolResult, error)

CallTool invokes a tool on the server.

func (*Client) CancelTask

func (c *Client) CancelTask(
	ctx context.Context,
	request mcp.CancelTaskRequest,
) (*mcp.CancelTaskResult, error)

CancelTask returns canceled task result

func (*Client) Close

func (c *Client) Close() error

Close shuts down the client and closes the transport.

func (*Client) Complete

func (c *Client) Complete(
	ctx context.Context,
	request mcp.CompleteRequest,
) (*mcp.CompleteResult, error)

Complete requests completion suggestions from the server.

func (*Client) Discover

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

func (c *Client) GetClientCapabilities() mcp.ClientCapabilities

GetClientCapabilities returns the client capabilities.

func (*Client) GetPrompt

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

func (c *Client) GetServerCapabilities() mcp.ServerCapabilities

GetServerCapabilities returns the server capabilities.

func (*Client) GetSessionId

func (c *Client) GetSessionId() string

GetSessionId returns the session ID of the transport. If the transport does not support sessions, it returns an empty string.

func (*Client) GetTask

func (c *Client) GetTask(
	ctx context.Context,
	request mcp.GetTaskRequest,
) (*mcp.GetTaskResult, error)

GetTask returns task with current status

func (*Client) GetTransport

func (c *Client) GetTransport() transport.Interface

GetTransport gives access to the underlying transport layer. Cast it to the specific transport type and obtain the other helper methods.

func (*Client) Initialize

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 without identifying a modern server, the server is taken to be legacy, and the classic initialize handshake is performed instead. A successful discovery or an UnsupportedProtocolVersionError with a supported list identifies a modern server; negotiation failures are returned to the caller rather than falling back to the legacy handshake.

func (*Client) IsInitialized

func (c *Client) IsInitialized() bool

IsInitialized returns true if the client has been initialized.

func (*Client) IterPrompts

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. Each iteration starts from the cursor in the original request. 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

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. Each iteration starts from the cursor in the original request. 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

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. Each iteration starts from the cursor in the original request. 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

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. Each iteration starts from the cursor in the original request. 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

func (c *Client) ListPrompts(
	ctx context.Context,
	request mcp.ListPromptsRequest,
) (*mcp.ListPromptsResult, error)

ListPrompts lists all prompts by following paginated responses.

func (*Client) ListPromptsByPage

func (c *Client) ListPromptsByPage(
	ctx context.Context,
	request mcp.ListPromptsRequest,
) (*mcp.ListPromptsResult, error)

ListPromptsByPage manually lists prompts by page.

func (*Client) ListResourceTemplates

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

func (c *Client) ListResourceTemplatesByPage(
	ctx context.Context,
	request mcp.ListResourceTemplatesRequest,
) (*mcp.ListResourceTemplatesResult, error)

ListResourceTemplatesByPage manually lists resource templates by page.

func (*Client) ListResources

func (c *Client) ListResources(
	ctx context.Context,
	request mcp.ListResourcesRequest,
) (*mcp.ListResourcesResult, error)

ListResources lists all resources by following paginated responses.

func (*Client) ListResourcesByPage

func (c *Client) ListResourcesByPage(
	ctx context.Context,
	request mcp.ListResourcesRequest,
) (*mcp.ListResourcesResult, error)

ListResourcesByPage manually list resources by page.

func (*Client) ListTasks

func (c *Client) ListTasks(
	ctx context.Context,
	request mcp.ListTasksRequest,
) (*mcp.ListTasksResult, error)

ListTasks lists all tasks by following paginated responses.

func (*Client) ListTasksByPage

func (c *Client) ListTasksByPage(
	ctx context.Context,
	request mcp.ListTasksRequest,
) (*mcp.ListTasksResult, error)

ListTasksByPage lists one page of tasks.

func (*Client) ListTools

func (c *Client) ListTools(
	ctx context.Context,
	request mcp.ListToolsRequest,
) (*mcp.ListToolsResult, error)

ListTools lists all tools by following paginated responses.

func (*Client) ListToolsByPage

func (c *Client) ListToolsByPage(
	ctx context.Context,
	request mcp.ListToolsRequest,
) (*mcp.ListToolsResult, error)

ListToolsByPage manually lists tools by page.

func (*Client) Listen

func (c *Client) Listen(ctx context.Context, filter mcp.SubscriptionFilter) error

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

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

func (c *Client) OnConnectionLost(handler func(error))

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

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. Handlers registered during dispatch receive subsequent notifications.

func (*Client) PendingSubscriptionFilter

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

func (c *Client) Ping(ctx context.Context) error

Ping sends a ping request to verify the server is responsive.

Deprecated: the ping RPC was removed in protocol version 2026-07-28 (SEP-2575); liveness is a transport concern there. On a modern connection this method succeeds without sending anything.

func (*Client) ProtocolVersion

func (c *Client) ProtocolVersion() string

ProtocolVersion returns the protocol version in effect for this client, or "" before the connection has been established.

func (*Client) ReadResource

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

func (c *Client) RootListChanges(
	ctx context.Context,
) error

RootListChanges sends a roots list-changed notification to the server.

func (*Client) SetLevel deprecated

func (c *Client) SetLevel(
	ctx context.Context,
	request mcp.SetLevelRequest,
) error

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

func (c *Client) Start(ctx context.Context) error

Start initiates the connection to the server. Must be called before using the client.

func (*Client) Subscribe deprecated

func (c *Client) Subscribe(
	ctx context.Context,
	request mcp.SubscribeRequest,
) error

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

func (c *Client) TaskResult(
	ctx context.Context,
	request mcp.TaskResultRequest,
) (*mcp.TaskResultResult, error)

TaskResult returns finished task result

func (*Client) Unsubscribe deprecated

func (c *Client) Unsubscribe(
	ctx context.Context,
	request mcp.UnsubscribeRequest,
) error

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.

func (*Client) WaitForTask

func (c *Client) WaitForTask(
	ctx context.Context,
	request mcp.GetTaskRequest,
	fallbackPollInterval time.Duration,
) (*mcp.GetTaskResult, error)

WaitForTask polls a task until it reaches a terminal state or the context is done. The server-provided poll interval takes precedence over fallbackPollInterval.

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client during construction.

func WithClientCapabilities

func WithClientCapabilities(capabilities mcp.ClientCapabilities) ClientOption

WithClientCapabilities sets the client capabilities for the client.

func WithDiscoverTimeout

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

func WithElicitationHandler(handler ElicitationHandler) ClientOption

WithElicitationHandler sets the elicitation handler for the client. When set, the client will declare elicitation capability during initialization.

func WithInvalidToolHandler

func WithInvalidToolHandler(handler InvalidToolHandler) ClientOption

WithInvalidToolHandler sets the handler notified about tools excluded for their invalid x-mcp-header annotations.

Exclusion itself is unchanged: the tool is still dropped from the listing and forgotten from the cache, and the warning is still logged. Without this option, that warning is the only signal that a tool disappeared.

func WithLegacyProtocolOnly deprecated

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

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

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

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

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

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

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

func WithSession() ClientOption

WithSession assumes a MCP Session has already been initialized

func WithTracer

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

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 InvalidToolHandler

type InvalidToolHandler func(ctx context.Context, tool mcp.Tool, err error)

InvalidToolHandler is called for each tool definition that ListTools, ListToolsByPage and IterTools exclude because its x-mcp-header annotations violate SEP-2243. err is the error returned by mcp.ValidateParamHeaderAnnotations.

The handler runs synchronously on the goroutine that listed the tools, once per excluded tool and page, with that request's context, so a caller can correlate the call with its own span or request. It must not block.

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

type MemoryTokenStore = transport.MemoryTokenStore

MemoryTokenStore is a convenience type that wraps transport.MemoryTokenStore

type OAuthAuthorizationRequiredError

type OAuthAuthorizationRequiredError = transport.OAuthAuthorizationRequiredError

OAuthAuthorizationRequiredError is returned when OAuth authorization is required

type OAuthConfig

type OAuthConfig = transport.OAuthConfig

OAuthConfig is a convenience type that wraps transport.OAuthConfig

type RootsHandler

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

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 Token

type Token = transport.Token

Token is a convenience type that wraps transport.Token

type TokenStore

type TokenStore = transport.TokenStore

TokenStore is a convenience type that wraps transport.TokenStore

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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