Documentation
¶
Overview ¶
Package mcp connects the configured Model Context Protocol servers and exposes their tools to the agent
Index ¶
- Constants
- Variables
- func AdoptLateConnections(ctx context.Context, agent LateConnectionAgent) []string
- func AgentToolNames(agent AgentToolSnapshot) []string
- func ApplyAnswer(ctx context.Context, op *tools.ConnectionOperation, raw string) (err error)
- func ApplyConnAnswer(ctx context.Context, op *tools.ConnectionOperation, raw string) error
- func ApplyMCPChange(cfg config.Tree, targets []string, action string) map[string]bool
- func ApplyMCPPreset(presetName, url, command string, cmdArgs []string, serverConfig map[string]any) error
- func ApplyOAuthProviderDefaults(cfg map[string]any, serverName, serverURL string) map[string]any
- func ApplyToolsetChange(ctx context.Context, cfg config.Tree, platform string, names []string, ...) error
- func BearerAuthHeaders(name string) map[string]any
- func BindRun(ctx context.Context, runID string) context.Context
- func BuildServerConfig(entry *CatalogEntry, installDir string) (map[string]any, error)
- func CallToolForPlugin(ctx context.Context, server, tool string, timeout float64, args map[string]any) (string, error)
- func CancelAttempt(flow *ClientOAuthFlow) bool
- func CancelOAuthFlow(ctx context.Context, sessionID, serverName, homeDir string) *pyjson.Object
- func CardInstallConfig(ctx context.Context, ui TerminalUI, entry *CatalogEntry) (map[string]any, error)
- func ChooseCallbackReceiver(flow *ClientOAuthFlow, cfg map[string]any, clientRedirectURI *string) (*http.Server, error)
- func ConfigFingerprint(cfg map[string]any) string
- func ConfigureMCPToolsInteractive(ctx context.Context, env *tools.Env, ui TerminalUI, cfg config.Tree) error
- func Connect(ctx context.Context, env *tools.Env, servers map[string]*Rendered) ([]string, error)
- func ConnectAll(ctx context.Context, env *tools.Env, allowed []string) ([]string, error)
- func DisconnectScope(ctx context.Context, scope string)
- func DiscoveryInFlight(ctx context.Context) bool
- func DropEventState(h, routeName string) error
- func EditorConnected(scope string, names map[int]string) []int
- func EditorToolsDrifted(scope string, names []string, timeout time.Duration) bool
- func EnsureDiscoveryBeforeAgentBuild(ctx context.Context, env *tools.Env, logger *slog.Logger, ...)
- func EnvKeyForServer(name string) string
- func ExceptionMessage(err error) string
- func FinishOAuthFlow(sessionID string)
- func ForceInteractiveOAuth(ctx context.Context) context.Context
- func ForgetMCPToolServer(toolName string)
- func GetCachedEntry(ctx context.Context, serverName, fingerprint string) map[string]any
- func GetMCPServers(ctx context.Context) (map[string]any, error)
- func HasConfiguredServers(ctx context.Context) bool
- func HasRegisteredTools() bool
- func HumanizeOAuthRegistrationError(serverName, msg, serverURL string) (string, bool)
- func IDKey(raw json.RawMessage) string
- func InstallByName(ctx context.Context, env *tools.Env, ui TerminalUI, identifier string) (int, error)
- func InstallEntry(ctx context.Context, env *tools.Env, ui TerminalUI, entry *CatalogEntry, ...) error
- func InterpolateServerConfig(ctx context.Context, env *tools.Env, cfg map[string]any) (any, error)
- func IsEnabled(ctx context.Context, name string) (bool, error)
- func IsInstalled(ctx context.Context, name string) (bool, error)
- func IsToolParallelSafe(ctx context.Context, toolName string) bool
- func JoinDiscovery(ctx context.Context, timeout *time.Duration) bool
- func KillOrphanedMCPChildren(includeActive bool, serverName string)
- func LoadServerConfigs(ctx context.Context, env *tools.Env) map[string]*Rendered
- func LoginConnectTimeout(serverConfig map[string]any) float64
- func LoginDevice(ctx context.Context, name, serverURL string, oauthConfig map[string]any, ...) error
- func MCPCommand(ctx context.Context, env *tools.Env, ui CLIConfigUI, a MCPArgs) (int, error)
- func MatchesNameFilter(toolName string, patterns map[string]bool) bool
- func NewStderrTee(log io.Writer) (*stderrTee, error)
- func OAuthTokensPresent(ctx context.Context, name string) bool
- func PersistAgentToolNames(ctx context.Context, agent AgentToolSnapshot)
- func PinnedToolDefs(ctx context.Context, env *tools.Env, saved any) []map[string]any
- func PluginConnector() plugins.MCPConnector
- func PollOAuthFlow(ctx context.Context, sessionID, serverName string) *pyjson.Object
- func PortableServerAvailability(ctx context.Context, decl plugins.AgentPluginServerDeclaration) (plugins.PortableAvailability, error)
- func PrefixedToolName(serverName, toolName string) string
- func Probe(ctx context.Context, env *tools.Env) map[string][]ToolSummary
- func ProbeFailureClass(err error) (class string)
- func RPCCode(err error) int
- func ReconnectServer(ctx context.Context, name string) bool
- func RefreshAgentMCPTools(ctx context.Context, agent AgentToolSnapshot, opts RefreshOptions) map[string]bool
- func RegisterOAuthFlow(flow *ClientOAuthFlow, httpd *http.Server) *oauthSession
- func RegisterRawServers(ctx context.Context, env *tools.Env, configs map[string]map[string]any) ([]string, error)
- func RegisteredServerNames() map[string]bool
- func RegistryScope(ctx context.Context) string
- func Reissue(ctx context.Context, op *tools.ConnectionOperation, names []string) (string, error)
- func RekeyUnscopedConnections(scope string)
- func RemoveOAuthTokens(ctx context.Context, serverName, homeDir string) error
- func RemoveServer(ctx context.Context, name string) (bool, error)
- func RenderCallToolResult(ctx context.Context, env *tools.Env, result *CallToolResult, serverName string, ...) string
- func ReprobeToolAvailability()
- func Respond(ctx context.Context, op *tools.ConnectionOperation, raw string) (bool, error)
- func Restart(ctx context.Context, env *tools.Env, names []string) ([]string, error)
- func RestoreAgentToolPrefix(ctx context.Context, agent AgentToolSnapshot, saved any) bool
- func Retry(ctx context.Context, op *tools.ConnectionOperation, names []string) (msg string, err error)
- func RunMCPOperation(ctx context.Context, env *tools.Env, names []string, action string, ...) string
- func RunOAuthWorker(ctx context.Context, env *tools.Env, homeDir, serverName string, ...)
- func RunPicker(ctx context.Context, env *tools.Env, ui TerminalUI) error
- func SanitizeNameComponent(value string) string
- func SaveBearerAuthToken(ctx context.Context, name, token string) (map[string]any, error)
- func SaveServer(ctx context.Context, ui TerminalUI, name string, serverConfig map[string]any) (bool, error)
- func ScopedServerNames(scope *string) map[string]bool
- func ServerAvailabilityReason(ctx context.Context, declaration plugins.AgentPluginServerDeclaration, ...) (string, bool, error)
- func ServerConfigsWithSources(ctx context.Context, configServers map[string]any) (map[string]map[string]any, map[string]*string)
- func ServerConnected(ctx context.Context, serverName string) bool
- func ServerEnabled(cfg map[string]any) bool
- func ServerReconnecting(ctx context.Context, name string) bool
- func ServerToolNames(ctx context.Context, serverName string) []string
- func ServerUnavailableState(ctx context.Context, serverName, displayName string) (state, sentence string, ok bool)
- func ServersAwaitingConnect(ctx context.Context, env *tools.Env) []string
- func ServersNotConnected(ctx context.Context, env *tools.Env) []string
- func ServersReady(ctx context.Context, env *tools.Env) []string
- func SetHomeDiscoveryRunForTests(ctx context.Context, done chan struct{}) func()
- func SetServerFilter(toolsets any) []string
- func ShowCatalog(ctx context.Context, ui TerminalUI) error
- func ShutdownMCPServers(ctx context.Context, scope *string, names []string, timeout time.Duration)
- func StartBackgroundDiscovery(ctx context.Context, env *tools.Env, logger *slog.Logger, threadName string)
- func StartOAuthFlow(ctx context.Context, env *tools.Env, homeDir, serverName string, ...) (*pyjson.Object, error)
- func StoreEventCursor(h, routeName, cursor string) error
- func StripBearerPrefix(token string) string
- func SuppressInteractiveOAuth(ctx context.Context) context.Context
- func SwapToolsConfigProbe(fn func(context.Context, *tools.Env) map[string][]ToolSummary) func(context.Context, *tools.Env) map[string][]ToolSummary
- func ToolPinVersion() string
- func ToolServerName(tool string) (string, bool)
- func ToolsDisableEnableCommand(ctx context.Context, ui TerminalUI, action, platform string, targets []string) error
- func ToolsFromCacheEntry(entry map[string]any) []any
- func TrackMCPToolServer(toolName, serverName string)
- func TransferSession(oldKey, newKey string)
- func UninstallEntry(ctx context.Context, name string, purgeInstallDir bool) (bool, error)
- func UnknownCostKeys(policy *CostPolicy, toolNames []string) []string
- func UtilityToolsFromCacheEntry(entry map[string]any) []any
- func ValidateClientRedirectURI(uri string) (string, error)
- func ValidateMCPNames(ctx context.Context, env *tools.Env, action string, names []string) string
- func ValidateServerEntry(name string, entry map[string]any) []string
- func WaitForDiscovery(ctx context.Context, env *tools.Env, timeout *time.Duration, singleQuery bool)
- func WriteCacheEntry(ctx context.Context, serverName, fingerprint string, tools, utilityTools []any, ...) error
- type AgentToolSnapshot
- type AppAvailability
- type AppDeclaration
- type AppDefinition
- type AppProbe
- type AttemptCanceled
- type AttemptPoll
- type AuthSpec
- type Authenticator
- type AuthorizationCodeResult
- type CLIConfigUI
- type CacheHints
- type CallToolResult
- type CardOAuthOptions
- type CardURLTimeout
- type CatalogDiagnostic
- type CatalogEntry
- type CatalogError
- type Charge
- func (c *Charge) Asking() func()
- func (c *Charge) Book()
- func (c *Charge) CostSentence() string
- func (c *Charge) Lines(already float64) []string
- func (c *Charge) OverLimit(already float64) bool
- func (c *Charge) Refund()
- func (c *Charge) Refusal(already float64) string
- func (c *Charge) ReserveWithinLimit() (bool, float64)
- func (c *Charge) SpendSentence(already float64) string
- func (c *Charge) Spent() float64
- type ChatAux
- type ClientCapabilities
- type ClientOAuthFlow
- func (f *ClientOAuthFlow) AuthorizationURL() string
- func (f *ClientOAuthFlow) Cancelled() bool
- func (f *ClientOAuthFlow) DeliverCallback(code, state, errText, iss string) error
- func (f *ClientOAuthFlow) ExpectedState() string
- func (f *ClientOAuthFlow) Failure() string
- func (f *ClientOAuthFlow) MarkApproved() error
- func (f *ClientOAuthFlow) MarkError(errText string, cancelled bool)
- func (f *ClientOAuthFlow) MarkWorkerDone()
- func (f *ClientOAuthFlow) PublishAuthorizationURL(_ context.Context, rawURL string) error
- func (f *ClientOAuthFlow) Snapshot() map[string]any
- func (f *ClientOAuthFlow) Status() string
- func (f *ClientOAuthFlow) WaitForAuthorizationURL(ctx context.Context, timeout time.Duration) (string, error)
- func (f *ClientOAuthFlow) WaitForCallback(ctx context.Context, timeout time.Duration) (code, state, iss string, err error)
- func (f *ClientOAuthFlow) WorkerDone() bool
- type ClientOAuthTimeoutError
- type ClientOAuthValueError
- type ConnectorAttempt
- type ConnectorBackend
- type ContentBlock
- type CostPolicy
- type CreateMessageParams
- type CredentialStamp
- type DiscoveryPass
- type ElicitParams
- type ElicitResult
- type Elicitor
- type EnvVarSpec
- type FieldError
- type GetPromptResult
- type HTTPOptions
- type HTTPRejection
- type HTTPStatusError
- type Implementation
- type InitializeParams
- type InitializeResult
- type InstallSpec
- type InvalidMCPURLError
- type LateConnectionAgent
- type LiveEndpointUnavailableError
- type Liveness
- type LivenessStatus
- type LockCookie
- type LoggingMessageParams
- type LoopTimeoutError
- type MCPArgs
- type Message
- func DecodeMessages(data []byte) ([]*Message, error)
- func NewErrorResponse(id json.RawMessage, code int, message string) *Message
- func NewNotification(method string, params any) (*Message, error)
- func NewRequest(method string, params any) (*Message, error)
- func NewResponse(id json.RawMessage, result any) (*Message, error)
- type ModelHint
- type ModelPreferences
- type NodeABIMismatchError
- type NonMCPEndpointError
- type OAuthAttempt
- type OAuthClientInfo
- type OAuthClientMetadata
- type OAuthFlowError
- type OAuthManager
- type OAuthMetadata
- type OAuthNonInteractiveError
- type OAuthProvider
- func (p *OAuthProvider) ClientMetadata() *OAuthClientMetadata
- func (p *OAuthProvider) CurrentTokens() *OAuthToken
- func (p *OAuthProvider) HandleUnauthorized(ctx context.Context, req *http.Request, resp *http.Response) (bool, error)
- func (p *OAuthProvider) Prepare(ctx context.Context, req *http.Request) error
- func (p *OAuthProvider) Storage() *TokenStorage
- type OAuthRegistrationError
- type OAuthToken
- type OAuthTokenError
- type OAuthWorkerOptions
- type PickerRow
- type ProbeDetails
- type ProbeError
- type ProgressFunc
- type ProgressParams
- type Prompt
- type PromptArgument
- type PromptMessage
- type ProtectedResourceMetadata
- type RPCError
- type ReadResourceResult
- type ReconcileResult
- type RefreshFenceTimeout
- type RefreshOptions
- type Rendered
- type Resource
- type ResourceContents
- type RuntimeError
- type SSEEvent
- type SSEReader
- type SSETransport
- type Sampler
- type SamplingMessage
- type SamplingTool
- type ServerCapabilities
- type ServerConfig
- type ServerKey
- type ServerStatus
- type Session
- func (s *Session) CallTool(ctx context.Context, name string, args map[string]any, progress ProgressFunc) (*CallToolResult, error)
- func (s *Session) Close() error
- func (s *Session) CompleteHandshakeAtOfferedVersion(ctx context.Context) (*InitializeResult, error)
- func (s *Session) Discover(ctx context.Context) (*InitializeResult, error)
- func (s *Session) Done() <-chan struct{}
- func (s *Session) Err() error
- func (s *Session) GetPrompt(ctx context.Context, name string, args map[string]string) (*GetPromptResult, error)
- func (s *Session) Initialize(ctx context.Context) (*InitializeResult, error)
- func (s *Session) InitializeResult() *InitializeResult
- func (s *Session) ListPrompts(ctx context.Context) ([]*Prompt, error)
- func (s *Session) ListResources(ctx context.Context) ([]*Resource, error)
- func (s *Session) ListTools(ctx context.Context, hints *CacheHints) ([]*Tool, error)
- func (s *Session) Name() string
- func (s *Session) Negotiate(ctx context.Context, mode string, connectTimeout time.Duration) (*InitializeResult, error)
- func (s *Session) Ping(ctx context.Context) error
- func (s *Session) ProtocolVersion() string
- func (s *Session) ReadResource(ctx context.Context, uri string) (*ReadResourceResult, error)
- type SessionOptions
- type StdioParams
- type StdioTransport
- func (t *StdioTransport) Alive() bool
- func (t *StdioTransport) Close() error
- func (t *StdioTransport) Err() error
- func (t *StdioTransport) Exited() <-chan struct{}
- func (t *StdioTransport) Label() string
- func (t *StdioTransport) PGID() int
- func (t *StdioTransport) PID() int
- func (t *StdioTransport) Receive() <-chan *Message
- func (t *StdioTransport) Send(ctx context.Context, msg *Message) error
- type StreamableHTTPTransport
- func (t *StreamableHTTPTransport) Close() error
- func (t *StreamableHTTPTransport) Err() error
- func (t *StreamableHTTPTransport) Label() string
- func (t *StreamableHTTPTransport) OpenStandaloneStream(ctx context.Context)
- func (t *StreamableHTTPTransport) Receive() <-chan *Message
- func (t *StreamableHTTPTransport) Rejection() HTTPRejection
- func (t *StreamableHTTPTransport) Send(ctx context.Context, msg *Message) error
- func (t *StreamableHTTPTransport) SessionID() string
- func (t *StreamableHTTPTransport) SetProtocolVersion(v string)
- type TerminalUI
- type TimeoutError
- type TokenStorage
- func (s *TokenStorage) BindIssuer(issuer string)
- func (s *TokenStorage) CIMDRejected() bool
- func (s *TokenStorage) CIMDRejectedPath() string
- func (s *TokenStorage) ClientInfoPath() string
- func (s *TokenStorage) CredentialStamp() CredentialStamp
- func (s *TokenStorage) GetClientInfo(ctx context.Context) (*OAuthClientInfo, error)
- func (s *TokenStorage) GetTokens() (*OAuthToken, error)
- func (s *TokenStorage) HasCachedTokens() bool
- func (s *TokenStorage) HomeDir() string
- func (s *TokenStorage) LoadOAuthMetadata() *OAuthMetadata
- func (s *TokenStorage) LoadedIssuer() string
- func (s *TokenStorage) MarkCIMDRejected(ctx context.Context)
- func (s *TokenStorage) MetaPath() string
- func (s *TokenStorage) PoisonClientRegistration() bool
- func (s *TokenStorage) Remove(keepMetadata bool) error
- func (s *TokenStorage) Restore(ctx context.Context, snap map[string][]byte, onlyIfAbsent bool) error
- func (s *TokenStorage) SaveOAuthMetadata(ctx context.Context, md *OAuthMetadata) error
- func (s *TokenStorage) ServerName() string
- func (s *TokenStorage) SetClientInfo(ctx context.Context, info *OAuthClientInfo) error
- func (s *TokenStorage) SetTokens(ctx context.Context, t *OAuthToken) error
- func (s *TokenStorage) Snapshot() map[string][]byte
- func (s *TokenStorage) StampIssuer(ctx context.Context, issuer string)
- func (s *TokenStorage) StripRefreshToken(ctx context.Context)
- func (s *TokenStorage) TokensPath() string
- type Tool
- type ToolAnnotations
- type ToolCost
- type ToolPinStore
- type ToolSummary
- func ProbeSingleServer(ctx context.Context, env *tools.Env, name string, cfg map[string]any) ([]ToolSummary, error)
- func ProbeSingleServerDetails(ctx context.Context, env *tools.Env, name string, cfg map[string]any, ...) ([]ToolSummary, error)
- func ProbeSingleServerTimeout(ctx context.Context, env *tools.Env, name string, cfg map[string]any, ...) ([]ToolSummary, error)
- type ToolsSpec
- type Transport
- type TransportSpec
- type URLElicitationError
- type UnsetReferenceError
- type UnsupportedServerVersionError
- type UtilitySchema
- type ValidationError
Constants ¶
const ( TrustFull = "full" TrustUntrusted = "untrusted" )
Trust tiers a server entry may declare
const ( CodeParseError = -32700 CodeInvalidRequest = -32600 CodeMethodNotFound = -32601 CodeInvalidParams = -32602 CodeInternalError = -32603 CodeUnsupportedProtocolVersion = -32022 )
JSON-RPC 2.0 error codes the client reasons about
const ClientName = "icebath-agent"
ClientName is the clientInfo name every server sees
const CodeURLElicitationRequired = -32042
CodeURLElicitationRequired is the 2025-11-25 error a request gets until a URL mode elicitation is finished
const DefaultCostUnit = "credits"
Unit label a cost table counts in when it names none
const LatestHandshakeVersion = "2025-11-25"
Newest revision the initialize handshake speaks and the MCP-Protocol-Version header is seeded from
const LatestProtocolVersion = "2026-07-28"
Newest revision the client knows, reached through the stateless server/discover probe
const MaxHTTPBodyBytes = 10 * 1024 * 1024
Wire body cap applied before any JSON parse, per finite body and per SSE event
const NoTimeout time.Duration = -1
NoTimeout lets a loop call run until it finishes or is interrupted
const ToolNamePrefix = "mcp__"
ToolNamePrefix starts every native MCP tool name
Variables ¶
var ClientVersion = "dev"
ClientVersion is the clientInfo version, set by the binary at startup
var ConfigWriteScope = func(ctx context.Context, profile string) (context.Context, func()) { if profile != "" { ctx = home.WithOverride(ctx, profile) } return provider.LockConfigMutation(ctx) }
ConfigWriteScope enters the profile scope then the one process wide config mutation lock
var CostConfigKeys = []string{"tool_costs", "spend_limit", "cost_unit"}
Native mcp_servers keys that declare costs, a portable package's costs maps onto tool_costs
var ErrBodyTooLarge = errors.New("MCP response exceeds the wire body cap")
ErrBodyTooLarge marks a response or event over the wire cap
var ErrEditorSchemaChanged = errors.New("acp_mcp_schema_changed")
ErrEditorSchemaChanged is the state authority refusal when an editor session server changes its frozen manifest
var ErrInterrupted = errors.New("User sent a new message")
ErrInterrupted ends a loop call when the user sent a new message
var ErrSessionExpired = errors.New("session expired: the server no longer knows this Mcp-Session-Id (session not found)")
ErrSessionExpired marks a 404 the server gave for a known session id
var SupportedProtocolVersions = []string{"2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"}
Protocol revisions this client negotiates, newest handshake revision last
var TUIProfileRuntimeScope func(ctx context.Context, profileHome string) context.Context
Profile runtime scope of the tui gateway, set by the binary
Functions ¶
func AdoptLateConnections ¶
func AdoptLateConnections(ctx context.Context, agent LateConnectionAgent) []string
Registers servers whose authorization committed after their card closed and adds them to the agent toolsets
func AgentToolNames ¶
func AgentToolNames(agent AgentToolSnapshot) []string
AgentToolNames lists the agent tool names in wire order skipping unnamed entries
func ApplyAnswer ¶
Folds the card's answer into the operation, a skip, an approval that starts the work and Continue
func ApplyConnAnswer ¶
Hands the card's answer to the catalog or MCP module running the operation
func ApplyMCPChange ¶
Toggles server and tool targets in each server exclude list for callers outside the package, returning servers not in config
func ApplyMCPPreset ¶
func ApplyMCPPreset(presetName, url, command string, cmdArgs []string, serverConfig map[string]any) error
Fills transport details from a known preset when none were given, an error for an unknown preset
func ApplyOAuthProviderDefaults ¶
Fills provider specific OAuth defaults the user left unset, returning cfg
func ApplyToolsetChange ¶
func ApplyToolsetChange(ctx context.Context, cfg config.Tree, platform string, names []string, action string) error
ApplyToolsetChange adds or removes toolset keys from a platform's saved toolsets for callers outside the package
func BearerAuthHeaders ¶
Persisted Authorization header template naming the MCP_<NAME>_API_KEY env key
func BindRun ¶
Binds a cron run id so each run gets its own tally instead of sharing the empty session key
func BuildServerConfig ¶
func BuildServerConfig(entry *CatalogEntry, installDir string) (map[string]any, error)
The mcp_servers block a catalog manifest translates to, before credentials and tool filters
func CallToolForPlugin ¶
func CallToolForPlugin(ctx context.Context, server, tool string, timeout float64, args map[string]any) (string, error)
Calls one tool of a server through the registered handler, the same trust gates and breaker as the agent
func CancelAttempt ¶
func CancelAttempt(flow *ClientOAuthFlow) bool
Cancels a card attempt, true when it had already committed so the authorization stays
func CancelOAuthFlow ¶
Cancels only the owning profile's flow and releases its callback waiter
func CardInstallConfig ¶
func CardInstallConfig(ctx context.Context, ui TerminalUI, entry *CatalogEntry) (map[string]any, error)
Server block a connection card installs, built in memory with the prior or manifest tool filter
func ChooseCallbackReceiver ¶
func ChooseCallbackReceiver(flow *ClientOAuthFlow, cfg map[string]any, clientRedirectURI *string) (*http.Server, error)
Sets the redirect the SDK consumes and returns the backend receiver when one is bound
func ConfigFingerprint ¶
Stable sixteen hex digit hash of the connection defining parts of a server entry
func ConfigureMCPToolsInteractive ¶
func ConfigureMCPToolsInteractive(ctx context.Context, env *tools.Env, ui TerminalUI, cfg config.Tree) error
ConfigureMCPToolsInteractive is the tools command entry of the per server tool checklist
func Connect ¶
Connect registers the tools of every enabled, not yet connected server, idempotent for connected names, and returns every MCP tool name
func ConnectAll ¶
ConnectAll loads config and connects every configured server, or only the allowed names when allowed is non nil
func DisconnectScope ¶
Closes every connection the editor scope owns and deregisters its tools
func DiscoveryInFlight ¶
Reports whether this home's discovery goroutine is still running
func DropEventState ¶
Forgets the grant, cursor and URL recorded for a route
func EditorConnected ¶
Indexes whose named connection under the editor scope has a live session, ascending
func EditorToolsDrifted ¶
Whether a held server's live tools list differs from its discovered one, an unanswered list counting as unchanged
func EnsureDiscoveryBeforeAgentBuild ¶
func EnsureDiscoveryBeforeAgentBuild(ctx context.Context, env *tools.Env, logger *slog.Logger, timeout *time.Duration, singleQuery bool, threadName string)
Starts discovery when needed and gives configured MCP tools a bounded chance to register before an agent builds
func EnvKeyForServer ¶
Env key holding the API key of a server, MCP_<NAME>_API_KEY
func ExceptionMessage ¶
Error text, or the error type name when the text is empty
func FinishOAuthFlow ¶
func FinishOAuthFlow(sessionID string)
Releases a finished flow's listener and keeps its relay visible outcome
func ForceInteractiveOAuth ¶
Context treated as interactive without a console, for GUI driven logins whose person is present
func ForgetMCPToolServer ¶
func ForgetMCPToolServer(toolName string)
Exported provenance removal paired with the exported tracking
func GetCachedEntry ¶
Cached entry of a server when its fingerprint matches and its recorded TTL still holds
func GetMCPServers ¶
The mcp_servers mapping of the home user config, empty when none is configured
func HasConfiguredServers ¶
Reports configured MCP servers or enabled plugin MCP packages, true when the config cannot be read
func HasRegisteredTools ¶
func HasRegisteredTools() bool
HasRegisteredTools reports whether any MCP server registered tools, not merely connected
func HumanizeOAuthRegistrationError ¶
Actionable next step for a registration refusal or missing registration endpoint, false to keep the original text
func IDKey ¶
func IDKey(raw json.RawMessage) string
IDKey normalizes a raw id so numeric and string spellings index one pending map
func InstallByName ¶
func InstallByName(ctx context.Context, env *tools.Env, ui TerminalUI, identifier string) (int, error)
Non interactive install of a catalog entry by name, exit code 0 on success and 1 otherwise
func InstallEntry ¶
func InstallEntry(ctx context.Context, env *tools.Env, ui TerminalUI, entry *CatalogEntry, enable bool, preloadedEnv map[string]string) error
Installs a catalog entry end to end
func InterpolateServerConfig ¶
Server config with every environment reference expanded the way the connect path renders it
func IsInstalled ¶
True when mcp_servers holds the name
func IsToolParallelSafe ¶
IsToolParallelSafe reports whether the tool's registering server opted into parallel tool calls
func JoinDiscovery ¶
Waits up to timeout for this home's discovery, true once complete and false while it still runs
func KillOrphanedMCPChildren ¶
Reaps orphaned MCP child processes the way the cron scheduler sweep asks for them
func LoadServerConfigs ¶
Every mcp_servers entry of the active profile rendered, suspicious and malformed ones dropped, empty in safe mode
func LoginConnectTimeout ¶
Seconds an interactive login probe may take, the connect timeout or the callback window plus 15 seconds
func LoginDevice ¶
func LoginDevice(ctx context.Context, name, serverURL string, oauthConfig map[string]any, transport HTTPOptions) error
Runs an RFC 8628 device login and commits client, metadata and tokens together, restoring the old state on a write failure
func MCPCommand ¶
Dispatches one icebath mcp subcommand and returns the process exit code
func MatchesNameFilter ¶
Reports whether a tool name matches an exact entry or a case sensitive glob entry
func NewStderrTee ¶
Tee copying child stderr into log as stamped lines, the writer of mcp-stderr.log
func OAuthTokensPresent ¶
Whether a usable OAuth token for the server is stored in the home of ctx
func PersistAgentToolNames ¶
func PersistAgentToolNames(ctx context.Context, agent AgentToolSnapshot)
PersistAgentToolNames writes the agent tools pin to its session row and remembers what it was built against
func PinnedToolDefs ¶
PinnedToolDefs returns a pin definitions as a fresh agent restores them, keeping pinned bytes
func PluginConnector ¶
func PluginConnector() plugins.MCPConnector
Plugin facing MCP connector service cmd/icebath installs as plugins.Services.MCP
func PollOAuthFlow ¶
Polls a session for pending, approved or error with its link and tools
func PortableServerAvailability ¶
func PortableServerAvailability(ctx context.Context, decl plugins.AgentPluginServerDeclaration) (plugins.PortableAvailability, error)
Install time availability verdict of a portable server declaration
func PrefixedToolName ¶
Registry and wire name mcp__server__tool clamped to 64 characters with a stable hash suffix
func Probe ¶
Probe connects each enabled server, lists its tools and disconnects, registering nothing and omitting failed servers
func ProbeFailureClass ¶
Extension install failure class of a failed probe from its tag or error type, never its message
func RPCCode ¶
RPCCode extracts the JSON-RPC error code carried anywhere in an error chain, zero when none
func ReconnectServer ¶
Asks a live server to rebuild after external re-auth, false when no such server is connected
func RefreshAgentMCPTools ¶
func RefreshAgentMCPTools(ctx context.Context, agent AgentToolSnapshot, opts RefreshOptions) map[string]bool
Rebuilds a live agent tool snapshot from the registry and returns the newly added tool names
func RegisterOAuthFlow ¶
func RegisterOAuthFlow(flow *ClientOAuthFlow, httpd *http.Server) *oauthSession
Registers a callback relay flow so RPC and card starts share ownership checks
func RegisterRawServers ¶
func RegisterRawServers(ctx context.Context, env *tools.Env, configs map[string]map[string]any) ([]string, error)
Connects raw server configs in the bound tool scope without interpolating them, returning every tool name
func RegisteredServerNames ¶
RegisteredServerNames lists the servers that registered at least one tool
func RegistryScope ¶
Registry scope key of the MCP servers bound to the profile of ctx
func RekeyUnscopedConnections ¶
func RekeyUnscopedConnections(scope string)
Moves every bare name connection, its owner and its tools under scope once a single profile process starts multiplexing
func RemoveOAuthTokens ¶
Deletes every stored OAuth file of a server
func RemoveServer ¶
Removes a server from config.yaml, dropping the mapping once empty, reporting whether it existed
func RenderCallToolResult ¶
func RenderCallToolResult(ctx context.Context, env *tools.Env, result *CallToolResult, serverName string, imagePaths *[]string) string
Handler JSON for a tool result, content and structured content both forwarded unless a text block dual emits it
func ReprobeToolAvailability ¶
func ReprobeToolAvailability()
ReprobeToolAvailability drops the cached availability verdicts and the memoized tool definitions
func Respond ¶
Applies the card's answer, settles once every row resolved and closes a settled operation
func Restart ¶
Restart reconnects each named live server whose resolved launch inputs changed, detaching borrowed connections, and returns the names restarted
func RestoreAgentToolPrefix ¶
func RestoreAgentToolPrefix(ctx context.Context, agent AgentToolSnapshot, saved any) bool
RestoreAgentToolPrefix folds a freshly built agent tools onto the session pin and reports a change
func Retry ¶
func Retry(ctx context.Context, op *tools.ConnectionOperation, names []string) (msg string, err error)
Re-runs the named MCP targets on the open operation, the refusal text when this module is not running it
func RunMCPOperation ¶
func RunMCPOperation(ctx context.Context, env *tools.Env, names []string, action string, opts tools.MCPOperationOptions) string
Runs one MCP manage_connections action, a card operation with a callback and the links at once without
func RunOAuthWorker ¶
func RunOAuthWorker(ctx context.Context, env *tools.Env, homeDir, serverName string, cfg map[string]any, reconnectLive bool, o OAuthWorkerOptions)
Drives the interactive MCP OAuth probe under the profile home and its secret scope
func RunPicker ¶
Interactive selector that re-renders after each action until cancelled, a text dump off a terminal
func SanitizeNameComponent ¶
Name component with every character outside letters digits and underscore replaced by underscore
func SaveBearerAuthToken ¶
Saves a normalized bearer token to the profile .env and returns the header template
func SaveServer ¶
func SaveServer(ctx context.Context, ui TerminalUI, name string, serverConfig map[string]any) (bool, error)
Adds or replaces a server entry in config.yaml, false when validation rejects it
func ScopedServerNames ¶
Names of the live connections visible from scope, every connection for a nil scope
func ServerAvailabilityReason ¶
func ServerAvailabilityReason(ctx context.Context, declaration plugins.AgentPluginServerDeclaration, appTitle string) (string, bool, error)
Why a declared server cannot be offered, offerable true with an empty reason when its app is available
func ServerConfigsWithSources ¶
func ServerConfigsWithSources(ctx context.Context, configServers map[string]any) (map[string]map[string]any, map[string]*string)
Config server entries plus the safe plugin portable ones, each name mapped to its owning plugin or nil
func ServerConnected ¶
Whether the connection the current scope resolves for a server holds a session or was recycled on purpose
func ServerEnabled ¶
Reports whether a server entry is on, absent null or unparseable counting as on
func ServerReconnecting ¶
ServerReconnecting reports whether this scope's connection was up once and is now healing from a transient outage
func ServerToolNames ¶
Tool names the resolved connection of a server registered plus the ones its schema cache holds
func ServerUnavailableState ¶
func ServerUnavailableState(ctx context.Context, serverName, displayName string) (state, sentence string, ok bool)
Unavailable state and its sentence for a declared server, ok false when it declares no app
func ServersAwaitingConnect ¶
ServersAwaitingConnect lists enabled servers the next ConnectAll would connect
func ServersNotConnected ¶
ServersNotConnected lists enabled servers this scope does not serve after a reload, parked and failed ones included
func ServersReady ¶
ServersReady lists enabled servers this scope serves now, live or lazily registered and not failed
func SetHomeDiscoveryRunForTests ¶
Puts a discovery run that ends when done closes in the slot of the caller's home, nil emptying it, and returns the restore
func SetServerFilter ¶
Stores the MCP spawn allowlist from a toolsets value, all or star or empty clears it
func ShowCatalog ¶
func ShowCatalog(ctx context.Context, ui TerminalUI) error
Prints the curated catalog and custom servers without interaction
func ShutdownMCPServers ¶
Closes the selected connections in parallel and stops the loop, a nil scope with no names closes every server
func StartBackgroundDiscovery ¶
func StartBackgroundDiscovery(ctx context.Context, env *tools.Env, logger *slog.Logger, threadName string)
Starts one background discovery per profile home, retrying when the last run connected nothing or missed new servers
func StartOAuthFlow ¶
func StartOAuthFlow(ctx context.Context, env *tools.Env, homeDir, serverName string, cfg map[string]any, reconnectLive bool, urlTimeout time.Duration, clientRedirectURI *string) (*pyjson.Object, error)
Begins an RPC MCP OAuth flow and returns its session id and authorization URL once published
func StoreEventCursor ¶
Persists the newest replay cursor a delivery carried for a route that still exists
func StripBearerPrefix ¶
Pasted token without a leading Bearer word and surrounding whitespace
func SuppressInteractiveOAuth ¶
Context in which OAuth never prompts on stdin nor starts a browser flow
func SwapToolsConfigProbe ¶
func SwapToolsConfigProbe(fn func(context.Context, *tools.Env) map[string][]ToolSummary) func(context.Context, *tools.Env) map[string][]ToolSummary
SwapToolsConfigProbe replaces the configurator probe, returning the previous one
func ToolPinVersion ¶
func ToolPinVersion() string
ToolPinVersion is the code identity a tools pin was built by, the build sha else the release version
func ToolServerName ¶
Server that registered the MCP tool, false when no server did
func ToolsDisableEnableCommand ¶
func ToolsDisableEnableCommand(ctx context.Context, ui TerminalUI, action, platform string, targets []string) error
Lists, enables or disables toolsets and server tool MCP targets for one platform
func ToolsFromCacheEntry ¶
Cached tool dicts with name, description and inputSchema
func TrackMCPToolServer ¶
func TrackMCPToolServer(toolName, serverName string)
Exported tool server tracking for packages that simulate a live MCP registration
func TransferSession ¶
func TransferSession(oldKey, newKey string)
Moves a chat's totals to its new session id so a rotation never hands it a fresh budget
func UninstallEntry ¶
Removes a catalog installed server from config and optionally its clone, true when anything was removed
func UnknownCostKeys ¶
func UnknownCostKeys(policy *CostPolicy, toolNames []string) []string
Declared tool names the server does not offer, sorted, so registration can warn about the typo
func UtilityToolsFromCacheEntry ¶
Cached schema and handler_key utility rows
func ValidateClientRedirectURI ¶
Accepts only plain http loopback URLs and returns the normalized redirect
func ValidateMCPNames ¶
The reason names do not fit action, install taking catalog entries and the rest configured servers
func ValidateServerEntry ¶
Security warnings for one server entry, empty when it is not one of the three blocked shapes
Types ¶
type AgentToolSnapshot ¶
type AgentToolSnapshot interface {
ToolDefs() []map[string]any
SetToolSnapshot(defs []map[string]any, names map[string]bool)
EnabledToolsets() []string
DisabledToolsets() []string
SetToolsets(enabled, disabled []string)
SetConfiguredDisabledToolsets(disabled []string)
ConfiguredDisabledToolsets() []string
Platform() string
SnapshotGeneration() (int64, bool)
SnapshotSelection() (string, bool)
RecordSnapshot(generation int64, selection string)
PublishContextEngineToolNames(names map[string]bool)
ToolPinStore() ToolPinStore
SessionID() string
DelegationBackend() string
MemoryToolSchemas() func() ([]any, error)
ContextEngineToolSchemas() func() ([]any, error)
ToolEnv() *tools.Env
ToolSurface(defs []map[string]any) []map[string]any
ToolDrops() map[string]bool
IsOneshot() bool
MemoryProviderToolsEnabled(enabled, disabled []string, memoryToolPresent bool) bool
SavedDelegationBackend() string
AdoptBuiltBackend(defs []any, backend any)
AdoptSessionDelegationMode()
MessageAgentAuthorized() bool
MessageAgentToolSchema() map[string]any
}
AgentToolSnapshot is the live agent surface the tool snapshot maintenance reads, publishes and delegates to
type AppAvailability ¶
AppAvailability is the install time availability verdict of a declaration
type AppDeclaration ¶
type AppDeclaration struct {
Name string
RequiredGPU string
AppFor func(osFamily string) (AppDefinition, bool)
Platform any
}
AppDeclaration is the registered platform declaration of an application backed server
type AppDefinition ¶
type AppDefinition struct {
Platform any
LivenessKind string
LivenessPath string
LivenessPIDKey string
LivenessURLKey string
LivenessTokenKey string
}
AppDefinition is a platform app definition plus the liveness keys its resolver reads
type AttemptCanceled ¶
type AttemptCanceled struct{}
AttemptCanceled is a card attempt the user canceled before it committed, nothing of it kept
func (*AttemptCanceled) Error ¶
func (*AttemptCanceled) Error() string
type AttemptPoll ¶
AttemptPoll is an attempt's status with its tools and discovery error once approved
type Authenticator ¶
type Authenticator interface {
// Prepare adds credentials to req, acquiring them when none are cached
Prepare(ctx context.Context, req *http.Request) error
HandleUnauthorized(ctx context.Context, req *http.Request, resp *http.Response) (bool, error)
}
Authenticator decorates outbound requests with credentials and reacts to an unauthorized answer
type AuthorizationCodeResult ¶
type AuthorizationCodeResult struct {
Code, State, Iss string
}
AuthorizationCodeResult carries the redirect parameters, empty strings standing for absent ones
type CLIConfigUI ¶
type CLIConfigUI interface {
TerminalUI
Input(display string) (string, bool)
}
CLIConfigUI is a terminal whose raw line input reports end of input or an interrupt as false
type CacheHints ¶
CacheHints are the SEP-2549 hints the first page of a list carries
type CallToolResult ¶
type CallToolResult struct {
Content []*ContentBlock `json:"content"`
StructuredContent any `json:"structuredContent,omitempty"`
IsError bool `json:"isError,omitempty"`
Meta map[string]any `json:"_meta,omitempty"`
}
CallToolResult is the answer to tools/call
func (*CallToolResult) UnmarshalJSON ¶
func (r *CallToolResult) UnmarshalJSON(data []byte) error
Decodes structured content like json.loads, integers kept integers and keys in wire order
type CardOAuthOptions ¶
type CardOAuthOptions struct {
URLTimeout time.Duration
ClientRedirectURI *string
Cfg map[string]any
Env *pyjson.Object
OnCommit func(context.Context) error
}
CardOAuthOptions carries an install's in memory config, its setup values and commit hook, and the redirect
type CardURLTimeout ¶
type CardURLTimeout struct{ Server string }
CardURLTimeout is a card flow whose provider never published an authorization URL
func (*CardURLTimeout) Error ¶
func (e *CardURLTimeout) Error() string
type CatalogDiagnostic ¶
func CatalogDiagnostics ¶
func CatalogDiagnostics() []CatalogDiagnostic
Skipped manifests of the latest listing, future_manifest for newer versions and invalid otherwise
type CatalogEntry ¶
type CatalogEntry struct {
Name string
Description string
Source string
Transport TransportSpec
Auth AuthSpec
ConnectorSlug string
Tools ToolsSpec
Install *InstallSpec
PostInstall string
ManifestPath string
}
func GetEntry ¶
func GetEntry(name string) (*CatalogEntry, error)
Catalog entry by name with an optional official/ prefix, nil when absent
func ListCatalog ¶
func ListCatalog() ([]*CatalogEntry, error)
Every valid catalog entry sorted by name, recording skipped manifests for CatalogDiagnostics
type CatalogError ¶
Manifest or install failure naming the failure class the install metric records
func (*CatalogError) Error ¶
func (e *CatalogError) Error() string
func (*CatalogError) FailureClass ¶
func (e *CatalogError) FailureClass() string
Failure class of the raise site, config_invalid when the site named none
type Charge ¶
type Charge struct {
Server string
Tool string
Cost ToolCost
Policy *CostPolicy
// contains filtered or unexported fields
}
Charge is one costed call about to be admitted, what it costs and whose tally it lands on
func PendingCharge ¶
func PendingCharge(ctx context.Context, policyKey ServerKey, serverName, toolName, sessionKey string) *Charge
Charge a call would add, nil for an undeclared or zero cost tool
func (*Charge) Asking ¶
func (c *Charge) Asking() func()
Holds this chat's budget prompt slot until the returned release runs
func (*Charge) CostSentence ¶
Sentence naming the call's declared cost
func (*Charge) ReserveWithinLimit ¶
Books the estimate when it keeps the chat within its limit, returning whether it booked and the spend before
func (*Charge) SpendSentence ¶
Sentence naming the chat's spend so far or its limit, empty when neither applies
type ChatAux ¶
type ChatAux interface {
CompleteChat(ctx context.Context, messages []map[string]any, toolDefs []map[string]any, opts tools.AuxOptions) (map[string]any, error)
}
ChatAux is the auxiliary client surface sampling needs, an OpenAI shaped chat completion that forwards tools
type ClientCapabilities ¶
type ClientCapabilities struct {
Sampling map[string]any `json:"sampling,omitzero"`
Elicitation map[string]any `json:"elicitation,omitzero"`
Roots map[string]any `json:"roots,omitempty"`
Experimental map[string]any `json:"experimental,omitempty"`
}
ClientCapabilities advertised in initialize
type ClientOAuthFlow ¶
type ClientOAuthFlow struct {
FlowID string
ServerName string
Profile string
HomeDir string
RedirectURI string
ReconnectLive bool
CreatedAt time.Time
Tools []map[string]any
DiscoveryError string
// contains filtered or unexported fields
}
Moves the authorization URL and the browser callback of one MCP login through the relaying client
func NewClientOAuthFlow ¶
func NewClientOAuthFlow(flowID, serverName, profile, homeDir, redirectURI string, reconnectLive bool) *ClientOAuthFlow
Flow in the starting state stamped with its creation time
func (*ClientOAuthFlow) AuthorizationURL ¶
func (f *ClientOAuthFlow) AuthorizationURL() string
Authorization URL the client shows, empty before one was published
func (*ClientOAuthFlow) Cancelled ¶
func (f *ClientOAuthFlow) Cancelled() bool
Reports whether the user abandoned the flow for good
func (*ClientOAuthFlow) DeliverCallback ¶
func (f *ClientOAuthFlow) DeliverCallback(code, state, errText, iss string) error
Hands the browser redirect to the waiting flow once, its state matching exactly
func (*ClientOAuthFlow) ExpectedState ¶
func (f *ClientOAuthFlow) ExpectedState() string
State parameter the next callback must carry, empty when none is expected
func (*ClientOAuthFlow) Failure ¶
func (f *ClientOAuthFlow) Failure() string
Recorded failure cause, empty while the flow has not failed
func (*ClientOAuthFlow) MarkApproved ¶
func (f *ClientOAuthFlow) MarkApproved() error
Marks the flow approved unless it already failed
func (*ClientOAuthFlow) MarkError ¶
func (f *ClientOAuthFlow) MarkError(errText string, cancelled bool)
Fails the flow keeping the first cause, waking both waiters, a cancellation always recorded
func (*ClientOAuthFlow) MarkWorkerDone ¶
func (f *ClientOAuthFlow) MarkWorkerDone()
Records that the worker driving the flow returned
func (*ClientOAuthFlow) PublishAuthorizationURL ¶
func (f *ClientOAuthFlow) PublishAuthorizationURL(_ context.Context, rawURL string) error
Records the authorization URL and its state, re-minting an ended attempt unless the user cancelled
func (*ClientOAuthFlow) Snapshot ¶
func (f *ClientOAuthFlow) Snapshot() map[string]any
Flow id, server, status, authorization URL and error, never the authorization code or state
func (*ClientOAuthFlow) Status ¶
func (f *ClientOAuthFlow) Status() string
Status of the flow, one of starting, authorization_required, approved or error
func (*ClientOAuthFlow) WaitForAuthorizationURL ¶
func (f *ClientOAuthFlow) WaitForAuthorizationURL(ctx context.Context, timeout time.Duration) (string, error)
Authorization URL once published, failing on timeout or when the flow ended without one
func (*ClientOAuthFlow) WaitForCallback ¶
func (f *ClientOAuthFlow) WaitForCallback(ctx context.Context, timeout time.Duration) (code, state, iss string, err error)
Code, state and iss of the delivered callback, failing on timeout, a callback error or a codeless end
func (*ClientOAuthFlow) WorkerDone ¶
func (f *ClientOAuthFlow) WorkerDone() bool
Reports whether the worker driving the flow returned
type ClientOAuthTimeoutError ¶
type ClientOAuthTimeoutError struct{ Msg string }
Wait for the authorization URL or the callback that ran out of time
func (*ClientOAuthTimeoutError) Error ¶
func (e *ClientOAuthTimeoutError) Error() string
type ClientOAuthValueError ¶
type ClientOAuthValueError struct{ Msg string }
Rejected authorization URL or browser callback, a client error for the relaying client
func (*ClientOAuthValueError) Error ¶
func (e *ClientOAuthValueError) Error() string
type ConnectorAttempt ¶
type ConnectorAttempt interface {
AuthURL() string
Detail() string
Poll() AttemptPoll
Flow() *ClientOAuthFlow
}
ConnectorAttempt is one OAuth flow in flight as the watcher reads it
type ConnectorBackend ¶
type ConnectorBackend interface {
RequiredEnv(ctx context.Context, name string) ([]*pyjson.Object, error)
StartOAuth(ctx context.Context, name string) (ConnectorAttempt, error)
InstallsWithOAuth(ctx context.Context, name string) (bool, error)
StartInstallOAuth(ctx context.Context, name string, env *pyjson.Object) (ConnectorAttempt, error)
Install(ctx context.Context, name string, env *pyjson.Object) ([]string, error)
Enable(ctx context.Context, name string) error
}
ConnectorBackend is the work behind an MCP target, the catalog, the installer and the OAuth flow
type ContentBlock ¶
type ContentBlock struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
URI string `json:"uri,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Size *int64 `json:"size,omitempty"`
Resource *ResourceContents `json:"resource,omitempty"`
Meta map[string]any `json:"_meta,omitempty"`
}
ContentBlock is one element of a tool result or prompt message content list
type CostPolicy ¶
CostPolicy is one server's declared tool costs, its per chat spend limit and the unit both count in
func ConfigCostPolicy ¶
func ConfigCostPolicy(serverName string, cfg map[string]any) (*CostPolicy, error)
Policy of a native or translated mcp_servers entry, an error when malformed
func ParseCostPolicy ¶
func ParseCostPolicy(costs, spendLimit, costUnit any, where string) (*CostPolicy, error)
One server's validated cost declaration, nil when it declares no cost, an error naming the bad key otherwise
type CreateMessageParams ¶
type CreateMessageParams struct {
Messages []SamplingMessage `json:"messages"`
ModelPreferences *ModelPreferences `json:"modelPreferences,omitempty"`
SystemPrompt string `json:"systemPrompt,omitempty"`
IncludeContext string `json:"includeContext,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens int `json:"maxTokens"`
StopSequences []string `json:"stopSequences,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Tools []SamplingTool `json:"tools,omitempty"`
ToolChoice map[string]any `json:"toolChoice,omitempty"`
}
CreateMessageParams is sampling/createMessage
type CredentialStamp ¶
type CredentialStamp [2]*fileStamp
CredentialStamp is the stat of the token and client files any reauthorization rewrites
func (CredentialStamp) Equal ¶
func (c CredentialStamp) Equal(o CredentialStamp) bool
Reports whether two stamps describe the same files
type DiscoveryPass ¶
One discovery pass connecting the allowed servers and returning the MCP tool names
func SwapDiscoveryPass ¶
func SwapDiscoveryPass(pass DiscoveryPass) DiscoveryPass
Replaces the pass background discovery runs and returns the pass it replaced
type ElicitParams ¶
type ElicitParams struct {
Message string `json:"message"`
RequestedSchema map[string]any `json:"requestedSchema,omitempty"`
Mode string `json:"mode,omitempty"`
URL string `json:"url,omitempty"`
ElicitationID string `json:"elicitationId,omitempty"`
// Raw requestedSchema bytes so the consent summary follows the server's property order
RawRequestedSchema json.RawMessage `json:"-"`
}
ElicitParams is elicitation/create
func (*ElicitParams) UnmarshalJSON ¶
func (p *ElicitParams) UnmarshalJSON(data []byte) error
Decodes the params and keeps the requestedSchema bytes as sent
type ElicitResult ¶
type ElicitResult struct {
Action string `json:"action"`
Content map[string]any `json:"content,omitzero"`
}
ElicitResult is the answer to elicitation/create
type Elicitor ¶
type Elicitor interface {
Capabilities() map[string]any
Elicit(ctx context.Context, params *ElicitParams) (*ElicitResult, *RPCError)
}
Elicitor answers a server's elicitation/create requests
type EnvVarSpec ¶
type FieldError ¶
type FieldError struct {
Loc, Msg, Type string
}
FieldError is one failing field of a model validation
type GetPromptResult ¶
type GetPromptResult struct {
Description string `json:"description,omitempty"`
Messages []*PromptMessage `json:"messages"`
}
GetPromptResult is the answer to prompts/get
type HTTPOptions ¶
type HTTPOptions struct {
URL string
Headers map[string]string
ConfiguredHeaderNames map[string]bool
StrictRedirectHeaders bool
SSLVerify any
ClientCert any
ClientKey any
ConnectTimeout time.Duration
ReadTimeout time.Duration
Auth Authenticator
ServerName string
}
HTTPOptions tune one owned HTTP client
type HTTPRejection ¶
HTTPRejection remembers the last 4xx or 5xx an owned client saw
func (*HTTPRejection) Describe ¶
func (r *HTTPRejection) Describe() string
Describe renders the rejection the way connect errors quote it
type HTTPStatusError ¶
HTTPStatusError is a non 2xx answer the server gave to a transport request
func (*HTTPStatusError) Error ¶
func (e *HTTPStatusError) Error() string
Error renders the status in the SDK's opaque wording plus the recorded detail
type Implementation ¶
type Implementation struct {
Name string `json:"name"`
Version string `json:"version"`
Title string `json:"title,omitempty"`
}
Implementation names one side of the connection
type InitializeParams ¶
type InitializeParams struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities ClientCapabilities `json:"capabilities"`
ClientInfo Implementation `json:"clientInfo"`
}
InitializeParams is the initialize request body
type InitializeResult ¶
type InitializeResult struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities *ServerCapabilities `json:"capabilities"`
ServerInfo Implementation `json:"serverInfo"`
Instructions string `json:"instructions,omitempty"`
}
InitializeResult is the handshake answer, also the shape server/discover returns
type InvalidMCPURLError ¶
type InvalidMCPURLError struct{ Msg string }
InvalidMCPURLError is a remote server url that is not a parseable http or https URL
func (*InvalidMCPURLError) Error ¶
func (e *InvalidMCPURLError) Error() string
type LateConnectionAgent ¶
type LateConnectionAgent interface {
SessionID() string
EnabledToolsets() []string
DisabledToolsets() []string
SetToolsets(enabled, disabled []string)
ToolEnv() *tools.Env
}
LateConnectionAgent is the agent view adopt late connections reads and updates
type LiveEndpointUnavailableError ¶
LiveEndpointUnavailableError is a declared runtime file without a usable live endpoint, a connection error
func (*LiveEndpointUnavailableError) Error ¶
func (e *LiveEndpointUnavailableError) Error() string
type Liveness ¶
Liveness is one portable plugin liveness declaration, kind static, server_json or interactive_session
func ParseLiveness ¶
Errors when a liveness declaration does not follow the portable plugin contract
func (Liveness) AppDefinition ¶
func (l Liveness) AppDefinition(def AppDefinition) AppDefinition
Definition with the runtime file liveness keys applied, unchanged for other kinds
type LivenessStatus ¶
type LivenessStatus struct {
State string
Availability AppAvailability
Liveness Liveness
UserAction string
Retry string
}
LivenessStatus is the current unavailable state of a declared server with its one user action
type LockCookie ¶
type LockCookie struct {
// contains filtered or unexported fields
}
LockCookie holds the cross process discovery lock until released
func (*LockCookie) Release ¶
func (c *LockCookie) Release()
Drops the lock, an unlock or close failure never propagating
type LoggingMessageParams ¶
type LoggingMessageParams struct {
Level string `json:"level"`
Logger string `json:"logger,omitempty"`
Data json.RawMessage `json:"data"`
}
LoggingMessageParams is notifications/message
type LoopTimeoutError ¶
LoopTimeoutError is a loop call that outlived its configured timeout
func (*LoopTimeoutError) Error ¶
func (e *LoopTimeoutError) Error() string
func (*LoopTimeoutError) Timeout ¶
func (e *LoopTimeoutError) Timeout() bool
Marks the error as a timeout for callers that test for one
type MCPArgs ¶
type MCPArgs struct {
Action, Name, URL, Command, Auth, Preset, Flow, Identifier string
Args, Env []string
ConnectTimeout *float64
All bool
}
MCPArgs carries the parsed icebath mcp flags, a nil ConnectTimeout is an absent flag
type Message ¶
type Message struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *RPCError `json:"error,omitempty"`
}
Message is one JSON-RPC 2.0 request, notification, or response on the wire
func DecodeMessages ¶
DecodeMessages parses one JSON document that is a single message or a batch
func NewErrorResponse ¶
func NewErrorResponse(id json.RawMessage, code int, message string) *Message
NewErrorResponse builds an error response for the given id
func NewNotification ¶
NewNotification builds a notification message
func NewRequest ¶
NewRequest builds a request message with a fresh id
func NewResponse ¶
func NewResponse(id json.RawMessage, result any) (*Message, error)
NewResponse builds a success response for the given id
func (*Message) IsNotification ¶
IsNotification reports whether the message carries a method without an id
func (*Message) IsResponse ¶
IsResponse reports whether the message answers a request
type ModelHint ¶
type ModelHint struct {
Name string `json:"name,omitempty"`
}
ModelHint names a preferred model in a sampling request
type ModelPreferences ¶
type ModelPreferences struct {
Hints []ModelHint `json:"hints,omitempty"`
CostPriority *float64 `json:"costPriority,omitempty"`
SpeedPriority *float64 `json:"speedPriority,omitempty"`
IntelligencePriority *float64 `json:"intelligencePriority,omitempty"`
}
ModelPreferences carries the server's model wishes in a sampling request
type NodeABIMismatchError ¶
type NodeABIMismatchError struct{ Msg string }
NodeABIMismatchError is a native addon that does not load under the managed Node, every retry loads the same binary
func (*NodeABIMismatchError) Error ¶
func (e *NodeABIMismatchError) Error() string
type NonMCPEndpointError ¶
type NonMCPEndpointError struct{ Msg string }
NonMCPEndpointError is a 2xx answer with a non MCP content type, retrying always gets the same page
func (*NonMCPEndpointError) Error ¶
func (e *NonMCPEndpointError) Error() string
type OAuthAttempt ¶
type OAuthAttempt struct {
// contains filtered or unexported fields
}
OAuthAttempt is one card flow in flight, its URL, callback bridge and outcome
func StartCardOAuth ¶
func StartCardOAuth(ctx context.Context, env *tools.Env, serverName string, o CardOAuthOptions) (*OAuthAttempt, error)
Starts a card OAuth flow and waits until its authorization URL is published
func (*OAuthAttempt) AuthURL ¶
func (a *OAuthAttempt) AuthURL() string
func (*OAuthAttempt) Detail ¶
func (a *OAuthAttempt) Detail() string
func (*OAuthAttempt) Flow ¶
func (a *OAuthAttempt) Flow() *ClientOAuthFlow
func (*OAuthAttempt) Poll ¶
func (a *OAuthAttempt) Poll() AttemptPoll
The flow's status with its tools and discovery error once approved
type OAuthClientInfo ¶
type OAuthClientInfo struct {
RedirectURIs []string
HasRedirectURIs bool
TokenEndpointAuthMethod *string
GrantTypes []string
ApplicationType *string
ClientID string
ClientSecret *string
ClientIDIssuedAt *int64
ClientSecretExpiresAt *int64
Issuer *string
// contains filtered or unexported fields
}
OAuthClientInfo is the authorization server's record of a registered client
type OAuthClientMetadata ¶
type OAuthClientMetadata struct {
RedirectURIs []string
TokenEndpointAuthMethod *string
GrantTypes []string
ApplicationType string
// contains filtered or unexported fields
}
OAuthClientMetadata is the dynamic client registration request this client sends
type OAuthFlowError ¶
type OAuthFlowError struct{ Msg string }
OAuthFlowError is a failure of the OAuth client flow
func (*OAuthFlowError) Error ¶
func (e *OAuthFlowError) Error() string
type OAuthManager ¶
type OAuthManager struct {
// contains filtered or unexported fields
}
OAuthManager caches one provider per home and server, reloads tokens changed on disk and dedupes 401 recoveries
type OAuthMetadata ¶
type OAuthMetadata struct {
Issuer string
AuthorizationEndpoint *string
TokenEndpoint string
RegistrationEndpoint *string
ScopesSupported []string
HasScopesSupported bool
ResponseTypesSupported []string
ResponseModesSupported []string
GrantTypesSupported []string
TokenEndpointAuthMethodsSupported []string
TokenEndpointAuthSigningAlgValuesSupported []string
ServiceDocumentation *string
UILocalesSupported []string
OpPolicyURI *string
OpTosURI *string
RevocationEndpoint *string
RevocationEndpointAuthMethodsSupported []string
RevocationEndpointAuthSigningAlgValuesSupported []string
IntrospectionEndpoint *string
IntrospectionEndpointAuthMethodsSupported []string
IntrospectionEndpointAuthSigningAlgValuesSupported []string
CodeChallengeMethodsSupported []string
ClientIDMetadataDocumentSupported *bool
AuthorizationResponseIssParameterSupported *bool
AuthorizationGrantProfilesSupported []string
DeviceAuthorizationEndpoint *string
// contains filtered or unexported fields
}
OAuthMetadata is RFC 8414 authorization server metadata, with the RFC 8628 device endpoint when advertised
func (*OAuthMetadata) IsDevice ¶
func (md *OAuthMetadata) IsDevice() bool
Reports whether the metadata is the device authorization variant
type OAuthNonInteractiveError ¶
type OAuthNonInteractiveError struct{ Msg string }
OAuthNonInteractiveError reports an OAuth step that needs a person no session can reach
func (*OAuthNonInteractiveError) Error ¶
func (e *OAuthNonInteractiveError) Error() string
type OAuthProvider ¶
type OAuthProvider struct {
// contains filtered or unexported fields
}
OAuthProvider authenticates MCP requests with OAuth 2.1, discovering, registering, authorizing and refreshing itself
func (*OAuthProvider) ClientMetadata ¶
func (p *OAuthProvider) ClientMetadata() *OAuthClientMetadata
Registration metadata the provider sends, its scope updated by discovery
func (*OAuthProvider) CurrentTokens ¶
func (p *OAuthProvider) CurrentTokens() *OAuthToken
Tokens currently held in memory, nil when none
func (*OAuthProvider) HandleUnauthorized ¶
func (p *OAuthProvider) HandleUnauthorized(ctx context.Context, req *http.Request, resp *http.Response) (bool, error)
HandleUnauthorized runs discovery, registration and authorization on a 401 or scope step up, true to retry
func (*OAuthProvider) Prepare ¶
Prepare loads state, refreshes an expired token under the fence and adds the bearer header
func (*OAuthProvider) Storage ¶
func (p *OAuthProvider) Storage() *TokenStorage
Storage the provider persists into
type OAuthRegistrationError ¶
type OAuthRegistrationError struct{ Msg string }
OAuthRegistrationError is a failed client registration, a kind of flow error
func (*OAuthRegistrationError) As ¶
func (e *OAuthRegistrationError) As(target any) bool
Lets errors.As match a registration failure as a flow error
func (*OAuthRegistrationError) Error ¶
func (e *OAuthRegistrationError) Error() string
type OAuthToken ¶
type OAuthToken struct {
AccessToken string
TokenType string
ExpiresIn *int64
Scope *string
RefreshToken *string
}
OAuthToken is the RFC 6749 token response the client stores
type OAuthTokenError ¶
type OAuthTokenError struct{ Msg string }
OAuthTokenError is a failed token exchange or refresh, a kind of flow error
func (*OAuthTokenError) As ¶
func (e *OAuthTokenError) As(target any) bool
Lets errors.As match a token failure as a flow error
func (*OAuthTokenError) Error ¶
func (e *OAuthTokenError) Error() string
type OAuthWorkerOptions ¶
type OAuthWorkerOptions struct {
Flow *ClientOAuthFlow
OnDone func()
Env *pyjson.Object
OnCommit func(context.Context) error
ReuseSaved bool
}
OAuthWorkerOptions carries the flow, completion hook, setup values and saved token rule of one worker
type PickerRow ¶
type PickerRow struct {
Name string
Description string
Status string
Entry *CatalogEntry
}
Picker row, Entry set for catalog rows and nil for custom servers
func BuildPickerRows ¶
Catalog rows with install status followed by custom configured servers sorted by name
type ProbeDetails ¶
type ProbeDetails struct {
Initialized bool
SchemaChars map[string]int
Prompts *int
Resources *int
}
ProbeDetails is the display extra of one probe, nil counts mean the list was not fetched
type ProbeError ¶
ProbeError is a redacted probe failure tagged with its extension install failure class
func (*ProbeError) Error ¶
func (e *ProbeError) Error() string
func (*ProbeError) FailureClass ¶
func (e *ProbeError) FailureClass() string
func (*ProbeError) Unwrap ¶
func (e *ProbeError) Unwrap() error
type ProgressFunc ¶
ProgressFunc receives one progress update of a running call
type ProgressParams ¶
type ProgressParams struct {
ProgressToken json.RawMessage `json:"progressToken"`
Progress float64 `json:"progress"`
Total *float64 `json:"total,omitempty"`
Message string `json:"message,omitempty"`
}
ProgressParams is notifications/progress
type Prompt ¶
type Prompt struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Arguments []*PromptArgument `json:"arguments,omitempty"`
}
Prompt is one entry of prompts/list
type PromptArgument ¶
type PromptArgument struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Required *bool `json:"required,omitempty"`
}
PromptArgument describes one prompt parameter
type PromptMessage ¶
type PromptMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
}
PromptMessage is one message of prompts/get
type ProtectedResourceMetadata ¶
type ProtectedResourceMetadata struct {
Resource string
AuthorizationServers []string
ScopesSupported []string
HasScopesSupported bool
}
ProtectedResourceMetadata is RFC 9728 protected resource metadata
type RPCError ¶
type RPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data json.RawMessage `json:"data,omitempty"`
}
RPCError is the error member of a JSON-RPC response
type ReadResourceResult ¶
type ReadResourceResult struct {
Contents []*ResourceContents `json:"contents"`
}
ReadResourceResult is the answer to resources/read
type ReconcileResult ¶
type ReconcileResult struct {
Removed []string `json:"removed"`
Added []string `json:"added"`
Pending []string `json:"pending"`
}
ReconcileResult names the servers a reconcile tore down, connected and could not yet tear down
type RefreshFenceTimeout ¶
type RefreshFenceTimeout struct{ Msg string }
RefreshFenceTimeout aborts a refresh whose single use token this process cannot prove it owns
func (*RefreshFenceTimeout) Error ¶
func (e *RefreshFenceTimeout) Error() string
type RefreshOptions ¶
type RefreshOptions struct {
EnabledOverride []string
DisabledOverride []string
Quiet bool
ContentAware bool
PreservePrefix bool
}
RefreshOptions selects the toolset overrides and rebuild mode of one snapshot refresh, a nil override meaning none
type Rendered ¶
Rendered is one server entry after reference rendering with how each templated string resolved
type Resource ¶
type Resource struct {
URI string `json:"uri"`
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Size *int64 `json:"size,omitempty"`
}
Resource is one entry of resources/list
type ResourceContents ¶
type ResourceContents struct {
URI string `json:"uri"`
MimeType string `json:"mimeType,omitempty"`
Text *string `json:"text,omitempty"`
Blob *string `json:"blob,omitempty"`
}
ResourceContents is the payload of an embedded resource or a resources/read entry
type RuntimeError ¶
type RuntimeError struct{ Msg string }
RuntimeError is a call aborted by a deliberate reconnect teardown, retryable or outcome uncertain by its text
func (*RuntimeError) Error ¶
func (e *RuntimeError) Error() string
type SSEReader ¶
type SSEReader struct {
// contains filtered or unexported fields
}
SSEReader parses a text/event-stream body one event at a time under a per event byte cap
func NewSSEReader ¶
NewSSEReader wraps a stream body, capping each event at limit bytes
type SSETransport ¶
type SSETransport struct {
// contains filtered or unexported fields
}
SSETransport speaks the 2024-11-05 HTTP with SSE transport, a GET stream plus POSTs to the announced endpoint
func StartSSE ¶
func StartSSE(ctx context.Context, opts HTTPOptions, connectTimeout time.Duration) (*SSETransport, error)
StartSSE opens the event stream and waits for the endpoint announcement within connectTimeout
func (*SSETransport) Close ¶
func (t *SSETransport) Close() error
Close ends the stream and releases the client
func (*SSETransport) Err ¶
func (t *SSETransport) Err() error
Err returns the terminal transport error
func (*SSETransport) Receive ¶
func (t *SSETransport) Receive() <-chan *Message
Receive returns the inbound message channel
func (*SSETransport) Rejection ¶
func (t *SSETransport) Rejection() HTTPRejection
Rejection returns the last 4xx or 5xx the owned client saw
type Sampler ¶
type Sampler interface {
Capabilities() map[string]any
CreateMessage(ctx context.Context, params *CreateMessageParams) (any, *RPCError)
}
Sampler answers a server's sampling/createMessage requests
type SamplingMessage ¶
type SamplingMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
}
SamplingMessage is one conversation message of sampling/createMessage
type SamplingTool ¶
type SamplingTool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
InputSchema *pyjson.Object `json:"inputSchema"`
}
SamplingTool is one tool the server offers the sampled model
type ServerCapabilities ¶
type ServerCapabilities struct {
Tools map[string]any `json:"tools,omitempty"`
Resources map[string]any `json:"resources,omitempty"`
Prompts map[string]any `json:"prompts,omitempty"`
Logging map[string]any `json:"logging,omitempty"`
Completions map[string]any `json:"completions,omitempty"`
Experimental map[string]any `json:"experimental,omitempty"`
}
ServerCapabilities is the capabilities object of InitializeResult, nil members mean unsupported
func (*ServerCapabilities) Has ¶
func (c *ServerCapabilities) Has(family string) bool
Has reports whether the named capability family is advertised
type ServerConfig ¶
type ServerConfig struct {
Name string
Raw map[string]any
Command string
Args []string
Env map[string]any
Cwd string
URL string
Headers map[string]string
Transport string
Enabled bool
ToolTimeout float64
ConnectTimeout float64
KeepaliveInterval float64
Lazy bool
IdleTimeout float64
MaxLifetime float64
ToolsInclude map[string]bool
ToolsExclude map[string]bool
Resources bool
Prompts bool
Trust string
Costs *CostPolicy
Auth string
OAuth map[string]any
Sampling map[string]any
Elicitation map[string]any
Events bool
Protocol string
SkipPreflight bool
SSLVerify any
ClientCert any
ClientKey any
StrictRedirectHeaders bool
IdentityHeader any
SupportsParallelToolCalls bool
}
ServerConfig is the typed view of one rendered mcp_servers entry
type ServerKey ¶
ServerKey is a connection key, the bare name outside a multiplexer and the owning scope with the name under one
type ServerStatus ¶
type ServerStatus struct {
Name string `json:"name"`
Transport string `json:"transport"`
Tools int `json:"tools"`
Connected bool `json:"connected"`
Disabled bool `json:"disabled"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
Sampling map[string]any `json:"sampling,omitempty"`
}
ServerStatus is one configured server's state for banners and the TUI
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is one JSON-RPC client session over a transport, the ClientSession of the server task
func NewSession ¶
func NewSession(t Transport, opts SessionOptions) *Session
Starts a session reading the transport's inbound messages
func (*Session) CallTool ¶
func (s *Session) CallTool(ctx context.Context, name string, args map[string]any, progress ProgressFunc) (*CallToolResult, error)
Calls a tool, opting into notifications/progress with the request id as token, a browser step the user refused or left unfinished answering as a tool error
func (*Session) CompleteHandshakeAtOfferedVersion ¶
func (s *Session) CompleteHandshakeAtOfferedVersion(ctx context.Context) (*InitializeResult, error)
Reruns initialize and adopts its result pinned to the offered revision, then sends notifications/initialized
func (*Session) Discover ¶
func (s *Session) Discover(ctx context.Context) (*InitializeResult, error)
Stateless server/discover probe adopting the capabilities and revision it names
func (*Session) Done ¶
func (s *Session) Done() <-chan struct{}
Channel closed once the transport ended and every pending request failed
func (*Session) GetPrompt ¶
func (s *Session) GetPrompt(ctx context.Context, name string, args map[string]string) (*GetPromptResult, error)
Messages of one prompt rendered with its arguments
func (*Session) Initialize ¶
func (s *Session) Initialize(ctx context.Context) (*InitializeResult, error)
Legacy handshake, refusing a server revision outside the supported set, then notifications/initialized
func (*Session) InitializeResult ¶
func (s *Session) InitializeResult() *InitializeResult
Handshake or discovery result the session adopted, nil before negotiation
func (*Session) ListPrompts ¶
Every prompt the server lists across pages
func (*Session) ListResources ¶
Every resource the server lists across pages
func (*Session) ListTools ¶
Every tool the server lists across pages, the first page's cache hints in hints when given
func (*Session) Negotiate ¶
func (s *Session) Negotiate(ctx context.Context, mode string, connectTimeout time.Duration) (*InitializeResult, error)
Negotiates this session per the configured protocol mode under the connect timeout
func (*Session) ProtocolVersion ¶
Protocol revision later requests are shaped for
func (*Session) ReadResource ¶
Contents of one resource
type SessionOptions ¶
type SessionOptions struct {
Name string
Env *tools.Env
Sampler Sampler
Elicitor Elicitor
OnToolsListChanged func()
}
SessionOptions configure one client session
type StdioParams ¶
type StdioParams struct {
Command string
Args []string
Env map[string]string
Cwd string
// Stderr receives the child's stderr, nil discards it
Stderr io.Writer
}
StdioParams describe the child process a stdio transport spawns
type StdioTransport ¶
type StdioTransport struct {
// contains filtered or unexported fields
}
StdioTransport runs an MCP server as a child process speaking newline framed JSON-RPC
func StartStdio ¶
func StartStdio(ctx context.Context, p StdioParams) (*StdioTransport, error)
StartStdio spawns the child and begins pumping its stdout into messages
func (*StdioTransport) Alive ¶
func (t *StdioTransport) Alive() bool
Alive reports whether the child process is still running
func (*StdioTransport) Close ¶
func (t *StdioTransport) Close() error
Close ends stdin, waits briefly for a clean exit, then terminates the whole process group
func (*StdioTransport) Err ¶
func (t *StdioTransport) Err() error
Err returns the terminal transport error
func (*StdioTransport) Exited ¶
func (t *StdioTransport) Exited() <-chan struct{}
Exited returns a channel closed once the child has been reaped
func (*StdioTransport) PGID ¶
func (t *StdioTransport) PGID() int
PGID returns the child's process group id, zero when groups are unsupported
func (*StdioTransport) Receive ¶
func (t *StdioTransport) Receive() <-chan *Message
Receive returns the inbound message channel
type StreamableHTTPTransport ¶
type StreamableHTTPTransport struct {
// contains filtered or unexported fields
}
StreamableHTTPTransport speaks the Streamable HTTP transport with session ids and SSE answers
func StartStreamableHTTP ¶
func StartStreamableHTTP(opts HTTPOptions) (*StreamableHTTPTransport, error)
StartStreamableHTTP builds the transport, no request is sent until the first Send
func (*StreamableHTTPTransport) Close ¶
func (t *StreamableHTTPTransport) Close() error
Close deletes the session, stops every stream and closes the receive channel
func (*StreamableHTTPTransport) Err ¶
func (t *StreamableHTTPTransport) Err() error
Err returns the terminal transport error
func (*StreamableHTTPTransport) Label ¶
func (t *StreamableHTTPTransport) Label() string
Label names the transport
func (*StreamableHTTPTransport) OpenStandaloneStream ¶
func (t *StreamableHTTPTransport) OpenStandaloneStream(ctx context.Context)
OpenStandaloneStream starts the optional GET event stream for server initiated messages
func (*StreamableHTTPTransport) Receive ¶
func (t *StreamableHTTPTransport) Receive() <-chan *Message
Receive returns the inbound message channel
func (*StreamableHTTPTransport) Rejection ¶
func (t *StreamableHTTPTransport) Rejection() HTTPRejection
Rejection returns the last 4xx or 5xx the owned client saw this connection
func (*StreamableHTTPTransport) Send ¶
func (t *StreamableHTTPTransport) Send(ctx context.Context, msg *Message) error
Send posts one message, delivering any JSON or SSE answer onto the receive channel
func (*StreamableHTTPTransport) SessionID ¶
func (t *StreamableHTTPTransport) SessionID() string
SessionID returns the server assigned session id, empty when the server is stateless
func (*StreamableHTTPTransport) SetProtocolVersion ¶
func (t *StreamableHTTPTransport) SetProtocolVersion(v string)
SetProtocolVersion pins the MCP-Protocol-Version header for every later request
type TerminalUI ¶
type TerminalUI interface {
Out() io.Writer
Color(text string, codes ...string) string
Prompt(question, def string, password bool) string
YesNo(question string, def bool) bool
Checklist(title string, items []string, selected, cancelReturns map[int]bool) map[int]bool
SingleSelect(title string, items []string) (int, bool)
Interactive() bool
}
Terminal surface for catalog, picker and tools commands, implemented by the cli_output and curses_ui port
type TimeoutError ¶
type TimeoutError struct{}
TimeoutError is a connect that outlived its connect_timeout, reported by class name like the bare Python exception
func (*TimeoutError) Error ¶
func (*TimeoutError) Error() string
func (*TimeoutError) Timeout ¶
func (*TimeoutError) Timeout() bool
Marks the error as a timeout for callers that test for one
type TokenStorage ¶
type TokenStorage struct {
// contains filtered or unexported fields
}
TokenStorage persists one server's OAuth tokens, client record, metadata and CIMD refusal marker
func NewTokenStorage ¶
func NewTokenStorage(ctx context.Context, serverName, homeDir string) *TokenStorage
Storage for a server under homeDir, the context's home when homeDir is empty
func (*TokenStorage) BindIssuer ¶
func (s *TokenStorage) BindIssuer(issuer string)
Sets the issuer stamped on future token writes, empty clearing it
func (*TokenStorage) CIMDRejected ¶
func (s *TokenStorage) CIMDRejected() bool
Reports whether this server refused the CIMD document before
func (*TokenStorage) CIMDRejectedPath ¶
func (s *TokenStorage) CIMDRejectedPath() string
CIMD refusal marker path
func (*TokenStorage) ClientInfoPath ¶
func (s *TokenStorage) ClientInfoPath() string
Client registration file path
func (*TokenStorage) CredentialStamp ¶
func (s *TokenStorage) CredentialStamp() CredentialStamp
Stat of the token and client files without reading their bytes
func (*TokenStorage) GetClientInfo ¶
func (s *TokenStorage) GetClientInfo(ctx context.Context) (*OAuthClientInfo, error)
Stored client registration, persisting a coerced auth method so later flows skip the coercion
func (*TokenStorage) GetTokens ¶
func (s *TokenStorage) GetTokens() (*OAuthToken, error)
Stored tokens with expiry rebased and the issuer record popped, nil when absent or corrupt
func (*TokenStorage) HasCachedTokens ¶
func (s *TokenStorage) HasCachedTokens() bool
Reports whether a token file exists, expired or not
func (*TokenStorage) HomeDir ¶
func (s *TokenStorage) HomeDir() string
Home directory the storage lives under
func (*TokenStorage) LoadOAuthMetadata ¶
func (s *TokenStorage) LoadOAuthMetadata() *OAuthMetadata
Stored server metadata, the device variant when it names a device endpoint, nil when absent or corrupt
func (*TokenStorage) LoadedIssuer ¶
func (s *TokenStorage) LoadedIssuer() string
Issuer the token file recorded at the last load, empty when none
func (*TokenStorage) MarkCIMDRejected ¶
func (s *TokenStorage) MarkCIMDRejected(ctx context.Context)
Durably records that this server refused the CIMD document
func (*TokenStorage) MetaPath ¶
func (s *TokenStorage) MetaPath() string
Authorization server metadata file path
func (*TokenStorage) PoisonClientRegistration ¶
func (s *TokenStorage) PoisonClientRegistration() bool
Discards a dead dynamic registration and stale metadata keeping one backup, true when a client file went
func (*TokenStorage) Remove ¶
func (s *TokenStorage) Remove(keepMetadata bool) error
Deletes the stored state, sparing the metadata when asked and always the refresh lock
func (*TokenStorage) Restore ¶
func (s *TokenStorage) Restore(ctx context.Context, snap map[string][]byte, onlyIfAbsent bool) error
Reverts to a snapshot, skipped when asked to keep newer state another writer produced
func (*TokenStorage) SaveOAuthMetadata ¶
func (s *TokenStorage) SaveOAuthMetadata(ctx context.Context, md *OAuthMetadata) error
Persists server metadata so a restarted process can refresh without rediscovery
func (*TokenStorage) ServerName ¶
func (s *TokenStorage) ServerName() string
Sanitized server name the files are keyed by
func (*TokenStorage) SetClientInfo ¶
func (s *TokenStorage) SetClientInfo(ctx context.Context, info *OAuthClientInfo) error
Persists the client registration with the secret auth method coercion applied
func (*TokenStorage) SetTokens ¶
func (s *TokenStorage) SetTokens(ctx context.Context, t *OAuthToken) error
Persists tokens with an absolute expiry and the bound issuer stamped
func (*TokenStorage) Snapshot ¶
func (s *TokenStorage) Snapshot() map[string][]byte
Bytes of the existing token, client and metadata files keyed by filename
func (*TokenStorage) StampIssuer ¶
func (s *TokenStorage) StampIssuer(ctx context.Context, issuer string)
Backfills the issuer onto a token file written before issuer binding existed
func (*TokenStorage) StripRefreshToken ¶
func (s *TokenStorage) StripRefreshToken(ctx context.Context)
Drops the refresh token and its issuer record from disk, keeping the access token
type Tool ¶
type Tool struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
InputSchema *pyjson.Object `json:"inputSchema"`
OutputSchema *pyjson.Object `json:"outputSchema,omitempty"`
Annotations *ToolAnnotations `json:"annotations,omitempty"`
Meta map[string]any `json:"_meta,omitempty"`
}
Tool is one entry of tools/list
type ToolAnnotations ¶
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 the behavioural hints a server attaches to a tool
type ToolPinStore ¶
ToolPinStore persists a session tools pin, nil pin clearing it
type ToolSummary ¶
ToolSummary is one probed tool's name and description
func ProbeSingleServer ¶
func ProbeSingleServer(ctx context.Context, env *tools.Env, name string, cfg map[string]any) ([]ToolSummary, error)
One server probe for callers outside the package
func ProbeSingleServerDetails ¶
func ProbeSingleServerDetails(ctx context.Context, env *tools.Env, name string, cfg map[string]any, details *ProbeDetails) ([]ToolSummary, error)
One server probe filling the prompt, resource and schema size details
type Transport ¶
type Transport interface {
// Send delivers one message to the server
Send(ctx context.Context, msg *Message) error
// Receive returns the channel of inbound messages, closed when the transport ends
Receive() <-chan *Message
// Err returns why the transport ended, nil while running or on a clean close
Err() error
// Close releases the connection and every child it owns
Close() error
// Label names the transport in diagnostics
Label() string
}
Transport moves JSON-RPC messages between the client and one server
type TransportSpec ¶
type URLElicitationError ¶
type URLElicitationError struct {
Server string
Method string
URLs []string
Outcome string
Wait time.Duration
}
URLElicitationError is a request held up by browser steps the user declined or has not finished in time
func (*URLElicitationError) Error ¶
func (e *URLElicitationError) Error() string
type UnsetReferenceError ¶
UnsetReferenceError is a remote entry whose url or headers still carry a literal reference
func (*UnsetReferenceError) Error ¶
func (e *UnsetReferenceError) Error() string
func (*UnsetReferenceError) FailureClass ¶
func (e *UnsetReferenceError) FailureClass() string
Failure class the status surfaces report for a missing credential
type UnsupportedServerVersionError ¶
type UnsupportedServerVersionError struct {
Version string
}
UnsupportedServerVersionError is an initialize answered with a revision outside the handshake set
func (*UnsupportedServerVersionError) Error ¶
func (e *UnsupportedServerVersionError) Error() string
type UtilitySchema ¶
UtilitySchema is one generated resource, prompt or event tool and the handler it dispatches to
type ValidationError ¶
type ValidationError struct {
Model string
Errors []FieldError
}
ValidationError lists the fields a model rejected without echoing their input
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) Fields ¶
func (e *ValidationError) Fields() string
Comma joined locations of every failing field
Source Files
¶
- access_unix.go
- agentsnapshot.go
- bridges.go
- catalog.go
- catalog_shell_unix.go
- cliconfig.go
- cliconfig_bearer_export.go
- cliconfig_servers_export.go
- client_oauth_flow.go
- config.go
- connectors_mcp.go
- connectors_mcp_oauth.go
- connectors_reissue.go
- content.go
- costs.go
- discovery.go
- discovery_run_export.go
- editor_session.go
- elicitation_form.go
- elicitation_url.go
- errors.go
- events.go
- handlers.go
- health.go
- httpclient.go
- jsonrpc.go
- kill_orphans_export.go
- lifecycle.go
- lifecycle_unix.go
- liveness.go
- log.go
- manager.go
- manager_scope_export.go
- media_cache_bridge.go
- nodeabi.go
- oauth.go
- oauth_callback.go
- oauth_cimd.go
- oauth_ctime_unix.go
- oauth_device.go
- oauth_flow.go
- oauth_inode_unix.go
- oauth_manager.go
- oauth_models.go
- oauth_sessions.go
- oauth_storage.go
- oauth_url.go
- picker.go
- plugin_connector.go
- plugin_servers_export.go
- probe_timeout.go
- proc_unix.go
- protocol.go
- proxy.go
- proxy_system_other.go
- registration.go
- reload_scope_export.go
- rpc_helpers_sources.go
- sampling.go
- schema.go
- schemacache.go
- security.go
- server.go
- server_transport.go
- session.go
- session_inputs.go
- startup.go
- startup_discovery_swap.go
- startup_export.go
- tlscert.go
- tools_config_mcp.go
- tools_config_mcp_export.go
- transport.go
- transport_http.go
- transport_sse.go
- transport_stdio.go
- tui_profile_scope.go
- tuiserver_export.go
- webhook_store_bridge.go