client

package
v1.7.2 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: MIT Imports: 34 Imported by: 0

Documentation

Overview

Package client provides the client-side implementation of the MCP protocol.

This package contains the Client interface and implementation for communicating with MCP services. It enables Go applications to interact with MCP servers through a clean, type-safe API that handles all aspects of the protocol, including version negotiation, connection management, and request/response handling.

Basic Usage

// Create a new client and connect to an MCP server
client, err := client.NewClient("my-client",
	client.WithProtocolVersion("2025-03-26"),
	client.WithLogger(logger),
)
if err != nil {
	log.Fatalf("Failed to connect: %v", err)
}
defer client.Close()

// Call a tool
result, err := client.CallTool("calculate", map[string]interface{}{
	"operation": "add",
	"values": []float64{1.5, 2.5, 3.0},
})

Client Options

The NewClient function accepts various options to customize client behavior:

  • WithProtocolVersion: Set a specific protocol version
  • WithProtocolNegotiation: Enable/disable automatic protocol negotiation
  • WithLogger: Configure a custom logger
  • WithTransport: Specify a custom transport implementation
  • WithRequestTimeout: Set request timeout duration
  • WithConnectionTimeout: Set connection timeout duration
  • WithSamplingOptimizations: Configure sampling performance optimizations

Thread Safety

All Client methods are thread-safe and can be called concurrently from multiple goroutines.

Package client provides the client-side implementation of the MCP protocol.

Package client provides the client-side implementation of the MCP protocol.

Package client provides the client-side implementation of the MCP protocol.

Package client provides the client-side implementation of the MCP protocol.

Package client provides the client-side implementation of the MCP protocol.

Package client provides the client-side implementation of the MCP protocol.

Package client provides the client-side implementation of the MCP protocol.

Package client provides the client-side implementation of the MCP protocol.

Package client provides the client-side implementation of the MCP protocol.

Package client provides the client-side implementation of the MCP protocol.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultGRPCClientOptions added in v1.2.1

func DefaultGRPCClientOptions() []grpc.Option

DefaultGRPCClientOptions returns a set of default options for gRPC client.

func NewLogger added in v1.6.0

func NewLogger(opts ...LoggerOption) *slog.Logger

NewLogger creates a logger with the specified options. By default, creates a logger that writes to stderr with Info level.

func WithGRPCKeepAlive added in v1.2.1

func WithGRPCKeepAlive(time, timeout time.Duration) grpc.Option

WithGRPCKeepAlive configures keepalive parameters for the gRPC transport.

func WithGRPCMaxMessageSize added in v1.2.1

func WithGRPCMaxMessageSize(size int) grpc.Option

WithGRPCMaxMessageSize sets the maximum message size for the gRPC transport.

func WithGRPCTLS added in v1.2.1

func WithGRPCTLS(certFile, keyFile, caFile string) grpc.Option

WithGRPCTLS configures TLS for the gRPC transport.

func WithGRPCTimeout added in v1.2.1

func WithGRPCTimeout(timeout time.Duration) grpc.Option

WithGRPCTimeout sets the connection timeout for the gRPC transport.

Types

type BatchError added in v1.5.0

type BatchError struct {
	// Code is the JSON-RPC error code
	Code int `json:"code"`

	// Message is a human-readable error message
	Message string `json:"message"`

	// Data contains additional error information
	Data interface{} `json:"data,omitempty"`
}

BatchError represents an error within a batch response.

type BatchRequest added in v1.5.0

type BatchRequest struct {
	// Method is the JSON-RPC method to call (e.g., "tools/call", "resources/read")
	Method string `json:"method"`

	// Params contains the parameters for the method call
	Params map[string]interface{} `json:"params,omitempty"`

	// ID is the request identifier. If nil, this is treated as a notification.
	// Notifications do not generate responses.
	ID interface{} `json:"id,omitempty"`
}

BatchRequest represents a single request within a batch operation.

type BatchRequestBuilder added in v1.5.0

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

BatchRequestBuilder provides a fluent interface for constructing batch requests.

func (*BatchRequestBuilder) AddRequest added in v1.5.0

func (b *BatchRequestBuilder) AddRequest(method string, params map[string]interface{}, id interface{}) *BatchRequestBuilder

AddRequest adds a request to the batch. For requests that expect a response, provide an ID. For notifications, set ID to nil.

func (*BatchRequestBuilder) Execute added in v1.5.0

func (b *BatchRequestBuilder) Execute(opts ...RequestOption) ([]BatchResponse, error)

Execute sends the batch request and returns the responses.

type BatchResponse added in v1.5.0

type BatchResponse struct {
	// ID is the request identifier that this response corresponds to
	ID interface{} `json:"id"`

	// Result contains the successful result of the method call
	Result interface{} `json:"result,omitempty"`

	// Error contains error information if the method call failed
	Error *BatchError `json:"error,omitempty"`
}

BatchResponse represents a single response within a batch operation.

type Client

type Client interface {
	// CallTool invokes a tool on the connected MCP server.
	//
	// The name parameter specifies the tool to call. The args parameter contains
	// the arguments to pass to the tool as key-value pairs. The returned interface{}
	// contains the tool's output, which can be any JSON-serializable value.
	//
	// Example:
	//  result, err := client.CallTool("translate", map[string]interface{}{
	//      "text": "Hello world",
	//      "target_language": "Spanish",
	//  })
	//
	// For timeout support:
	//  result, err := client.CallTool("translate", map[string]interface{}{
	//      "text": "Hello world",
	//      "target_language": "Spanish",
	//  }, client.WithRequestTimeoutOption(10*time.Second))
	CallTool(name string, args map[string]interface{}, opts ...RequestOption) (interface{}, error)

	// GetResource retrieves a resource from the server.
	//
	// The path parameter specifies the resource URI to retrieve.
	//
	// Example:
	//  resource, err := client.GetResource("/files/readme.txt")
	//  // Access content based on protocol version:
	//  if len(resource.Content) > 0 {
	//      // 2024-11-05 format
	//      fmt.Println("Text:", resource.Content[0].Text)
	//  } else if len(resource.Contents) > 0 {
	//      // 2025-03-26 format
	//      fmt.Println("Text:", resource.Contents[0].Content[0].Text)
	//  }
	//
	// For timeout support:
	//  resource, err := client.GetResource("/files/readme.txt",
	//      client.WithRequestTimeoutOption(5*time.Second))
	//
	// For passing additional parameters:
	//  resource, err := client.GetResource("/api/users",
	//      client.WithResourceParams(map[string]interface{}{
	//          "include_posts": true,
	//          "limit": 50,
	//      }),
	//      client.WithRequestTimeoutOption(5*time.Second))
	GetResource(path string, opts ...RequestOption) (*ResourceResponse, error)

	// GetPrompt retrieves a prompt from the server.
	//
	// The name parameter specifies the prompt to retrieve. The variables parameter
	// contains any variables to substitute in the prompt template.
	//
	// Example:
	//  prompt, err := client.GetPrompt("greeting", map[string]interface{}{
	//      "name": "Alice",
	//  })
	//
	// For timeout support:
	//  prompt, err := client.GetPrompt("greeting", map[string]interface{}{
	//      "name": "Alice",
	//  }, client.WithRequestTimeoutOption(3*time.Second))
	GetPrompt(name string, variables map[string]interface{}, opts ...RequestOption) (*PromptResponse, error)

	// GetRoot retrieves the root resource from the server.
	//
	// This is a convenience method equivalent to calling GetResource("/").
	//
	// Example:
	//  root, err := client.GetRoot()
	//  // Access content based on protocol version:
	//  if len(root.Content) > 0 {
	//      // 2024-11-05 format
	//      fmt.Println("Root text:", root.Content[0].Text)
	//  } else if len(root.Contents) > 0 {
	//      // 2025-03-26 format
	//      fmt.Println("Root text:", root.Contents[0].Content[0].Text)
	//  }
	GetRoot() (*ResourceResponse, error)

	// Close closes the client connection to the server and releases all resources.
	//
	// After calling Close, the client cannot be used for further operations.
	// It is good practice to defer this call after creating a client.
	//
	// Example:
	//  client, err := client.NewClient("my-client")
	//  if err != nil {
	//      log.Fatal(err)
	//  }
	//  defer client.Close()
	Close() error

	// AddRoot registers a new root endpoint with the server.
	//
	// The uri parameter specifies the path of the root. The name parameter
	// provides a human-readable name for the root.
	//
	// Example:
	//  err := client.AddRoot("/api/v2", "API Version 2")
	AddRoot(uri string, name string) error

	// RemoveRoot unregisters a root endpoint from the server.
	//
	// The uri parameter specifies the path of the root to remove.
	//
	// Example:
	//  err := client.RemoveRoot("/api/v1")
	RemoveRoot(uri string) error

	// GetRoots retrieves the list of root endpoints from the server.
	//
	// The returned slice contains all registered roots with their URIs and names.
	//
	// Example:
	//  roots, err := client.GetRoots()
	//  for _, root := range roots {
	//      fmt.Printf("Root: %s (%s)\n", root.URI, root.Name)
	//  }
	GetRoots() ([]Root, error)

	// ListTools retrieves the list of available tools from the server.
	//
	// This method calls the tools/list endpoint as specified in the MCP protocol.
	// It automatically handles pagination internally and returns all available tools.
	// The returned slice contains all available tools with their names, descriptions,
	// and input schemas, which can be used for tool discovery and proxy patterns.
	//
	// Example:
	//  tools, err := client.ListTools()
	//  for _, tool := range tools {
	//      fmt.Printf("Tool: %s - %s\n", tool.Name, tool.Description)
	//      fmt.Printf("Schema: %+v\n", tool.InputSchema)
	//  }
	ListTools() ([]Tool, error)

	// ListResources retrieves the list of available resources from the server.
	//
	// This method calls the resources/list endpoint as specified in the MCP protocol.
	// It automatically handles pagination internally and returns all available resources.
	// The returned slice contains all available resources with their URIs, names,
	// descriptions, and MIME types, which can be used for resource discovery.
	//
	// Example:
	//  resources, err := client.ListResources()
	//  for _, resource := range resources {
	//      fmt.Printf("Resource: %s - %s\n", resource.Name, resource.Description)
	//      fmt.Printf("URI: %s, MIME Type: %s\n", resource.URI, resource.MimeType)
	//  }
	ListResources(opts ...RequestOption) ([]Resource, error)

	// ListPrompts retrieves the list of available prompts from the server.
	//
	// This method calls the prompts/list endpoint as specified in the MCP protocol.
	// It automatically handles pagination internally and returns all available prompts.
	// The returned slice contains all available prompts with their names, descriptions,
	// and argument specifications, which can be used for prompt discovery.
	//
	// Example:
	//  prompts, err := client.ListPrompts()
	//  for _, prompt := range prompts {
	//      fmt.Printf("Prompt: %s - %s\n", prompt.Name, prompt.Description)
	//      fmt.Printf("Arguments: %d\n", len(prompt.Arguments))
	//  }
	ListPrompts(opts ...RequestOption) ([]Prompt, error)

	// Version returns the negotiated protocol version with the server.
	//
	// This returns one of the standardized version strings: "draft", "2024-11-05",
	// or "2025-03-26".
	//
	// Example:
	//  version := client.Version()
	//  fmt.Printf("Connected using MCP protocol version %s\n", version)
	Version() string

	// IsInitialized returns whether the client has been initialized.
	//
	// Initialization occurs during the first operation that requires
	// server communication.
	IsInitialized() bool

	// IsConnected returns whether the client is currently connected to the server.
	//
	// Example:
	//  if client.IsConnected() {
	//      fmt.Println("Client is connected to the server")
	//  } else {
	//      fmt.Println("Client is not connected")
	//  }
	IsConnected() bool

	// WithSamplingHandler registers a handler for sampling requests.
	//
	// The handler will be called when the server requests sampling (e.g., for LLM interactions).
	// Returns the client instance for method chaining.
	//
	// Example:
	//  client = client.WithSamplingHandler(func(params SamplingCreateMessageParams) (SamplingResponse, error) {
	//      // Process sampling request
	//      return SamplingResponse{...}, nil
	//  })
	WithSamplingHandler(handler SamplingHandler) Client

	// GetSamplingHandler returns the currently registered sampling handler.
	GetSamplingHandler() SamplingHandler

	// Events returns the events subject for subscribing to client events.
	//
	// This provides access to the event system for monitoring client lifecycle,
	// errors, and other significant events. Subscribers can listen for specific
	// event types such as initialization, connection changes, and errors.
	//
	// Example:
	//  events := client.Events()
	//  events.Subscribe(events.TopicClientError, func(event events.ClientErrorEvent) {
	//      log.Printf("Client error: %s", event.Error)
	//  })
	Events() *events.Subject

	// RequestSampling initiates a sampling request to the server.
	//
	// This is the unified method for all sampling operations, supporting both
	// regular and streaming modes through options configuration.
	//
	// Example:
	//  opts := client.NewSamplingOptions(messages, prefs).
	//      WithSystemPrompt("You are a helpful assistant").
	//      WithMaxTokens(1000)
	//  response, err := client.RequestSampling(opts)
	//
	// For streaming (protocol version 2025-03-26 only):
	//  opts := client.NewSamplingOptions(messages, prefs).
	//      WithStreaming(func(chunk *SamplingResponse) error {
	//          fmt.Printf("Received chunk: %s\n", chunk.Content.Text)
	//          return nil
	//      })
	//  response, err := client.RequestSampling(opts)
	RequestSampling(opts *SamplingOptions) (*SamplingResponse, error)

	// SendBatch sends multiple requests to the server in a single batch operation.
	//
	// This method implements JSON-RPC 2.0 batch requests, allowing multiple operations
	// to be sent together for improved efficiency. The requests parameter contains
	// the individual requests to include in the batch.
	//
	// The method returns a slice of BatchResponse objects, where each response
	// corresponds to a request in the batch (excluding notifications). The order
	// of responses matches the order of requests.
	//
	// Example:
	//  requests := []BatchRequest{
	//      {Method: "tools/call", Params: map[string]interface{}{"name": "calculator", "arguments": map[string]interface{}{"op": "add", "a": 1, "b": 2}}},
	//      {Method: "resources/read", Params: map[string]interface{}{"uri": "/config.json"}},
	//      {Method: "prompts/get", Params: map[string]interface{}{"name": "greeting", "arguments": map[string]interface{}{"name": "Alice"}}},
	//  }
	//  responses, err := client.SendBatch(requests)
	//  for i, response := range responses {
	//      if response.Error != nil {
	//          fmt.Printf("Request %d failed: %v\n", i, response.Error)
	//      } else {
	//          fmt.Printf("Request %d result: %v\n", i, response.Result)
	//      }
	//  }
	//
	// For timeout support:
	//  responses, err := client.SendBatch(requests, client.WithRequestTimeoutOption(30*time.Second))
	SendBatch(requests []BatchRequest, opts ...RequestOption) ([]BatchResponse, error)

	// BatchBuilder creates a new batch builder for constructing batch requests.
	//
	// The batch builder provides a fluent interface for adding multiple requests
	// to a batch operation. Use AddRequest to add individual requests.
	//
	// Example:
	//  responses, err := client.BatchBuilder().
	//      AddRequest("tools/call", map[string]interface{}{
	//          "name": "calculator",
	//          "arguments": map[string]interface{}{"op": "add", "a": 1, "b": 2}
	//      }, 1).
	//      AddRequest("resources/read", map[string]interface{}{"uri": "/config.json"}, 2).
	//      AddRequest("prompts/get", map[string]interface{}{
	//          "name": "greeting",
	//          "arguments": map[string]interface{}{"name": "Alice"}
	//      }, 3).
	//      Execute()
	BatchBuilder() *BatchRequestBuilder

	// GetServerCapabilities returns the server's declared capabilities from initialization.
	//
	// This method returns the capabilities that the server declared during the MCP
	// initialization handshake. These capabilities indicate which optional protocol
	// features are supported by the server, such as resources, prompts, tools, and
	// logging. Returns nil if the client has not been initialized yet.
	//
	// Example:
	//  caps := client.GetServerCapabilities()
	//  if caps != nil && caps.Resources != nil {
	//      fmt.Println("Server supports resources")
	//      if caps.Resources.Subscribe {
	//          fmt.Println("Server supports resource subscriptions")
	//      }
	//  }
	GetServerCapabilities() *ServerCapabilities

	// GetServerInfo returns the server's identification information from initialization.
	//
	// This method returns the server information (name, version) that was provided
	// during the MCP initialization handshake. Returns nil if the client has not
	// been initialized yet.
	//
	// Example:
	//  info := client.GetServerInfo()
	//  if info != nil {
	//      fmt.Printf("Connected to %s version %s\n", info.Name, info.Version)
	//  }
	GetServerInfo() *ServerInfo

	// GetServerInstructions returns optional instructions provided by the server.
	//
	// This method returns any optional instructions that the server provided during
	// initialization (available in MCP protocol version 2025-03-26). Returns an
	// empty string if no instructions were provided or if using an older protocol version.
	//
	// Example:
	//  instructions := client.GetServerInstructions()
	//  if instructions != "" {
	//      fmt.Printf("Server instructions: %s\n", instructions)
	//  }
	GetServerInstructions() string

	// HasCapability checks if the server supports a specific top-level capability.
	//
	// This is a convenience method for checking server capability support. The
	// capability parameter should be one of: "logging", "prompts", "resources",
	// "tools", or "experimental". Returns false if the client has not been
	// initialized or if the capability is not supported.
	//
	// Example:
	//  if client.HasCapability("resources") {
	//      resources, err := client.ListResources()
	//      // ... handle resources
	//  }
	HasCapability(capability string) bool

	// SupportsResourceSubscriptions checks if the server supports resource change subscriptions.
	//
	// This is a convenience method for checking if the server's resource capability
	// includes the "subscribe" sub-capability, which allows clients to receive
	// notifications when specific resources change. Returns false if the server
	// doesn't support resources or subscriptions.
	//
	// Example:
	//  if client.SupportsResourceSubscriptions() {
	//      // Can subscribe to resource changes
	//  }
	SupportsResourceSubscriptions() bool

	// SupportsListChangedNotifications checks if the server supports list change notifications.
	//
	// This method checks if the server supports notifications when the list of items
	// of a specific type changes. The resourceType parameter should be one of:
	// "prompts", "resources", or "tools". Returns false if the server doesn't
	// support the specified resource type or list change notifications.
	//
	// Example:
	//  if client.SupportsListChangedNotifications("resources") {
	//      // Server will notify when the resource list changes
	//  }
	SupportsListChangedNotifications(resourceType string) bool

	// Ping sends a ping request to the server to verify connection health.
	Ping() error

	// WaitForReady waits for the client to be fully connected and ready to handle requests.
	//
	// This method blocks until the client is connected, initialized, and can successfully
	// ping the server, or until the timeout is reached. It's useful for ensuring the
	// server is fully ready before making API calls.
	//
	// Example:
	//  if err := client.WaitForReady(5 * time.Second); err != nil {
	//      log.Fatal("Server not ready:", err)
	//  }
	//  // Now safe to make API calls
	//  tools, err := client.ListTools()
	WaitForReady(timeout time.Duration) error

	// GetServerStatus returns the status of a managed MCP server.
	//
	// This method is only available for clients created with WithServersFromConfig
	// or WithServerConfig options. It returns the running status, any errors,
	// and process information for the specified server.
	//
	// Example:
	//  status := client.GetServerStatus("file-server")
	//  if !status.Running {
	//      log.Printf("File server is not running: %v", status.Error)
	//  }
	GetServerStatus(serverName string) *ServerStatus

	// RestartServer attempts to restart a managed MCP server.
	//
	// This method is only available for clients created with WithServersFromConfig
	// or WithServerConfig options. It stops the specified server if running and
	// starts it again with the same configuration.
	//
	// Example:
	//  err := client.RestartServer("file-server")
	//  if err != nil {
	//      log.Fatalf("Failed to restart server: %v", err)
	//  }
	RestartServer(serverName string) error
}

Client represents an MCP client for communicating with MCP servers. It provides methods for all MCP operations including tool calls, resource access, prompt rendering, root management, and sampling functionality.

func NewClient

func NewClient(url string, options ...Option) (Client, error)

NewClient creates a new MCP client with the given URL and options. The client will automatically detect and adapt to the server's MCP specification version. It immediately establishes a connection to the server and returns an error if the connection fails.

The url parameter is interpreted based on its format:

  • "stdio:///": Uses Standard I/O for communication (useful for child processes)
  • "ws://host:port/path": Uses WebSocket protocol
  • "http://host:port/path": Uses HTTP protocol
  • "sse://host:port/path": Uses Server-Sent Events protocol
  • Custom schemes can be handled with a custom Transport implementation

Errors returned by NewClient may include:

  • Connection failures (e.g., server unreachable)
  • Protocol negotiation failures
  • Transport initialization errors

Example:

// Basic client with default options
client, err := client.NewClient("ws://localhost:8080/mcp")
if err != nil {
	log.Fatalf("Failed to create client: %v", err)
}

// Client with custom options
client, err := client.NewClient("http://api.example.com/mcp",
	client.WithProtocolVersion("2025-03-26"),
	client.WithLogger(myCustomLogger),
	client.WithRequestTimeout(time.Second * 20),
)

type ClientCapabilities added in v1.2.0

type ClientCapabilities struct {
	Roots        RootsCapability        `json:"roots,omitempty"`
	Sampling     map[string]interface{} `json:"sampling,omitempty"`
	Experimental map[string]interface{} `json:"experimental,omitempty"`
}

ClientCapabilities represents the capabilities supported by this client.

type ContentItem added in v1.6.0

type ContentItem struct {
	Type     string      `json:"type"`
	Text     string      `json:"text,omitempty"`
	ImageURL string      `json:"imageUrl,omitempty"`
	AltText  string      `json:"altText,omitempty"`
	URL      string      `json:"url,omitempty"`
	Title    string      `json:"title,omitempty"`
	Blob     string      `json:"blob,omitempty"`
	MimeType string      `json:"mimeType,omitempty"`
	Data     interface{} `json:"data,omitempty"`
	Filename string      `json:"filename,omitempty"`
}

ContentItem represents a content item in a resource response.

type EmbeddedOption added in v1.6.4

type EmbeddedOption func(*embeddedConfig)

EmbeddedOption is a function that configures an embedded transport. These options allow customizing the behavior of the embedded client connection.

func WithEmbeddedTimeout added in v1.6.4

func WithEmbeddedTimeout(timeout time.Duration) EmbeddedOption

WithEmbeddedTimeout sets the timeout for embedded transport operations.

type EmbeddedTransport added in v1.6.2

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

EmbeddedTransport implements the Transport interface for embedded (in-process) communication.

func NewEmbeddedTransport added in v1.6.2

func NewEmbeddedTransport(transport *embedded.Transport) *EmbeddedTransport

NewEmbeddedTransport creates a new embedded transport client.

func (*EmbeddedTransport) Connect added in v1.6.2

func (t *EmbeddedTransport) Connect() error

Connect implements the Transport interface.

func (*EmbeddedTransport) ConnectWithContext added in v1.6.2

func (t *EmbeddedTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext implements the Transport interface.

func (*EmbeddedTransport) Disconnect added in v1.6.2

func (t *EmbeddedTransport) Disconnect() error

Disconnect implements the Transport interface.

func (*EmbeddedTransport) RegisterNotificationHandler added in v1.6.2

func (t *EmbeddedTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler implements the Transport interface.

func (*EmbeddedTransport) Send added in v1.6.2

func (t *EmbeddedTransport) Send(message []byte) ([]byte, error)

Send implements the Transport interface.

func (*EmbeddedTransport) SendWithContext added in v1.6.2

func (t *EmbeddedTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext implements the Transport interface.

func (*EmbeddedTransport) SetConnectionTimeout added in v1.6.2

func (t *EmbeddedTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout implements the Transport interface.

func (*EmbeddedTransport) SetRequestTimeout added in v1.6.2

func (t *EmbeddedTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout implements the Transport interface.

type GRPCTransport added in v1.2.1

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

GRPCTransport wraps a grpc.Transport to implement the client.Transport interface

func (*GRPCTransport) Connect added in v1.2.1

func (t *GRPCTransport) Connect() error

Connect establishes a connection to the server

func (*GRPCTransport) ConnectWithContext added in v1.2.1

func (t *GRPCTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext establishes a connection to the server with context

func (*GRPCTransport) Disconnect added in v1.2.1

func (t *GRPCTransport) Disconnect() error

Disconnect closes the connection to the server

func (*GRPCTransport) RegisterNotificationHandler added in v1.2.1

func (t *GRPCTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler registers a handler for server-initiated messages

func (*GRPCTransport) Send added in v1.2.1

func (t *GRPCTransport) Send(message []byte) ([]byte, error)

Send sends a message to the server and waits for a response

func (*GRPCTransport) SendWithContext added in v1.2.1

func (t *GRPCTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext sends a message with context for timeout/cancellation

func (*GRPCTransport) SetConnectionTimeout added in v1.2.1

func (t *GRPCTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout sets the default timeout for connection operations

func (*GRPCTransport) SetRequestTimeout added in v1.2.1

func (t *GRPCTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout sets the default timeout for request operations

type HTTPOption added in v1.2.2

type HTTPOption func(*httpConfig)

HTTPOption is a function that configures an HTTP transport. These options allow customizing the behavior of the HTTP client connection.

func WithHTTPClient added in v0.1.11

func WithHTTPClient(client *http.Client) HTTPOption

WithHTTPClient sets a custom HTTP client for the HTTP transport.

func WithHTTPHeader added in v1.2.2

func WithHTTPHeader(key, value string) HTTPOption

WithHTTPHeader adds a custom header to HTTP requests.

func WithHTTPHeaders added in v1.2.2

func WithHTTPHeaders(headers map[string]string) HTTPOption

WithHTTPHeaders sets multiple custom headers for HTTP requests.

func WithHTTPPollInterval added in v1.2.2

func WithHTTPPollInterval(interval time.Duration) HTTPOption

WithHTTPPollInterval sets the interval for long-polling in HTTP transport.

func WithHTTPRetry added in v1.2.2

func WithHTTPRetry(attempts int, delay time.Duration) HTTPOption

WithHTTPRetry configures retry behavior for HTTP requests.

func WithHTTPTimeout added in v1.2.2

func WithHTTPTimeout(timeout time.Duration) HTTPOption

WithHTTPTimeout sets a specific timeout for HTTP operations.

type HTTPTransportAdapter added in v1.2.2

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

HTTPTransportAdapter adapts the HTTP transport to the client Transport interface.

func NewHTTPTransportAdapter added in v1.2.2

func NewHTTPTransportAdapter(url string) *HTTPTransportAdapter

NewHTTPTransportAdapter creates a new HTTP transport adapter.

func (*HTTPTransportAdapter) AddHeader added in v1.2.2

func (t *HTTPTransportAdapter) AddHeader(key, value string)

AddHeader adds a custom header to all HTTP requests.

func (*HTTPTransportAdapter) Connect added in v1.2.2

func (t *HTTPTransportAdapter) Connect() error

Connect implements the Transport interface Connect method.

func (*HTTPTransportAdapter) ConnectWithContext added in v1.2.2

func (t *HTTPTransportAdapter) ConnectWithContext(ctx context.Context) error

ConnectWithContext implements the Transport interface ConnectWithContext method.

func (*HTTPTransportAdapter) Disconnect added in v1.2.2

func (t *HTTPTransportAdapter) Disconnect() error

Disconnect implements the Transport interface Disconnect method.

func (*HTTPTransportAdapter) GetAddr added in v1.2.2

func (t *HTTPTransportAdapter) GetAddr() string

GetAddr returns the transport's address.

func (*HTTPTransportAdapter) RegisterNotificationHandler added in v1.2.2

func (t *HTTPTransportAdapter) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler implements the Transport interface.

func (*HTTPTransportAdapter) Send added in v1.2.2

func (t *HTTPTransportAdapter) Send(message []byte) ([]byte, error)

Send implements the Transport interface Send method.

func (*HTTPTransportAdapter) SendWithContext added in v1.2.2

func (t *HTTPTransportAdapter) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext implements the Transport interface SendWithContext method.

func (*HTTPTransportAdapter) SetClient added in v1.2.2

func (t *HTTPTransportAdapter) SetClient(client *http.Client)

SetClient sets a custom HTTP client.

func (*HTTPTransportAdapter) SetConnectionTimeout added in v1.2.2

func (t *HTTPTransportAdapter) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout implements the Transport interface.

func (*HTTPTransportAdapter) SetPollInterval added in v1.2.2

func (t *HTTPTransportAdapter) SetPollInterval(interval time.Duration)

SetPollInterval sets the interval for HTTP long-polling.

func (*HTTPTransportAdapter) SetRequestTimeout added in v1.2.2

func (t *HTTPTransportAdapter) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout implements the Transport interface.

type LoggerOption added in v1.6.0

type LoggerOption func(*loggerConfig)

LoggerOption configures a logger

func WithLogDiscard added in v1.6.0

func WithLogDiscard() LoggerOption

WithLogDiscard disables all logging output

func WithLogFile added in v1.6.0

func WithLogFile(filename string) LoggerOption

WithLogFile sets the output to a file (safe for stdio-based MCP communication)

func WithLogLevel added in v1.6.0

func WithLogLevel(level slog.Level) LoggerOption

WithLogLevel sets the log level

func WithLogOutput added in v1.6.0

func WithLogOutput(w io.Writer) LoggerOption

WithLogOutput sets the output writer

type LoggingCapability added in v1.6.0

type LoggingCapability struct {
}

LoggingCapability represents the server's logging capability. Currently defined as an empty object in all MCP specification versions.

type MCPServer added in v1.2.0

type MCPServer struct {
	Name   string
	Client Client
	// contains filtered or unexported fields
}

MCPServer represents a running MCP server process with a connected client

type MQTTTransport added in v1.2.1

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

MQTTTransport implements the Transport interface for MQTT.

func NewMQTTTransport added in v1.2.1

func NewMQTTTransport(brokerURL string, options ...MQTTTransportOption) *MQTTTransport

NewMQTTTransport creates a new MQTT transport.

func (*MQTTTransport) Connect added in v1.2.1

func (t *MQTTTransport) Connect() error

Connect implements the Transport.Connect method.

func (*MQTTTransport) ConnectWithContext added in v1.2.1

func (t *MQTTTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext implements the Transport.ConnectWithContext method.

func (*MQTTTransport) Disconnect added in v1.2.1

func (t *MQTTTransport) Disconnect() error

Disconnect implements the Transport.Disconnect method.

func (*MQTTTransport) RegisterNotificationHandler added in v1.2.1

func (t *MQTTTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler implements the Transport.RegisterNotificationHandler method.

func (*MQTTTransport) Send added in v1.2.1

func (t *MQTTTransport) Send(message []byte) ([]byte, error)

Send implements the Transport.Send method.

func (*MQTTTransport) SendWithContext added in v1.2.1

func (t *MQTTTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext implements the Transport.SendWithContext method. ONE way to send and receive responses

func (*MQTTTransport) SetConnectionTimeout added in v1.2.1

func (t *MQTTTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout implements the Transport.SetConnectionTimeout method.

func (*MQTTTransport) SetRequestTimeout added in v1.2.1

func (t *MQTTTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout implements the Transport.SetRequestTimeout method.

type MQTTTransportOption added in v1.2.1

type MQTTTransportOption func(*MQTTTransport)

MQTTTransportOption represents a configuration option for the MQTT transport

func WithMQTTClientID added in v1.2.1

func WithMQTTClientID(clientID string) MQTTTransportOption

WithMQTTClientID sets the client ID

func WithMQTTCredentials added in v1.2.1

func WithMQTTCredentials(username, password string) MQTTTransportOption

WithMQTTCredentials sets the username and password for MQTT broker authentication

func WithMQTTQoS added in v1.2.1

func WithMQTTQoS(qos byte) MQTTTransportOption

WithMQTTQoS sets the MQTT Quality of Service level

func WithMQTTTLS added in v1.2.1

func WithMQTTTLS(config *mqtt.TLSConfig) MQTTTransportOption

WithMQTTTLS sets TLS configuration for secure MQTT connections

func WithMQTTTopicPrefix added in v1.2.1

func WithMQTTTopicPrefix(prefix string) MQTTTransportOption

WithMQTTTopicPrefix sets the topic prefix for MQTT messages

type NATSTransport added in v1.2.1

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

NATSTransport implements the Transport interface for NATS.

func NewNATSTransport added in v1.2.1

func NewNATSTransport(serverURL string, options ...NATSTransportOption) *NATSTransport

NewNATSTransport creates a new NATS transport.

func (*NATSTransport) Connect added in v1.2.1

func (t *NATSTransport) Connect() error

Connect implements the Transport.Connect method.

func (*NATSTransport) ConnectWithContext added in v1.2.1

func (t *NATSTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext implements the Transport.ConnectWithContext method.

func (*NATSTransport) Disconnect added in v1.2.1

func (t *NATSTransport) Disconnect() error

Disconnect implements the Transport.Disconnect method.

func (*NATSTransport) RegisterNotificationHandler added in v1.2.1

func (t *NATSTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler implements the Transport.RegisterNotificationHandler method.

func (*NATSTransport) Send added in v1.2.1

func (t *NATSTransport) Send(message []byte) ([]byte, error)

Send implements the Transport.Send method.

func (*NATSTransport) SendWithContext added in v1.2.1

func (t *NATSTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext implements the Transport.SendWithContext method.

func (*NATSTransport) SetConnectionTimeout added in v1.2.1

func (t *NATSTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout implements the Transport.SetConnectionTimeout method.

func (*NATSTransport) SetRequestTimeout added in v1.2.1

func (t *NATSTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout implements the Transport.SetRequestTimeout method.

type NATSTransportOption added in v1.2.1

type NATSTransportOption func(*NATSTransport)

NATSTransportOption represents a configuration option for the NATS transport

func WithNATSClientID added in v1.2.1

func WithNATSClientID(clientID string) NATSTransportOption

WithNATSClientID sets the client ID for the NATS transport

func WithNATSCredentials added in v1.2.1

func WithNATSCredentials(username, password string) NATSTransportOption

WithNATSCredentials sets the username and password for the NATS transport

func WithNATSSubjectPrefix added in v1.2.1

func WithNATSSubjectPrefix(prefix string) NATSTransportOption

WithNATSSubjectPrefix sets the subject prefix for the NATS transport

func WithNATSTLS added in v1.2.1

func WithNATSTLS(config *natst.TLSConfig) NATSTransportOption

WithNATSTLS sets the TLS configuration for the NATS transport

func WithNATSToken added in v1.2.1

func WithNATSToken(token string) NATSTransportOption

WithNATSToken sets the token for the NATS transport

type Option added in v1.2.0

type Option func(*clientImpl)

Option is a client configuration option.

func WithConnectionTimeout added in v1.2.0

func WithConnectionTimeout(timeout time.Duration) Option

WithConnectionTimeout sets the client's connection timeout.

func WithEmbedded added in v1.6.4

func WithEmbedded(transport *embedded.Transport, options ...EmbeddedOption) Option

WithEmbedded configures the client to use embedded (in-process) transport for communication.

Embedded transport provides zero-overhead in-process communication, perfect for testing, library integration, and embedded use cases where network overhead should be minimized.

The transport parameter should be the client-side transport from a transport pair created using embedded.NewTransportPair().

Parameters: - transport: The client-side embedded transport from a transport pair - options: Optional configuration settings (timeout, buffer size, etc.)

Example:

// Create transport pair
clientTransport, serverTransport := embedded.NewTransportPair()

// Configure client with the client-side transport
client, err := client.NewClient("embedded://",
    client.WithEmbedded(clientTransport),
    // or with options:
    client.WithEmbedded(clientTransport,
        client.WithEmbeddedTimeout(5*time.Second)))

func WithExperimentalCapability added in v1.2.0

func WithExperimentalCapability(name string, config interface{}) Option

WithExperimentalCapability adds an experimental capability.

func WithGRPC added in v1.2.1

func WithGRPC(address string, options ...grpc.Option) Option

WithGRPC returns a client configuration option that uses gRPC transport. The gRPC transport provides bi-directional streaming and high-performance communication.

Parameters:

  • address: The server address to connect to (e.g., "localhost:50051")
  • options: Optional configuration options for the gRPC transport

Returns:

  • A client configuration option

func WithHTTP added in v1.2.2

func WithHTTP(url string, options ...HTTPOption) Option

WithHTTP configures the client to use HTTP transport for communication.

Parameters: - url: The endpoint URL (e.g., "http://localhost:8080/mcp") - options: Optional configuration settings

Example:

client.New(
    client.WithHTTP("http://localhost:8080/mcp"),
    // or with options:
    client.WithHTTP("http://localhost:8080/mcp",
        client.WithHTTPHeader("Authorization", "Bearer token"),
        client.WithHTTPTimeout(10 * time.Second))
)

func WithLogger added in v0.1.11

func WithLogger(logger *slog.Logger) Option

WithLogger sets the client's logger.

func WithMQTT added in v1.2.1

func WithMQTT(brokerURL string, options ...MQTTTransportOption) Option

WithMQTT configures the client to use MQTT for communication with optional configuration options.

Parameters: - brokerURL: The MQTT broker URL (e.g., "tcp://broker.example.com:1883") - options: Optional configuration settings (QoS, credentials, topics, etc.)

Example:

client, err := gomcp.NewClient("test-service",
    client.WithMQTT("tcp://broker.example.com:1883"),
    // or with options:
    client.WithMQTT("tcp://broker.example.com:1883",
        client.WithMQTTClientID("my-client"),
        client.WithMQTTQoS(1),
        client.WithMQTTCredentials("username", "password")),
)

func WithNATS added in v1.2.1

func WithNATS(serverURL string, options ...NATSTransportOption) Option

WithNATS configures the client to use NATS for communication with optional configuration options.

Parameters: - serverURL: The NATS server URL (e.g., "nats://localhost:4222") - options: Optional configuration settings (credentials, token, subjects, etc.)

Example:

client, err := gomcp.NewClient("test-service",
    client.WithNATS("nats://localhost:4222"),
    // or with options:
    client.WithNATS("nats://localhost:4222",
        client.WithNATSClientID("my-client"),
        client.WithNATSCredentials("username", "password")),
)

func WithOldestProtocolVersion added in v1.2.2

func WithOldestProtocolVersion() Option

WithOldestProtocolVersion sets the client to use the oldest supported protocol version. This is useful for maximum compatibility with servers that might not support newer versions.

func WithProtocolNegotiation added in v1.2.0

func WithProtocolNegotiation(enabled bool) Option

WithProtocolNegotiation enables or disables protocol version negotiation.

func WithProtocolVersion added in v1.2.0

func WithProtocolVersion(version string) Option

WithProtocolVersion sets a specific protocol version for the client to use. This bypasses the normal negotiation process and forces the client to use this version. This is useful for testing or when you know exactly which version the server expects.

func WithRequestTimeout added in v0.1.11

func WithRequestTimeout(timeout time.Duration) Option

WithRequestTimeout sets the client's request timeout.

func WithRoots added in v1.2.0

func WithRoots(roots []Root) Option

WithRoots sets the initial roots for the client.

func WithRootsCapability added in v1.2.0

func WithRootsCapability(enabled bool, listChanged bool) Option

WithRootsCapability enables or disables the roots capability.

func WithSSE added in v1.2.2

func WithSSE(url string) Option

WithSSE returns a client configuration option that uses SSE transport. The SSE transport provides server-sent events for real-time updates from server to client. By default, it uses the oldest protocol version for maximum compatibility unless the user has explicitly set a different protocol version.

Parameters:

Returns:

  • A client configuration option

func WithSamplingCapability added in v1.2.0

func WithSamplingCapability(enabled bool, config map[string]interface{}) Option

WithSamplingCapability enables or disables the sampling capability.

func WithServerConfig added in v1.2.0

func WithServerConfig(configPath string, serverName string, opts ...ServerConfigOption) Option

WithServerConfig loads server configurations from a file and connects to a specific named server. This is used to integrate with the server registry system to automatically manage server processes. If the server requires starting a new process, it will be launched and managed by the registry. When the client is closed, the associated server process will be terminated if it was launched by this option.

func WithServers added in v1.2.0

func WithServers(config ServerConfig, serverName string, opts ...ServerConfigOption) Option

WithServers provides direct server configurations to the client. This is similar to WithServerConfig but accepts an in-memory configuration instead of loading from a file.

func WithServersFromConfig added in v1.7.0

func WithServersFromConfig(config *ServerConfig, serverNames ...string) Option

WithServersFromConfig provides server configurations from a loaded config to the client. This allows connecting to multiple servers from a configuration file. The first serverName in the list will be used as the primary transport.

func WithStdio added in v1.2.2

func WithStdio(options ...StdioOption) Option

WithStdio configures the client to use Standard I/O for communication with optional configuration options.

This is particularly useful for CLI applications or when communicating with child processes.

Parameters: - options: Optional configuration settings (custom I/O, timeout, etc.)

Example:

client.New(
    client.WithStdio(),
    // or with options:
    client.WithStdio(
        client.WithStdioInput(customInput),
        client.WithStdioOutput(customOutput),
        client.WithStdioNewline(false))
)

func WithTransport added in v1.2.0

func WithTransport(transport Transport) Option

WithTransport sets the client's transport.

func WithUDP added in v1.2.1

func WithUDP(address string, options ...UDPOption) Option

WithUDP configures the client to use UDP for communication with optional configuration options.

UDP provides low-latency communication with minimal overhead, suitable for high-throughput scenarios where occasional packet loss is acceptable.

Parameters: - address: The UDP address in the format "host:port" - options: Optional configuration settings (buffering, timeouts, etc.)

Example:

client.New(
    client.WithUDP("example.com:8080"),
    // or with options:
    client.WithUDP("example.com:8080",
        client.WithReadTimeout(5*time.Second),
        client.WithReliability(true))
)

func WithUnixSocket added in v1.2.1

func WithUnixSocket(socketPath string, options ...UnixSocketOption) Option

WithUnixSocket configures the client to use Unix Domain Sockets for communication with optional configuration options.

Parameters: - socketPath: The path to the Unix socket file - options: Optional configuration settings (timeouts, reconnection, etc.)

Example:

client.New(
    client.WithUnixSocket("/tmp/mcp.sock"),
    // or with options:
    client.WithUnixSocket("/tmp/mcp.sock",
        unix.WithTimeout(time.Second*5),
        unix.WithReconnect(true))
)

func WithVersionDetector added in v1.2.0

func WithVersionDetector(detector *mcp.VersionDetector) Option

WithVersionDetector sets the client's version detector.

func WithWSPath added in v1.2.2

func WithWSPath(path string) Option

WithWSPath configures the WebSocket path for the WebSocket connection.

func WithWSPathPrefix added in v1.2.2

func WithWSPathPrefix(prefix string) Option

WithWSPathPrefix configures the path prefix for the WebSocket connection.

func WithWebsocket added in v1.2.2

func WithWebsocket(url string) Option

WithWebsocket returns a client configuration option that uses WebSocket transport. The WebSocket transport provides a persistent connection for communication with a server.

Parameters:

  • url: The WebSocket server URL to connect to (e.g., "ws://localhost:8080/ws")

Returns:

  • A client configuration option

type ProcessInfo added in v1.6.0

type ProcessInfo struct {
	PID        int
	ServerName string
	Command    string
	StartTime  time.Time
	Children   []int // Child process PIDs
}

ProcessInfo tracks spawned processes for comprehensive cleanup

type Prompt added in v1.6.0

type Prompt struct {
	Name        string           `json:"name"`
	Description string           `json:"description,omitempty"`
	Arguments   []PromptArgument `json:"arguments,omitempty"`
}

Prompt represents a server prompt template that can be used to generate messages.

type PromptArgument added in v1.6.0

type PromptArgument struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

PromptArgument represents a parameter for a prompt template.

type PromptContent added in v1.6.0

type PromptContent struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

PromptContent represents the content of a prompt message.

type PromptMessage added in v1.6.0

type PromptMessage struct {
	Role    string        `json:"role"`
	Content PromptContent `json:"content"`
}

PromptMessage represents a rendered message from a prompt template.

type PromptResponse added in v1.6.0

type PromptResponse struct {
	Description string          `json:"description"`
	Messages    []PromptMessage `json:"messages"`
}

PromptResponse represents the response from a prompt request. This provides concrete types instead of interface{} for better type safety.

type PromptsCapability added in v1.6.0

type PromptsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

PromptsCapability represents the server's prompt template capability.

type RequestOption added in v1.5.0

type RequestOption interface {
	// contains filtered or unexported methods
}

RequestOption represents an option that can be passed to client methods.

type RequestOptions added in v1.5.0

type RequestOptions struct {
	// Timeout specifies the timeout for this specific request
	// If not set, uses the client's default timeout
	Timeout *time.Duration

	// MaxTimeout specifies the maximum timeout regardless of progress notifications
	// If not set, uses 2x the regular timeout as the maximum
	MaxTimeout *time.Duration

	// AllowProgressReset indicates whether progress notifications should reset the timeout clock
	// Default is true as per MCP specification
	AllowProgressReset bool
}

RequestOptions contains options for configuring individual requests

func DefaultRequestOptions added in v1.5.0

func DefaultRequestOptions() *RequestOptions

DefaultRequestOptions returns default request options

func (*RequestOptions) WithMaxTimeout added in v1.5.0

func (opts *RequestOptions) WithMaxTimeout(maxTimeout time.Duration) *RequestOptions

WithMaxTimeout sets the maximum timeout for this request

func (*RequestOptions) WithProgressReset added in v1.5.0

func (opts *RequestOptions) WithProgressReset(allow bool) *RequestOptions

WithProgressReset configures whether progress notifications reset the timeout

func (*RequestOptions) WithTimeout added in v1.5.0

func (opts *RequestOptions) WithTimeout(timeout time.Duration) *RequestOptions

WithTimeout sets the timeout for this request

type Resource added in v1.6.0

type Resource struct {
	URI         string                 `json:"uri"`
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	MimeType    string                 `json:"mimeType,omitempty"`
	Size        *int64                 `json:"size,omitempty"`
	Annotations map[string]interface{} `json:"annotations,omitempty"`
}

Resource represents a server resource that can be accessed via the MCP protocol.

type ResourceContent added in v1.6.0

type ResourceContent struct {
	URI      string                 `json:"uri"`
	Text     string                 `json:"text,omitempty"`
	Content  []ContentItem          `json:"content"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

ResourceContent represents a single resource item (2025-03-26 format).

type ResourceParamsOption added in v1.6.0

type ResourceParamsOption struct {
	Params map[string]interface{}
}

ResourceParamsOption creates a request option that adds parameters to a resource request.

func WithResourceParams added in v1.6.0

func WithResourceParams(params map[string]interface{}) ResourceParamsOption

WithResourceParams creates a ResourceParamsOption for adding parameters to GetResource requests.

This allows passing additional parameters alongside the URI in resources/read requests as specified in the MCP protocol.

Example:

resource, err := client.GetResource("/api/users",
    client.WithResourceParams(map[string]interface{}{
        "include_posts": true,
        "limit": 50,
    }),
    client.WithRequestTimeoutOption(10*time.Second),
)

type ResourceResponse added in v1.6.0

type ResourceResponse struct {
	// Content field (2024-11-05 format) - flat array of content items
	Content []ContentItem `json:"content,omitempty"`

	// Contents field (2025-03-26 format) - array of resource objects with content
	Contents []ResourceContent `json:"contents,omitempty"`

	// Metadata that can be present in either format
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

ResourceResponse represents the actual response from a resource request. This matches the MCP protocol format exactly - no wrapper. The format depends on the negotiated protocol version: - 2024-11-05: {"content": [ContentItem...], "metadata": {...}} - 2025-03-26: {"contents": [ResourceContent...], "metadata": {...}}

type ResourcesCapability added in v1.6.0

type ResourcesCapability struct {
	Subscribe   bool `json:"subscribe,omitempty"`
	ListChanged bool `json:"listChanged,omitempty"`
}

ResourcesCapability represents the server's resource capability.

type Root added in v1.2.0

type Root struct {
	URI      string                 `json:"uri"`
	Name     string                 `json:"name,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

Root represents a filesystem root exposed to the MCP server.

type RootsCapability added in v1.2.0

type RootsCapability struct {
	ListChanged atomic.Bool `json:"-"` // Use atomic.Bool and exclude from JSON
}

RootsCapability represents the client's roots capability.

func (RootsCapability) MarshalJSON added in v1.7.1

func (r RootsCapability) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for RootsCapability

func (*RootsCapability) UnmarshalJSON added in v1.7.1

func (r *RootsCapability) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for RootsCapability

type SSETransport added in v1.2.2

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

SSETransport adapts the sse.Transport to implement the client.Transport interface

func NewSSETransport added in v0.1.11

func NewSSETransport(url string, logger *slog.Logger) *SSETransport

NewSSETransport creates a new SSE transport adapter.

func (*SSETransport) Connect added in v1.2.2

func (t *SSETransport) Connect() error

Connect establishes a connection to the server.

func (*SSETransport) ConnectWithContext added in v1.2.2

func (t *SSETransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext establishes a connection to the server with context for timeout/cancellation.

func (*SSETransport) Disconnect added in v1.2.2

func (t *SSETransport) Disconnect() error

Disconnect closes the connection to the server.

func (*SSETransport) RegisterNotificationHandler added in v1.2.2

func (t *SSETransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler registers a handler for server-initiated messages.

func (*SSETransport) Send added in v1.2.2

func (t *SSETransport) Send(message []byte) ([]byte, error)

Send sends a message to the server and waits for a response.

func (*SSETransport) SendWithContext added in v1.2.2

func (t *SSETransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext sends a message with context for timeout/cancellation.

func (*SSETransport) SetConnectionTimeout added in v1.2.2

func (t *SSETransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout sets the default timeout for connection operations.

func (*SSETransport) SetDebugEnabled added in v1.2.2

func (t *SSETransport) SetDebugEnabled(enabled bool)

SetDebugEnabled enables or disables debug logging

func (*SSETransport) SetRequestTimeout added in v1.2.2

func (t *SSETransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout sets the default timeout for request operations.

type SamplingCreateMessageParams added in v1.2.0

type SamplingCreateMessageParams struct {
	Messages         []SamplingMessage        `json:"messages"`
	ModelPreferences SamplingModelPreferences `json:"modelPreferences"`
	SystemPrompt     string                   `json:"systemPrompt,omitempty"`
	MaxTokens        int                      `json:"maxTokens,omitempty"`
}

SamplingCreateMessageParams represents the parameters for a sampling/createMessage request.

type SamplingHandler added in v1.2.0

type SamplingHandler func(params SamplingCreateMessageParams) (SamplingResponse, error)

SamplingHandler is a function that handles sampling/createMessage requests from the server.

type SamplingMessage added in v1.2.0

type SamplingMessage struct {
	Role    string                 `json:"role"`
	Content SamplingMessageContent `json:"content"`
}

SamplingMessage represents a message in a sampling conversation.

func CreateAudioMessage added in v1.5.0

func CreateAudioMessage(role, audioData, mimeType string) SamplingMessage

func CreateImageMessage added in v1.5.0

func CreateImageMessage(role, imageData, mimeType string) SamplingMessage

func CreateTextMessage added in v1.5.0

func CreateTextMessage(role, text string) SamplingMessage

Convenience functions for creating messages

type SamplingMessageContent added in v1.2.0

type SamplingMessageContent struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
}

SamplingMessageContent represents the content of a sampling message.

func (*SamplingMessageContent) IsValidForVersion added in v1.2.0

func (c *SamplingMessageContent) IsValidForVersion(version string) bool

IsValidForVersion checks if the content type is valid for the given protocol version

type SamplingModelHint added in v1.2.0

type SamplingModelHint struct {
	Name string `json:"name"`
}

SamplingModelHint represents a hint for model selection in sampling requests.

type SamplingModelPreferences added in v1.2.0

type SamplingModelPreferences struct {
	Hints                []SamplingModelHint `json:"hints,omitempty"`
	CostPriority         *float64            `json:"costPriority,omitempty"`
	SpeedPriority        *float64            `json:"speedPriority,omitempty"`
	IntelligencePriority *float64            `json:"intelligencePriority,omitempty"`
}

SamplingModelPreferences represents the model preferences for a sampling request.

type SamplingOptions added in v1.5.0

type SamplingOptions struct {
	// Core request parameters
	Messages         []SamplingMessage
	ModelPreferences SamplingModelPreferences
	SystemPrompt     string
	MaxTokens        int

	// Request configuration
	Context         context.Context
	Timeout         time.Duration
	ProtocolVersion string

	// Streaming options (only for protocol version 2025-03-26)
	Streaming      bool
	StreamHandler  func(*SamplingResponse) error // Called for each chunk when streaming
	ChunkSize      int                           // Maximum size of text chunks
	MaxChunks      int                           // Maximum number of chunks (0 for unlimited)
	StopOnComplete bool                          // Stop streaming when isComplete=true

	// Retry configuration
	MaxRetries      int
	RetryInterval   time.Duration
	RetryMultiplier float64
	MaxInterval     time.Duration
}

SamplingOptions configures how sampling requests are made.

func DefaultSamplingOptions added in v1.5.0

func DefaultSamplingOptions() *SamplingOptions

DefaultSamplingOptions returns default sampling options.

func NewSamplingOptions added in v1.5.0

func NewSamplingOptions(messages []SamplingMessage, prefs SamplingModelPreferences) *SamplingOptions

NewSamplingOptions creates new sampling options with the given messages and preferences.

func (*SamplingOptions) Validate added in v1.5.0

func (opts *SamplingOptions) Validate() error

Validate validates the sampling options.

func (*SamplingOptions) WithChunkSize added in v1.5.0

func (opts *SamplingOptions) WithChunkSize(size int) *SamplingOptions

WithChunkSize sets the chunk size for streaming (only for streaming mode).

func (*SamplingOptions) WithContext added in v1.5.0

func (opts *SamplingOptions) WithContext(ctx context.Context) *SamplingOptions

WithContext sets the context for the sampling request.

func (*SamplingOptions) WithMaxTokens added in v1.5.0

func (opts *SamplingOptions) WithMaxTokens(maxTokens int) *SamplingOptions

WithMaxTokens sets the maximum tokens for the sampling request.

func (*SamplingOptions) WithStreaming added in v1.5.0

func (opts *SamplingOptions) WithStreaming(handler func(*SamplingResponse) error) *SamplingOptions

WithStreaming enables streaming mode (only available in protocol version 2025-03-26).

func (*SamplingOptions) WithSystemPrompt added in v1.5.0

func (opts *SamplingOptions) WithSystemPrompt(prompt string) *SamplingOptions

WithSystemPrompt sets the system prompt for the sampling request.

func (*SamplingOptions) WithTimeout added in v1.5.0

func (opts *SamplingOptions) WithTimeout(timeout time.Duration) *SamplingOptions

WithTimeout sets the timeout for the sampling request.

type SamplingResponse added in v1.2.0

type SamplingResponse struct {
	Role       string                 `json:"role"`
	Content    SamplingMessageContent `json:"content"`
	Model      string                 `json:"model,omitempty"`
	StopReason string                 `json:"stopReason,omitempty"`

	// Streaming fields
	IsComplete bool `json:"isComplete,omitempty"` // Only for streaming responses
	ChunkIndex int  `json:"chunkIndex,omitempty"` // Only for streaming responses
}

SamplingResponse represents the response to a sampling request.

type ServerCapabilities added in v1.6.0

type ServerCapabilities struct {
	Logging      *LoggingCapability     `json:"logging,omitempty"`
	Prompts      *PromptsCapability     `json:"prompts,omitempty"`
	Resources    *ResourcesCapability   `json:"resources,omitempty"`
	Tools        *ToolsCapability       `json:"tools,omitempty"`
	Experimental map[string]interface{} `json:"experimental,omitempty"`
}

ServerCapabilities represents the capabilities declared by the MCP server during initialization.

type ServerConfig added in v1.0.9

type ServerConfig struct {
	MCPServers map[string]ServerDefinition `json:"mcpServers"`
}

ServerConfig represents a complete MCP server configuration file

func LoadServerConfig added in v1.7.0

func LoadServerConfig(path string) (*ServerConfig, error)

LoadServerConfig loads a server configuration from a file and returns the parsed config. This is a standalone function for loading configuration files without creating a registry.

type ServerConfigOption added in v1.6.0

type ServerConfigOption func(*serverConfigParams)

ServerConfigOption configures server registry behavior

func WithServerRegistryLogger added in v1.6.0

func WithServerRegistryLogger(logger *slog.Logger) ServerConfigOption

WithServerRegistryLogger sets a logger for the server registry. Use this when you want logging from the server management, but make sure the logger doesn't write to stdout/stderr if using stdio transport to avoid interfering with the MCP communication.

type ServerDefinition added in v1.2.0

type ServerDefinition struct {
	Command string            `json:"command"`
	Args    []string          `json:"args"`
	Env     map[string]string `json:"env,omitempty"`
	URL     string            `json:"url,omitempty"`
}

ServerDefinition defines how to launch and connect to an MCP server

type ServerInfo added in v1.6.0

type ServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

ServerInfo represents information about the MCP server.

type ServerRegistry added in v1.2.0

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

ServerRegistry manages a collection of MCP servers loaded from configuration

func NewServerRegistry added in v1.2.0

func NewServerRegistry(opts ...ServerRegistryOption) *ServerRegistry

NewServerRegistry creates a new empty server registry. By default, no logging is enabled to avoid interfering with stdio-based MCP communication.

func (*ServerRegistry) ApplyConfig added in v1.2.0

func (r *ServerRegistry) ApplyConfig(config ServerConfig) error

ApplyConfig applies a server configuration by starting servers and connecting clients

func (*ServerRegistry) Close added in v1.6.0

func (r *ServerRegistry) Close() error

Close shuts down the ServerRegistry and ensures all processes are terminated. This should be called when the application is shutting down to prevent orphaned processes.

func (*ServerRegistry) GetClient added in v1.2.0

func (r *ServerRegistry) GetClient(name string) (Client, error)

GetClient returns the client for a named server

func (*ServerRegistry) GetServerNames added in v1.2.0

func (r *ServerRegistry) GetServerNames() ([]string, error)

GetServerNames returns a list of all server names in the registry

func (*ServerRegistry) LoadConfig added in v1.2.0

func (r *ServerRegistry) LoadConfig(path string) error

LoadConfig loads a server configuration from a file

func (*ServerRegistry) StartServer added in v1.2.0

func (r *ServerRegistry) StartServer(name string, def ServerDefinition) error

StartServer starts a server from its definition and connects a client to it

func (*ServerRegistry) StopAll added in v1.2.0

func (r *ServerRegistry) StopAll() error

StopAll stops all servers

func (*ServerRegistry) StopServer added in v1.2.0

func (r *ServerRegistry) StopServer(name string) error

StopServer stops a server by name

type ServerRegistryOption added in v1.6.0

type ServerRegistryOption func(*ServerRegistry)

ServerRegistryOption configures a ServerRegistry

func WithProcessTracking added in v1.6.0

func WithProcessTracking() ServerRegistryOption

WithProcessTracking enables comprehensive process tracking and cleanup. This is recommended for production environments to prevent process leaks. Process tracking adds overhead and should be disabled for tests with mock commands.

func WithRegistryLogger added in v1.6.0

func WithRegistryLogger(logger *slog.Logger) ServerRegistryOption

WithRegistryLogger sets a logger for the server registry. When using stdio-based MCP servers, ensure the logger does not write to stdout/stderr to avoid interfering with the JSON-RPC communication.

type ServerStatus added in v1.7.0

type ServerStatus struct {
	Running bool  `json:"running"`
	Error   error `json:"error,omitempty"`
	PID     int   `json:"pid,omitempty"`
}

ServerStatus represents the status of a managed MCP server.

type StdioOption added in v1.2.2

type StdioOption func(*stdioConfig)

StdioOption is a function that configures a Stdio transport. These options allow customizing the behavior of the Stdio client connection.

func WithStdioInput added in v1.2.2

func WithStdioInput(in io.Reader) StdioOption

WithStdioInput sets a custom input reader for the Stdio transport.

func WithStdioNewline added in v1.2.2

func WithStdioNewline(appendNewline bool) StdioOption

WithStdioNewline configures whether to append a newline character to messages.

func WithStdioOutput added in v1.2.2

func WithStdioOutput(out io.Writer) StdioOption

WithStdioOutput sets a custom output writer for the Stdio transport.

func WithStdioTimeout added in v1.2.2

func WithStdioTimeout(timeout time.Duration) StdioOption

WithStdioTimeout sets the timeout for Stdio operations.

type StdioTransport added in v1.2.2

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

StdioTransport adapts the stdio transport to the client Transport interface.

func NewStdioTransport added in v0.1.11

func NewStdioTransport() *StdioTransport

NewStdioTransport creates a new stdio transport adapter.

func NewStdioTransportWithIO added in v1.2.2

func NewStdioTransportWithIO(in io.Reader, out io.Writer) *StdioTransport

NewStdioTransportWithIO creates a new stdio transport adapter with custom IO.

func (*StdioTransport) Connect added in v1.2.2

func (t *StdioTransport) Connect() error

Connect establishes a connection to the server.

func (*StdioTransport) ConnectWithContext added in v1.2.2

func (t *StdioTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext establishes a connection to the server with context for timeout/cancellation.

func (*StdioTransport) Disconnect added in v1.2.2

func (t *StdioTransport) Disconnect() error

Disconnect closes the connection to the server.

func (*StdioTransport) RegisterNotificationHandler added in v1.2.2

func (t *StdioTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler registers a handler for server-initiated messages.

func (*StdioTransport) Send added in v1.2.2

func (t *StdioTransport) Send(message []byte) ([]byte, error)

Send sends a message to the server and waits for a response.

func (*StdioTransport) SendWithContext added in v1.2.2

func (t *StdioTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext sends a message with context for timeout/cancellation.

func (*StdioTransport) SetConnectionTimeout added in v1.2.2

func (t *StdioTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout sets the default timeout for connection operations.

func (*StdioTransport) SetRequestTimeout added in v1.2.2

func (t *StdioTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout sets the default timeout for request operations.

type TimeoutOption added in v1.5.0

type TimeoutOption struct {
	Duration time.Duration
}

TimeoutOption creates a request option that sets a timeout for the request.

func WithRequestTimeoutOption added in v1.5.0

func WithRequestTimeoutOption(d time.Duration) TimeoutOption

WithRequestTimeoutOption creates a TimeoutOption from a duration.

type Tool added in v1.3.1

type Tool = mcp.Tool

Tool is an alias to the shared mcp.Tool type for backward compatibility.

type ToolsCapability added in v1.6.0

type ToolsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

ToolsCapability represents the server's tool capability.

type Transport added in v1.2.0

type Transport interface {
	// Connect establishes a connection to the server.
	Connect() error

	// ConnectWithContext establishes a connection to the server with context for timeout/cancellation.
	ConnectWithContext(ctx context.Context) error

	// Disconnect closes the connection to the server.
	Disconnect() error

	// Send sends a message to the server and waits for a response.
	Send(message []byte) ([]byte, error)

	// SendWithContext sends a message with context for timeout/cancellation.
	SendWithContext(ctx context.Context, message []byte) ([]byte, error)

	// SetRequestTimeout sets the default timeout for request operations.
	SetRequestTimeout(timeout time.Duration)

	// SetConnectionTimeout sets the default timeout for connection operations.
	SetConnectionTimeout(timeout time.Duration)

	// RegisterNotificationHandler registers a handler for server-initiated messages.
	RegisterNotificationHandler(handler func(method string, params []byte))
}

Transport represents a transport layer for client communication. It handles the communication between the client and the server.

type UDPOption added in v1.2.1

type UDPOption func(*udpConfig)

UDPOption is a function that configures a UDP transport. These options allow customizing the behavior of the UDP client connection.

func WithFragmentTTL added in v1.2.1

func WithFragmentTTL(ttl time.Duration) UDPOption

WithFragmentTTL sets the time-to-live for message fragments.

func WithMaxPacketSize added in v1.2.1

func WithMaxPacketSize(size int) UDPOption

WithMaxPacketSize sets the maximum UDP packet size.

func WithReadBufferSize added in v1.2.1

func WithReadBufferSize(size int) UDPOption

WithReadBufferSize sets the read buffer size.

func WithReadTimeout added in v0.1.11

func WithReadTimeout(timeout time.Duration) UDPOption

WithReadTimeout sets the read timeout.

func WithReliability added in v1.2.1

func WithReliability(enabled bool) UDPOption

WithReliability enables or disables reliability mechanisms.

func WithUDPMaxRetries added in v1.2.1

func WithUDPMaxRetries(retries int) UDPOption

WithMaxRetries sets the maximum number of reconnection attempts.

func WithUDPReconnect added in v1.2.1

func WithUDPReconnect(enabled bool) UDPOption

WithReconnect enables automatic reconnection for UDP transport.

func WithUDPReconnectDelay added in v1.2.1

func WithUDPReconnectDelay(delay time.Duration) UDPOption

WithReconnectDelay sets the delay between reconnection attempts.

func WithWriteBufferSize added in v1.2.1

func WithWriteBufferSize(size int) UDPOption

WithWriteBufferSize sets the write buffer size.

func WithWriteTimeout added in v0.1.11

func WithWriteTimeout(timeout time.Duration) UDPOption

WithWriteTimeout sets the write timeout.

type UnixSocketOption added in v1.2.1

type UnixSocketOption func(*unixConfig)

UnixSocketOption is a function that configures a Unix Domain Socket transport. These options allow customizing the behavior of the Unix Domain Socket client connection.

func WithBufferSize added in v1.2.1

func WithBufferSize(size int) UnixSocketOption

WithBufferSize sets the buffer size for socket I/O operations

func WithMaxRetries added in v1.2.1

func WithMaxRetries(maxRetries int) UnixSocketOption

WithMaxRetries sets the maximum number of reconnection attempts

func WithPermissions added in v1.2.1

func WithPermissions(permissions uint32) UnixSocketOption

WithPermissions sets the permissions for the socket file (server-side only)

func WithReconnect added in v1.2.1

func WithReconnect(enabled bool) UnixSocketOption

WithReconnect enables automatic reconnection for Unix Domain Socket transport

func WithReconnectDelay added in v1.2.1

func WithReconnectDelay(delay time.Duration) UnixSocketOption

WithReconnectDelay sets the delay between reconnection attempts

func WithTimeout added in v0.1.11

func WithTimeout(timeout time.Duration) UnixSocketOption

WithTimeout sets the timeout for Unix Domain Socket operations

type WSTransport added in v1.2.2

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

WSTransport wraps a ws.Transport to implement the client.Transport interface

func (*WSTransport) Connect added in v1.2.2

func (t *WSTransport) Connect() error

Connect establishes a connection to the server

func (*WSTransport) ConnectWithContext added in v1.2.2

func (t *WSTransport) ConnectWithContext(ctx context.Context) error

ConnectWithContext establishes a connection to the server with context

func (*WSTransport) Disconnect added in v1.2.2

func (t *WSTransport) Disconnect() error

Disconnect closes the connection to the server

func (*WSTransport) RegisterNotificationHandler added in v1.2.2

func (t *WSTransport) RegisterNotificationHandler(handler func(method string, params []byte))

RegisterNotificationHandler registers a handler for server-initiated messages

func (*WSTransport) Send added in v1.2.2

func (t *WSTransport) Send(message []byte) ([]byte, error)

Send sends a message to the server and waits for a response

func (*WSTransport) SendWithContext added in v1.2.2

func (t *WSTransport) SendWithContext(ctx context.Context, message []byte) ([]byte, error)

SendWithContext sends a message with context for timeout/cancellation

func (*WSTransport) SetConnectionTimeout added in v1.2.2

func (t *WSTransport) SetConnectionTimeout(timeout time.Duration)

SetConnectionTimeout sets the default timeout for connection operations

func (*WSTransport) SetRequestTimeout added in v1.2.2

func (t *WSTransport) SetRequestTimeout(timeout time.Duration)

SetRequestTimeout sets the default timeout for request operations

Directories

Path Synopsis
Package test provides test utilities for the client package.
Package test provides test utilities for the client package.
draft
Package draft provides test utilities specific to the draft protocol version.
Package draft provides test utilities specific to the draft protocol version.

Jump to

Keyboard shortcuts

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