mcp

package
v2.12.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package mcp is PromptKit's Model Context Protocol client.

It is built on the official Go SDK (github.com/modelcontextprotocol/go-sdk), which speaks both generations of the protocol: the stateless revision (2026-07-28), where every request carries its version and the client's capabilities, and the handshake revisions up to 2025-11-25, detecting which a server speaks. Transports are stdio, Streamable HTTP and the deprecated HTTP+SSE. This package adapts the SDK to PromptKit's types and adds what the SDK leaves to its callers: retries, reconnection, timeouts that pause while a user answers, and the delegation of authorization and user interaction (elicitation) to the host through Authorizer and ElicitationHandler.

The types results arrive in are checked against the claimed revisions' published schemas by spec_parity_test.go, and behavior by the official conformance suite (make mcp-conformance).

Index

Constants

View Source
const (
	ElicitModeForm = "form"
	ElicitModeURL  = "url"
)

Elicitation modes (MCP client/elicitation).

View Source
const (
	ElicitActionAccept  = "accept"
	ElicitActionDecline = "decline"
	ElicitActionCancel  = "cancel"
)

Elicitation actions a user's answer can carry.

View Source
const (
	ContentTypeText         = "text"
	ContentTypeImage        = "image"
	ContentTypeAudio        = "audio"
	ContentTypeResourceLink = "resource_link"
	ContentTypeResource     = "resource"
)

Content types a ContentBlock can have.

View Source
const DefaultMaxProcesses = 0

DefaultMaxProcesses is the default maximum number of concurrent MCP processes. 0 means unlimited.

View Source
const LegacyProtocolVersion = "2025-11-25"

LegacyProtocolVersion is the newest handshake-era revision the client speaks, with servers that predate ProtocolVersion's stateless protocol. The client also accepts the earlier handshake revisions a server may choose (2025-06-18, 2025-03-26, 2024-11-05).

View Source
const ProtocolVersion = "2026-07-28"

ProtocolVersion is the newest MCP protocol revision the client speaks: the stateless revision it uses with servers that support it.

ProtocolVersion and LegacyProtocolVersion are the claims the conformance checks grade against: the mirrored schemas in testdata/spec, the parity test, the generated docs and the official suite all follow them.

Variables

View Source
var (
	// ErrClientNotInitialized is returned when attempting operations on uninitialized client
	ErrClientNotInitialized = errors.New("mcp: client not initialized")
	// ErrClientClosed is returned when attempting operations on closed client
	ErrClientClosed = errors.New("mcp: client closed")
	// ErrServerUnresponsive is returned when server doesn't respond
	ErrServerUnresponsive = errors.New("mcp: server unresponsive")
	// ErrProcessDied is returned when server process dies unexpectedly
	ErrProcessDied = errors.New("mcp: server process died")
)
View Source
var (
	// ErrMaxProcessesReached is returned when the concurrent process limit has been reached.
	ErrMaxProcessesReached = errors.New("mcp: maximum concurrent processes reached")
)

Functions

This section is empty.

Types

type Annotations added in v2.10.0

type Annotations struct {
	Audience     []string `json:"audience,omitempty"`
	Priority     *float64 `json:"priority,omitempty"`
	LastModified string   `json:"lastModified,omitempty"`
}

Annotations tell a client how to use a content block: who it is for and how important it is.

type AuthChallenge added in v2.10.0

type AuthChallenge struct {
	// Server is the server's name in the client configuration.
	Server string
	// ResourceURL is the URL of the request the server refused: the MCP
	// endpoint, which is the protected resource.
	ResourceURL string
	// Status is 401 (missing or invalid credentials) or 403 (insufficient
	// scope).
	Status int
	// Challenges are the parsed WWW-Authenticate challenges.
	Challenges []WWWAuthenticate
	// ResourceMetadata, Scope, Error and ErrorDescription are the parameters
	// of the Bearer challenge, if there is one. ResourceMetadata is the
	// protected resource metadata URL (RFC 9728); Scope is the scope the
	// server needs.
	ResourceMetadata string
	Scope            string
	Error            string
	ErrorDescription string
	// Header is the response's full header.
	Header http.Header
	// Attempt counts the challenges for this request, starting at 1.
	Attempt int
}

AuthChallenge describes a server's refusal of a request for lack of authorization.

type AuthError added in v2.10.0

type AuthError struct {
	Server string
	Status int
	Err    error
}

AuthError is returned when a request stays unauthorized: the Authorizer failed, or the server kept refusing after maxAuthChallenges challenges.

func (*AuthError) Error added in v2.10.0

func (e *AuthError) Error() string

func (*AuthError) Unwrap added in v2.10.0

func (e *AuthError) Unwrap() error

type Authorizer added in v2.10.0

type Authorizer interface {
	// Authorize adds credentials to an outgoing HTTP request: typically an
	// Authorization header, and a DPoP proof where one is used. It is
	// called for every request, including retries after a challenge.
	Authorize(ctx context.Context, req *http.Request) error

	// Challenge is called when the server rejects a request with 401, or
	// with 403 and error="insufficient_scope" (scope step-up). Return nil
	// once new credentials are ready: the request is built and sent again,
	// through Authorize. Return an error to fail the request.
	Challenge(ctx context.Context, challenge *AuthChallenge) error
}

Authorizer supplies credentials for an HTTP MCP server and handles its authorization challenges (MCP basic/authorization).

PromptKit runs no OAuth flow and stores no secrets. Discovering the authorization server (RFC 9728 protected resource metadata, RFC 8414), registering the client, obtaining the user's consent, validating the issuer, and storing and refreshing tokens belong to the host — the hosting runtime that owns secret storage and the user. The client calls the Authorizer at the two points the protocol defines, and bounds the retries.

type Client

type Client interface {
	// Initialize establishes the MCP connection and negotiates capabilities
	Initialize(ctx context.Context) (*InitializeResponse, error)

	// ListTools retrieves all available tools from the server
	ListTools(ctx context.Context) ([]Tool, error)

	// CallTool executes a tool with the given arguments
	CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)

	// Close terminates the connection to the MCP server
	Close() error

	// IsAlive checks if the connection is still active
	IsAlive() bool
}

Client interface defines the MCP client operations

type ClientCapabilities

type ClientCapabilities struct {
	Elicitation *ElicitationCapability `json:"elicitation,omitempty"`
	Sampling    *SamplingCapability    `json:"sampling,omitempty"`
	// Deprecated: logging is a server capability; MCP defines no client
	// "logging" capability. The client never sets this.
	Logging *LoggingCapability `json:"logging,omitempty"`
	// Extensions advertises optional protocol extensions, keyed by
	// identifier (2026-07-28). The client advertises none.
	Extensions map[string]json.RawMessage `json:"extensions,omitempty"`
}

ClientCapabilities describes what the client supports

type ClientOptions

type ClientOptions struct {
	// RequestTimeout bounds each request (tools/list, tools/call). It does
	// not run out while the client is answering the server's own request
	// for user input: that time is the user's, not the server's. A
	// tools/call's timeout restarts each time the server reports progress on
	// it; the caller's context still bounds the call.
	RequestTimeout time.Duration
	// InitTimeout bounds connecting: starting a stdio server or reaching an
	// HTTP one, and agreeing the protocol.
	InitTimeout time.Duration
	// MaxRetries is the number of times connecting is retried after a
	// failure that is not the server's answer. tools/call is never retried:
	// a tool may have side effects.
	MaxRetries int
	// RetryDelay is the initial delay between retries (exponential backoff).
	RetryDelay time.Duration
	// EnableGracefulDegradation makes a failed tools/list yield no tools
	// rather than an error.
	EnableGracefulDegradation bool
	// MaxReconnectAttempts is how many times the client reconnects when its
	// connection is lost (a stdio server exits, an SSE stream ends) before
	// reporting the server unresponsive. 0 disables reconnection.
	MaxReconnectAttempts int
	// ElicitationHandler, when set, answers servers' requests for user input
	// and makes the client advertise the elicitation capability (form mode).
	// Without it the client does not advertise elicitation, and refuses
	// elicitation requests.
	ElicitationHandler ElicitationHandler
	// DisableModernProtocol skips stateless (2026-07-28) detection and always
	// uses the initialize handshake. For servers that misbehave when probed.
	DisableModernProtocol bool
	// EraProbeTimeout bounds how long the client waits for a stdio server to
	// answer the server/discover probe before restarting it with the
	// initialize handshake: a handshake-era server may never answer a
	// request it does not know. Defaults to 3s. A server slower than that to
	// start is treated as handshake-era; raise it for modern-only servers
	// with slow starts. HTTP servers always answer, so it does not apply.
	EraProbeTimeout time.Duration
	// Authorizer, when set, supplies credentials for an HTTP server and
	// handles its authorization challenges. The host implements it; see
	// Authorizer. Static credentials can go in ServerConfig.Headers instead.
	Authorizer Authorizer
}

ClientOptions configures MCP client behavior.

func DefaultClientOptions

func DefaultClientOptions() ClientOptions

DefaultClientOptions returns sensible defaults.

type Content

type Content struct {
	Type     string `json:"type"` // one of the ContentType constants
	Text     string `json:"text,omitempty"`
	Data     string `json:"data,omitempty"`     // Base64 encoded data (image, audio)
	MimeType string `json:"mimeType,omitempty"` // MIME type for data
	URI      string `json:"uri,omitempty"`      // URI for resource_link
	// Name, Title, Description and Size describe a resource_link.
	Name        string `json:"name,omitempty"`
	Title       string `json:"title,omitempty"`
	Description string `json:"description,omitempty"`
	Size        *int64 `json:"size,omitempty"`
	Icons       []Icon `json:"icons,omitempty"`
	// Resource is an embedded resource's contents.
	Resource    *ResourceContents          `json:"resource,omitempty"`
	Annotations *Annotations               `json:"annotations,omitempty"`
	Meta        map[string]json.RawMessage `json:"_meta,omitempty"`
}

Content is one content block of a tool result. It is a flattened union of the spec's text, image, audio, resource_link and embedded resource blocks; Type says which fields apply.

type DiscoverResult added in v2.10.0

type DiscoverResult struct {
	SupportedVersions []string                   `json:"supportedVersions"`
	Capabilities      ServerCapabilities         `json:"capabilities"`
	Instructions      string                     `json:"instructions,omitempty"`
	ResultType        string                     `json:"resultType"`
	TTLMs             *int64                     `json:"ttlMs"`
	CacheScope        string                     `json:"cacheScope"`
	Meta              map[string]json.RawMessage `json:"_meta,omitempty"`
}

DiscoverResult is a server's answer to server/discover: its supported versions, capabilities and identity (2026-07-28 server/discover).

type ElicitRequest added in v2.10.0

type ElicitRequest struct {
	// Mode is ElicitModeForm (the default when absent) or ElicitModeURL.
	Mode            string          `json:"mode,omitempty"`
	Message         string          `json:"message"`
	RequestedSchema json.RawMessage `json:"requestedSchema,omitempty"`
	URL             string          `json:"url,omitempty"`
}

ElicitRequest is a server's request for information from the user (MCP client/elicitation). In form mode the answer is structured input matching RequestedSchema.

type ElicitResult added in v2.10.0

type ElicitResult struct {
	// Action is ElicitActionAccept, ElicitActionDecline or ElicitActionCancel.
	Action string `json:"action"`
	// Content is the submitted input, for an accepted form request.
	Content json.RawMessage `json:"content,omitempty"`
}

ElicitResult is the user's answer to an ElicitRequest.

type ElicitationCapability

type ElicitationCapability struct {
	Form *struct{} `json:"form,omitempty"`
	URL  *struct{} `json:"url,omitempty"`
}

ElicitationCapability indicates the client supports elicitation. An empty object means form mode only; Form and URL name the modes explicitly (2025-11-25).

type ElicitationHandler added in v2.10.0

type ElicitationHandler func(ctx context.Context, server string, req ElicitRequest) (ElicitResult, error)

ElicitationHandler asks the user for what a server requested and returns their answer. server is the name of the MCP server asking.

PromptKit does not talk to users; the host does. Setting a handler on ClientOptions is what makes the client advertise the elicitation capability, so a client without one is never asked.

type Icon added in v2.10.0

type Icon struct {
	Src      string   `json:"src"`
	MimeType string   `json:"mimeType,omitempty"`
	Sizes    []string `json:"sizes,omitempty"`
	// Theme is "light" or "dark", the background the icon is designed for.
	Theme string `json:"theme,omitempty"`
}

Icon is a display icon for an implementation, tool or resource (2025-11-25).

type Implementation

type Implementation struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	// Title is a display name.
	Title string `json:"title,omitempty"`
	// Description is a human-readable summary (2025-11-25).
	Description string `json:"description,omitempty"`
	// WebsiteURL links to the implementation's site (2025-11-25).
	WebsiteURL string `json:"websiteUrl,omitempty"`
	// Icons are display icons (2025-11-25).
	Icons []Icon `json:"icons,omitempty"`
}

Implementation describes client or server implementation details

type InitializeRequest

type InitializeRequest struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ClientCapabilities `json:"capabilities"`
	ClientInfo      Implementation     `json:"clientInfo"`
}

InitializeRequest represents the initialization request params

type InitializeResponse

type InitializeResponse struct {
	ProtocolVersion string             `json:"protocolVersion"`
	Capabilities    ServerCapabilities `json:"capabilities"`
	ServerInfo      Implementation     `json:"serverInfo"`
	// Instructions is the server's guidance on how to use it.
	Instructions string `json:"instructions,omitempty"`
}

InitializeResponse represents the initialization response. For a modern (2026-07-28) server, which has no handshake, the client builds it from the server/discover result.

type InputRequest added in v2.10.0

type InputRequest struct {
	Method string          `json:"method"`
	Params json.RawMessage `json:"params,omitempty"`
}

InputRequest is one request for input inside an InputRequiredResult.

type InputRequiredResult added in v2.10.0

type InputRequiredResult struct {
	ResultType    string                     `json:"resultType"`
	InputRequests map[string]InputRequest    `json:"inputRequests,omitempty"`
	RequestState  json.RawMessage            `json:"requestState,omitempty"`
	Meta          map[string]json.RawMessage `json:"_meta,omitempty"`
}

InputRequiredResult is a server's interim answer asking for input before it completes a request (2026-07-28 multi round-trip requests).

type JSONRPCError

type JSONRPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

JSONRPCError represents a JSON-RPC 2.0 error

type JSONRPCMessage

type JSONRPCMessage struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      interface{}     `json:"id,omitempty"`     // Request ID (number or string)
	Method  string          `json:"method,omitempty"` // Method name for requests/notifications
	Params  json.RawMessage `json:"params,omitempty"` // Parameters for method
	Result  json.RawMessage `json:"result,omitempty"` // Result for responses
	Error   *JSONRPCError   `json:"error,omitempty"`  // Error for error responses
}

JSONRPCMessage represents a JSON-RPC 2.0 message

type LoggingCapability deprecated

type LoggingCapability struct{}

LoggingCapability is not an MCP client capability: logging is declared by servers (ServerCapabilities.logging), not clients.

Deprecated: the client never sends it. Setting ClientCapabilities.Logging sends a field the MCP spec does not define for clients.

type PromptsCapability

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

PromptsCapability indicates the server supports prompts

type RPCError added in v2.10.0

type RPCError struct {
	Code    int
	Message string
	Data    json.RawMessage
}

RPCError is a JSON-RPC error returned by an MCP server. Callers can errors.As a request error into it to read the code and data.

func (*RPCError) Error added in v2.10.0

func (e *RPCError) Error() string

type Registry

type Registry interface {
	// RegisterServer adds a new MCP server configuration
	RegisterServer(config ServerConfig) error

	// UnregisterServer closes the client (if any) and removes the server
	// from the registry. Unknown names are no-ops.
	UnregisterServer(name string) error

	// GetClient returns an active client for the given server name
	GetClient(ctx context.Context, serverName string) (Client, error)

	// GetClientForTool returns the client that provides the specified tool
	GetClientForTool(ctx context.Context, toolName string) (Client, error)

	// ListServers returns all registered server names
	ListServers() []string

	// ListAllTools returns all tools from all connected servers
	ListAllTools(ctx context.Context) (map[string][]Tool, error)

	// GetServerConfig returns the configuration for a registered server.
	GetServerConfig(serverName string) (ServerConfig, bool)

	// Close shuts down all MCP servers and connections
	Close() error
}

Registry interface defines the MCP server registry operations

type RegistryImpl

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

RegistryImpl implements the Registry interface

func NewRegistry

func NewRegistry() *RegistryImpl

NewRegistry creates a new MCP server registry with default options (unlimited processes).

func NewRegistryWithOptions

func NewRegistryWithOptions(opts RegistryOptions) *RegistryImpl

NewRegistryWithOptions creates a new MCP server registry with custom options.

func NewRegistryWithServers

func NewRegistryWithServers(serverConfigs []ServerConfigData) (*RegistryImpl, error)

NewRegistryWithServers creates a registry and registers multiple servers. Returns error if any server registration fails.

func (*RegistryImpl) ActiveProcessCount

func (r *RegistryImpl) ActiveProcessCount() int

ActiveProcessCount returns the number of active MCP processes. Returns -1 if no process limit is configured.

func (*RegistryImpl) Close

func (r *RegistryImpl) Close() error

Close shuts down all MCP servers and connections

func (*RegistryImpl) Fork

func (r *RegistryImpl) Fork() *RegistryImpl

Fork returns a child registry that shares this registry's static servers and clients via lookup fall-through, but has its own per-instance dynamic state. Children can register their own servers (including names that exist in the parent) without colliding; this is the mechanism that lets concurrent runs each open their own session-scoped MCP source while sharing static client connections.

Registration on the child is local-only: the parent never sees the child's entries. Lookups (GetServerConfig, GetClient, GetClientForTool, ListServers) try local state first, then fall through to the parent. UnregisterServer is local-only.

Cycle safety is the caller's responsibility; in practice forks only chain one level deep (engine → run).

func (*RegistryImpl) GetClient

func (r *RegistryImpl) GetClient(ctx context.Context, serverName string) (Client, error)

GetClient returns an active client for the given server name. For child registries (Fork), if the name resolves only to the parent, the parent's client is returned — preserving connection sharing for static servers across all per-run forks.

func (*RegistryImpl) GetClientForTool

func (r *RegistryImpl) GetClientForTool(ctx context.Context, toolName string) (Client, error)

GetClientForTool returns the client that provides the specified tool. Child registries (Fork) check their own tool index first; if the tool is not owned by a locally-registered server, the lookup falls through to the parent's tool index.

func (*RegistryImpl) GetServerConfig

func (r *RegistryImpl) GetServerConfig(serverName string) (ServerConfig, bool)

GetServerConfig returns the configuration for a registered server. Child registries fall through to the parent when the name is not registered locally.

func (*RegistryImpl) GetToolSchema

func (r *RegistryImpl) GetToolSchema(ctx context.Context, toolName string) (*Tool, error)

GetToolSchema returns the schema for a specific tool

func (*RegistryImpl) ListAllTools

func (r *RegistryImpl) ListAllTools(ctx context.Context) (map[string][]Tool, error)

ListAllTools returns all tools from all connected servers

func (*RegistryImpl) ListServers

func (r *RegistryImpl) ListServers() []string

ListServers returns all registered server names. For child registries (produced by Fork), this is the union of local and parent entries — child names override parent names with the same key.

func (*RegistryImpl) RegisterServer

func (r *RegistryImpl) RegisterServer(config ServerConfig) error

RegisterServer adds a new MCP server configuration. Child registries (produced by Fork) accept names that exist in the parent — registration is local-only.

func (*RegistryImpl) UnregisterServer

func (r *RegistryImpl) UnregisterServer(name string) error

UnregisterServer closes the client if one exists, removes the server from the registry, and prunes its tool-index entries. Unknown names are no-ops; already-closed clients are not an error.

type RegistryOptions

type RegistryOptions struct {
	// MaxProcesses limits the number of concurrent MCP server processes.
	// 0 means unlimited (no limit enforced).
	MaxProcesses int
	// ConfigureClient, when set, adjusts the options of each server's client
	// before it is created: the place a host supplies an Authorizer or an
	// ElicitationHandler per server. The options arrive with the defaults
	// and the server's TimeoutMs applied.
	ConfigureClient func(config ServerConfig, options *ClientOptions)
	// OnToolsChanged, when set, is called after a server reports that its
	// tool list changed (notifications/tools/list_changed) and the registry
	// has re-read it. tools is the server's new list. It is called on its own
	// goroutine. A list that cannot be re-read leaves the previous tools in
	// place and is not reported.
	OnToolsChanged func(serverName string, tools []Tool)
}

RegistryOptions configures the MCP registry behavior.

type ResourceContents added in v2.10.0

type ResourceContents struct {
	URI      string                     `json:"uri"`
	MimeType string                     `json:"mimeType,omitempty"`
	Text     string                     `json:"text,omitempty"`
	Blob     string                     `json:"blob,omitempty"`
	Meta     map[string]json.RawMessage `json:"_meta,omitempty"`
}

ResourceContents is the content of an embedded resource: Text for a text resource, Blob (base64) for a binary one.

type ResourcesCapability

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

ResourcesCapability indicates the server supports resources

type SSEClient

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

SSEClient talks to an MCP server over the deprecated HTTP+SSE transport (MCP 2024-11-05). ServerConfig.URL is the SSE endpoint.

func NewSSEClient

func NewSSEClient(config ServerConfig) *SSEClient

NewSSEClient creates an HTTP+SSE client with default options.

func NewSSEClientWithOptions

func NewSSEClientWithOptions(config ServerConfig, options ClientOptions) *SSEClient

NewSSEClientWithOptions creates an HTTP+SSE client with custom options.

func (SSEClient) CallTool

func (c SSEClient) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)

CallTool calls a tool. It is never retried: a tool may have side effects. The call asks for progress notifications, and each one restarts its request timeout.

func (SSEClient) Close

func (c SSEClient) Close() error

Close ends the session, and a stdio server process. Idempotent.

func (SSEClient) Initialize

func (c SSEClient) Initialize(ctx context.Context) (*InitializeResponse, error)

Initialize connects to the server and agrees the protocol: server/discover first, falling back to the initialize handshake. Idempotent.

func (SSEClient) IsAlive

func (c SSEClient) IsAlive() bool

IsAlive reports whether the client is connected and its connection unbroken.

func (SSEClient) ListTools

func (c SSEClient) ListTools(ctx context.Context) ([]Tool, error)

ListTools lists every tool, following pagination. A tool that can only run as a task is left out: the client does not implement tasks.

type SamplingCapability

type SamplingCapability struct{}

SamplingCapability indicates the client supports sampling

type ServerCapabilities

type ServerCapabilities struct {
	Tools     *ToolsCapability     `json:"tools,omitempty"`
	Resources *ResourcesCapability `json:"resources,omitempty"`
	Prompts   *PromptsCapability   `json:"prompts,omitempty"`
	// Extensions lists the optional protocol extensions the server supports,
	// keyed by identifier (2026-07-28).
	Extensions map[string]json.RawMessage `json:"extensions,omitempty"`
}

ServerCapabilities describes what the server supports

type ServerConfig

type ServerConfig struct {
	Name    string            `json:"name" yaml:"name"`
	Command string            `json:"command,omitempty" yaml:"command,omitempty"`
	Args    []string          `json:"args,omitempty" yaml:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty" yaml:"env,omitempty"`
	// WorkingDir sets the working directory for the server process (stdio only).
	WorkingDir string `json:"working_dir,omitempty" yaml:"working_dir,omitempty"`
	// URL is the URL of an HTTP MCP server. Without a TransportName the
	// registry uses Streamable HTTP, falling back to HTTP+SSE if the server
	// does not host a Streamable HTTP endpoint at it.
	URL string `json:"url,omitempty" yaml:"url,omitempty"`
	// Headers are sent on HTTP transports (both SSE and Streamable HTTP).
	Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
	// TransportName selects the transport adapter explicitly. When empty it
	// is inferred: URL → Streamable HTTP (with the HTTP+SSE fallback),
	// Command → stdio.
	TransportName Transport `json:"transport,omitempty" yaml:"transport,omitempty"`
	// TimeoutMs sets the per-request timeout in milliseconds.
	TimeoutMs int `json:"timeout_ms,omitempty" yaml:"timeout_ms,omitempty"`
	// ToolFilter controls which tools from this server are exposed.
	ToolFilter *ToolFilter `json:"tool_filter,omitempty" yaml:"tool_filter,omitempty"`
}

ServerConfig represents configuration for an MCP server.

Exactly one transport should be specified:

  • Command: stdio transport — PromptKit spawns a local subprocess.
  • URL: HTTP transport — Streamable HTTP, falling back to the deprecated HTTP+SSE transport when the server does not host a Streamable HTTP endpoint. Set TransportName to pin one.

The registry selects the adapter via Transport(). Headers applies to all HTTP transports (SSE and Streamable HTTP).

func (*ServerConfig) Transport

func (c *ServerConfig) Transport() Transport

Transport returns the resolved transport. An explicit TransportName field wins; otherwise URL → TransportStreamableHTTP, Command → TransportStdio. For a URL with no TransportName the registry also falls back to HTTP+SSE when the server does not host a Streamable HTTP endpoint. Pointer receiver to avoid copying the (~120-byte) struct.

type ServerConfigData

type ServerConfigData struct {
	Name          string
	Command       string
	Args          []string
	Env           map[string]string
	WorkingDir    string
	URL           string
	Headers       map[string]string
	TransportName Transport
	TimeoutMs     int
	ToolFilter    *ToolFilter
}

ServerConfigData holds MCP server configuration matching config.MCPServerConfig. Kept in field-for-field sync with ServerConfig; adding a field here that isn't on ServerConfig (or vice versa) breaks the direct conversion used in NewRegistryWithServers.

type StdioClient

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

StdioClient runs an MCP server as a subprocess and talks to it over stdin and stdout.

func NewStdioClient

func NewStdioClient(config ServerConfig) *StdioClient

NewStdioClient creates a stdio client with default options.

func NewStdioClientWithOptions

func NewStdioClientWithOptions(config ServerConfig, options ClientOptions) *StdioClient

NewStdioClientWithOptions creates a stdio client with custom options.

func (StdioClient) CallTool

func (c StdioClient) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)

CallTool calls a tool. It is never retried: a tool may have side effects. The call asks for progress notifications, and each one restarts its request timeout.

func (StdioClient) Close

func (c StdioClient) Close() error

Close ends the session, and a stdio server process. Idempotent.

func (StdioClient) Initialize

func (c StdioClient) Initialize(ctx context.Context) (*InitializeResponse, error)

Initialize connects to the server and agrees the protocol: server/discover first, falling back to the initialize handshake. Idempotent.

func (StdioClient) IsAlive

func (c StdioClient) IsAlive() bool

IsAlive reports whether the client is connected and its connection unbroken.

func (StdioClient) ListTools

func (c StdioClient) ListTools(ctx context.Context) ([]Tool, error)

ListTools lists every tool, following pagination. A tool that can only run as a task is left out: the client does not implement tasks.

type StreamableClient

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

StreamableClient talks to an MCP server over Streamable HTTP.

func NewStreamableClient

func NewStreamableClient(config ServerConfig) *StreamableClient

NewStreamableClient creates a Streamable HTTP client with default options.

func NewStreamableClientWithOptions

func NewStreamableClientWithOptions(config ServerConfig, options ClientOptions) *StreamableClient

NewStreamableClientWithOptions creates a Streamable HTTP client with custom options.

func (StreamableClient) CallTool

func (c StreamableClient) CallTool(ctx context.Context, name string, arguments json.RawMessage) (*ToolCallResponse, error)

CallTool calls a tool. It is never retried: a tool may have side effects. The call asks for progress notifications, and each one restarts its request timeout.

func (StreamableClient) Close

func (c StreamableClient) Close() error

Close ends the session, and a stdio server process. Idempotent.

func (StreamableClient) Initialize

func (c StreamableClient) Initialize(ctx context.Context) (*InitializeResponse, error)

Initialize connects to the server and agrees the protocol: server/discover first, falling back to the initialize handshake. Idempotent.

func (StreamableClient) IsAlive

func (c StreamableClient) IsAlive() bool

IsAlive reports whether the client is connected and its connection unbroken.

func (StreamableClient) ListTools

func (c StreamableClient) ListTools(ctx context.Context) ([]Tool, error)

ListTools lists every tool, following pagination. A tool that can only run as a task is left out: the client does not implement tasks.

type Tool

type Tool struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	InputSchema json.RawMessage `json:"inputSchema"` // JSON Schema for tool input
	// Title is a display name.
	Title string `json:"title,omitempty"`
	// OutputSchema is the JSON Schema the tool's structuredContent conforms to.
	OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
	// Annotations are hints about the tool's behavior. They are not
	// guaranteed: a client MUST NOT trust them from an untrusted server.
	Annotations *ToolAnnotations `json:"annotations,omitempty"`
	// Icons are display icons (2025-11-25).
	Icons []Icon `json:"icons,omitempty"`
	// Execution says whether the tool runs as a task (2025-11-25). The
	// client does not implement tasks, so it never lists a tool that
	// requires one.
	Execution *ToolExecution             `json:"execution,omitempty"`
	Meta      map[string]json.RawMessage `json:"_meta,omitempty"`
}

Tool represents an MCP tool definition

type ToolAnnotations added in v2.10.0

type ToolAnnotations struct {
	Title           string `json:"title,omitempty"`
	ReadOnlyHint    *bool  `json:"readOnlyHint,omitempty"`
	DestructiveHint *bool  `json:"destructiveHint,omitempty"`
	IdempotentHint  *bool  `json:"idempotentHint,omitempty"`
	OpenWorldHint   *bool  `json:"openWorldHint,omitempty"`
}

ToolAnnotations are hints about a tool's behavior (server/tools).

type ToolCallRequest

type ToolCallRequest struct {
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments,omitempty"`
	// InputResponses answers a modern server's input_required result, keyed
	// as the server keyed its inputRequests (2026-07-28 MRTR).
	InputResponses map[string]json.RawMessage `json:"inputResponses,omitempty"`
	// RequestState echoes, unchanged, the requestState of the input_required
	// result being answered.
	RequestState json.RawMessage `json:"requestState,omitempty"`
}

ToolCallRequest represents a request to execute a tool

type ToolCallResponse

type ToolCallResponse struct {
	Content []Content `json:"content"`
	// StructuredContent is the tool's structured result (MCP 2025-06-18).
	// Servers SHOULD mirror it as serialized JSON in Content, but are not
	// required to, so it is the authoritative result when present.
	StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
	IsError           bool            `json:"isError,omitempty"`
	// ResultType is "complete" from a 2026-07-28 server (absent before).
	ResultType string                     `json:"resultType,omitempty"`
	Meta       map[string]json.RawMessage `json:"_meta,omitempty"`
}

ToolCallResponse represents the response from a tool execution

func (*ToolCallResponse) HasStructuredContent added in v2.10.0

func (r *ToolCallResponse) HasStructuredContent() bool

HasStructuredContent reports whether the response carries a non-null structuredContent payload.

type ToolExecution added in v2.10.0

type ToolExecution struct {
	// TaskSupport is "forbidden" (the default), "optional" or "required".
	TaskSupport string `json:"taskSupport,omitempty"`
}

ToolExecution holds a tool's execution properties (2025-11-25).

type ToolFilter

type ToolFilter struct {
	Allowlist []string `json:"allowlist,omitempty" yaml:"allowlist,omitempty"`
	Blocklist []string `json:"blocklist,omitempty" yaml:"blocklist,omitempty"`
}

ToolFilter controls which tools from an MCP server are exposed to the LLM. If Allowlist is non-empty, only those tools are included. If Blocklist is non-empty, those tools are excluded. Allowlist takes precedence over Blocklist.

func (ToolFilter) Includes

func (f ToolFilter) Includes(name string) bool

Includes returns true if the given tool name passes the filter. Allowlist and blocklist entries may use a trailing-"*" prefix wildcard.

type ToolsCapability

type ToolsCapability struct {
	ListChanged bool `json:"listChanged,omitempty"` // Server can send notifications
}

ToolsCapability indicates the server supports tools

type ToolsListRequest

type ToolsListRequest struct {
	// Cursor requests the page after the one that returned it as NextCursor.
	Cursor string `json:"cursor,omitempty"`
}

ToolsListRequest represents a request to list available tools

type ToolsListResponse

type ToolsListResponse struct {
	Tools []Tool `json:"tools"`
	// NextCursor is set when more tools follow; the client requests the next
	// page with it.
	NextCursor string `json:"nextCursor,omitempty"`
	// ResultType, TTLMs and CacheScope are set by 2026-07-28 servers.
	// TTLMs is how long the list may be cached; CacheScope is "public" or
	// "private". The client does not cache tool lists.
	ResultType string                     `json:"resultType,omitempty"`
	TTLMs      *int64                     `json:"ttlMs,omitempty"`
	CacheScope string                     `json:"cacheScope,omitempty"`
	Meta       map[string]json.RawMessage `json:"_meta,omitempty"`
}

ToolsListResponse represents the response to a tools/list request

type Transport

type Transport string

Transport identifies which transport adapter should serve a config.

const (
	// TransportUnknown means the config specifies no usable transport.
	TransportUnknown Transport = ""
	// TransportStdio is the local-subprocess transport.
	TransportStdio Transport = "stdio"
	// TransportSSE is the legacy HTTP+SSE transport (MCP 2024-11-05 spec).
	TransportSSE Transport = "sse"
	// TransportStreamableHTTP is the Streamable HTTP transport
	// (MCP 2025-03-26 spec). A single POST endpoint that returns either
	// application/json or text/event-stream.
	TransportStreamableHTTP Transport = "streamable_http"
)

type WWWAuthenticate added in v2.10.0

type WWWAuthenticate struct {
	Scheme string
	Params map[string]string
}

WWWAuthenticate is one challenge from a WWW-Authenticate header (RFC 9110 §11.6.1).

Jump to

Keyboard shortcuts

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