client

package
v0.37.1 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

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

Index

Constants

This section is empty.

Variables

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

func IsOAuthAuthorizationRequiredError

func IsOAuthAuthorizationRequiredError(err error) bool

IsOAuthAuthorizationRequiredError checks if an error is an OAuthAuthorizationRequiredError

func WithHTTPClient

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

func WithHeaderFunc

func WithHeaderFunc(headerFunc transport.HTTPHeaderFunc) transport.ClientOption

func WithHeaders

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

Types

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

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. Don't call the Start method manually. 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. Don't call the Start method manually. 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)

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)

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)

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) 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 negotiates with the server. Must be called after Start, and before any request methods.

func (*Client) IsInitialized

func (c *Client) IsInitialized() bool

IsInitialized returns true if the client has been initialized.

func (*Client) ListPrompts

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

func (*Client) ListPromptsByPage

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

func (*Client) ListResourceTemplates

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

func (*Client) ListResourceTemplatesByPage

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

func (*Client) ListResources

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

func (*Client) ListResourcesByPage

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

ListResourcesByPage manually list resources by page.

func (*Client) ListTools

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

func (*Client) ListToolsByPage

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

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.

func (*Client) Ping

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

func (*Client) ReadResource

func (c *Client) ReadResource(
	ctx context.Context,
	request mcp.ReadResourceRequest,
) (*mcp.ReadResourceResult, error)

func (*Client) SetLevel

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

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

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

func (*Client) Unsubscribe

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

type ClientOption

type ClientOption func(*Client)

func WithClientCapabilities

func WithClientCapabilities(capabilities mcp.ClientCapabilities) ClientOption

WithClientCapabilities sets the client capabilities for the client.

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

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 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