mcp

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 90 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mcp connects the configured Model Context Protocol servers and exposes their tools to the agent

Index

Constants

View Source
const (
	TrustFull      = "full"
	TrustUntrusted = "untrusted"
)

Trust tiers a server entry may declare

View Source
const (
	CodeParseError                 = -32700
	CodeInvalidRequest             = -32600
	CodeMethodNotFound             = -32601
	CodeInvalidParams              = -32602
	CodeInternalError              = -32603
	CodeUnsupportedProtocolVersion = -32022
)

JSON-RPC 2.0 error codes the client reasons about

View Source
const ClientName = "icebath-agent"

ClientName is the clientInfo name every server sees

View Source
const CodeURLElicitationRequired = -32042

CodeURLElicitationRequired is the 2025-11-25 error a request gets until a URL mode elicitation is finished

View Source
const DefaultCostUnit = "credits"

Unit label a cost table counts in when it names none

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

Newest revision the initialize handshake speaks and the MCP-Protocol-Version header is seeded from

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

Newest revision the client knows, reached through the stateless server/discover probe

View Source
const MaxHTTPBodyBytes = 10 * 1024 * 1024

Wire body cap applied before any JSON parse, per finite body and per SSE event

View Source
const NoTimeout time.Duration = -1

NoTimeout lets a loop call run until it finishes or is interrupted

View Source
const ToolNamePrefix = "mcp__"

ToolNamePrefix starts every native MCP tool name

Variables

View Source
var ClientVersion = "dev"

ClientVersion is the clientInfo version, set by the binary at startup

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

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

View Source
var ErrBodyTooLarge = errors.New("MCP response exceeds the wire body cap")

ErrBodyTooLarge marks a response or event over the wire cap

View Source
var ErrEditorSchemaChanged = errors.New("acp_mcp_schema_changed")

ErrEditorSchemaChanged is the state authority refusal when an editor session server changes its frozen manifest

View Source
var ErrInterrupted = errors.New("User sent a new message")

ErrInterrupted ends a loop call when the user sent a new message

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

View Source
var SupportedProtocolVersions = []string{"2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"}

Protocol revisions this client negotiates, newest handshake revision last

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

func ApplyAnswer(ctx context.Context, op *tools.ConnectionOperation, raw string) (err error)

Folds the card's answer into the operation, a skip, an approval that starts the work and Continue

func ApplyConnAnswer

func ApplyConnAnswer(ctx context.Context, op *tools.ConnectionOperation, raw string) error

Hands the card's answer to the catalog or MCP module running the operation

func ApplyMCPChange

func ApplyMCPChange(cfg config.Tree, targets []string, action string) map[string]bool

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

func ApplyOAuthProviderDefaults(cfg map[string]any, serverName, serverURL string) map[string]any

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

func BearerAuthHeaders(name string) map[string]any

Persisted Authorization header template naming the MCP_<NAME>_API_KEY env key

func BindRun

func BindRun(ctx context.Context, runID string) context.Context

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

func CancelOAuthFlow(ctx context.Context, sessionID, serverName, homeDir string) *jsonutil.Object

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

func ConfigFingerprint(cfg map[string]any) string

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

func Connect(ctx context.Context, env *tools.Env, servers map[string]*Rendered) ([]string, error)

Connect registers the tools of every enabled, not yet connected server, idempotent for connected names, and returns every MCP tool name

func ConnectAll

func ConnectAll(ctx context.Context, env *tools.Env, allowed []string) ([]string, error)

ConnectAll loads config and connects every configured server, or only the allowed names when allowed is non nil

func DisconnectScope

func DisconnectScope(ctx context.Context, scope string)

Closes every connection the editor scope owns and deregisters its tools

func DiscoveryInFlight

func DiscoveryInFlight(ctx context.Context) bool

Reports whether this home's discovery goroutine is still running

func DropEventState

func DropEventState(h, routeName string) error

Forgets the grant, cursor and URL recorded for a route

func EditorConnected

func EditorConnected(scope string, names map[int]string) []int

Indexes whose named connection under the editor scope has a live session, ascending

func EditorToolsDrifted

func EditorToolsDrifted(scope string, names []string, timeout time.Duration) bool

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

func EnvKeyForServer(name string) string

Env key holding the API key of a server, MCP_<NAME>_API_KEY

func FinishOAuthFlow

func FinishOAuthFlow(sessionID string)

Releases a finished flow's listener and keeps its relay visible outcome

func ForceInteractiveOAuth

func ForceInteractiveOAuth(ctx context.Context) context.Context

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

func GetCachedEntry(ctx context.Context, serverName, fingerprint string) map[string]any

Cached entry of a server when its fingerprint matches and its recorded TTL still holds

func HasConfiguredServers

func HasConfiguredServers(ctx context.Context) bool

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

func HumanizeOAuthRegistrationError(serverName, msg, serverURL string) (string, bool)

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

func InterpolateServerConfig(ctx context.Context, env *tools.Env, cfg map[string]any) (any, error)

Server config with every environment reference expanded the way the connect path renders it

func IsEnabled

func IsEnabled(ctx context.Context, name string) (bool, error)

True when the server block exists, is non empty and its enabled flag reads on

func IsInstalled

func IsInstalled(ctx context.Context, name string) (bool, error)

True when mcp_servers holds the name

func IsToolParallelSafe

func IsToolParallelSafe(ctx context.Context, toolName string) bool

IsToolParallelSafe reports whether the tool's registering server opted into parallel tool calls

func JoinDiscovery

func JoinDiscovery(ctx context.Context, timeout *time.Duration) bool

Waits up to timeout for this home's discovery, true once complete and false while it still runs

func KillOrphanedMCPChildren

func KillOrphanedMCPChildren(includeActive bool, serverName string)

Reaps orphaned MCP child processes the way the cron scheduler sweep asks for them

func LoadServerConfigs

func LoadServerConfigs(ctx context.Context, env *tools.Env) map[string]*Rendered

Every mcp_servers entry of the active profile rendered, suspicious and malformed ones dropped, empty in safe mode

func LoginConnectTimeout

func LoginConnectTimeout(serverConfig map[string]any) float64

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

func MCPCommand(ctx context.Context, env *tools.Env, ui CLIConfigUI, a MCPArgs) (int, error)

Dispatches one icebath mcp subcommand and returns the process exit code

func MatchesNameFilter

func MatchesNameFilter(toolName string, patterns map[string]bool) bool

Reports whether a tool name matches an exact entry or a case sensitive glob entry

func NewStderrTee

func NewStderrTee(log io.Writer) (*stderrTee, error)

Tee copying child stderr into log as stamped lines, the writer of mcp-stderr.log

func OAuthTokensPresent

func OAuthTokensPresent(ctx context.Context, name string) bool

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

func PinnedToolDefs(ctx context.Context, env *tools.Env, saved any) []map[string]any

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

func PollOAuthFlow(ctx context.Context, sessionID, serverName string) *jsonutil.Object

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

func PrefixedToolName(serverName, toolName string) string

Registry and wire name mcp__server__tool clamped to 64 characters with a stable hash suffix

func Probe

func Probe(ctx context.Context, env *tools.Env) map[string][]ToolSummary

Probe connects each enabled server, lists its tools and disconnects, registering nothing and omitting failed servers

func ProbeFailureClass

func ProbeFailureClass(err error) (class string)

Extension install failure class of a failed probe from its tag or error type, never its message

func RPCCode

func RPCCode(err error) int

RPCCode extracts the JSON-RPC error code carried anywhere in an error chain, zero when none

func ReconnectServer

func ReconnectServer(ctx context.Context, name string) bool

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

func RegisteredServerNames() map[string]bool

RegisteredServerNames lists the servers that registered at least one tool

func RegistryScope

func RegistryScope(ctx context.Context) string

Registry scope key of the MCP servers bound to the profile of ctx

func Reissue

func Reissue(ctx context.Context, op *tools.ConnectionOperation, names []string) (string, error)

Re-runs the named failed rows, the refusal key when the card retry cannot run

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

func RemoveOAuthTokens(ctx context.Context, serverName, homeDir string) error

Deletes every stored OAuth file of a server

func RemoveServer

func RemoveServer(ctx context.Context, name string) (bool, error)

Removes a server from config.yaml, 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

func Respond(ctx context.Context, op *tools.ConnectionOperation, raw string) (bool, error)

Applies the card's answer, settles once every row resolved and closes a settled operation

func Restart

func Restart(ctx context.Context, env *tools.Env, names []string) ([]string, error)

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

func RunPicker(ctx context.Context, env *tools.Env, ui TerminalUI) error

Interactive selector that re-renders after each action until cancelled, a text dump off a terminal

func SanitizeNameComponent

func SanitizeNameComponent(value string) string

Name component with every character outside letters digits and underscore replaced by underscore

func SaveBearerAuthToken

func SaveBearerAuthToken(ctx context.Context, name, token string) (map[string]any, error)

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

func ScopedServerNames(scope *string) map[string]bool

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

func ServerConnected(ctx context.Context, serverName string) bool

Whether the connection the current scope resolves for a server holds a session or was recycled on purpose

func ServerEnabled

func ServerEnabled(cfg map[string]any) bool

Reports whether a server entry is on, absent null or unparseable counting as on

func ServerReconnecting

func ServerReconnecting(ctx context.Context, name string) bool

ServerReconnecting reports whether this scope's connection was up once and is now healing from a transient outage

func ServerToolNames

func ServerToolNames(ctx context.Context, serverName string) []string

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

func ServersAwaitingConnect(ctx context.Context, env *tools.Env) []string

ServersAwaitingConnect lists enabled servers the next ConnectAll would connect

func ServersNotConnected

func ServersNotConnected(ctx context.Context, env *tools.Env) []string

ServersNotConnected lists enabled servers this scope does not serve after a reload, parked and failed ones included

func ServersReady

func ServersReady(ctx context.Context, env *tools.Env) []string

ServersReady lists enabled servers this scope serves now, live or lazily registered and not failed

func SetHomeDiscoveryRunForTests

func SetHomeDiscoveryRunForTests(ctx context.Context, done chan struct{}) func()

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

func SetServerFilter(toolsets any) []string

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

func ShutdownMCPServers(ctx context.Context, scope *string, names []string, timeout time.Duration)

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) (*jsonutil.Object, error)

Begins an RPC MCP OAuth flow and returns its session id and authorization URL once published

func StoreEventCursor

func StoreEventCursor(h, routeName, cursor string) error

Persists the newest replay cursor a delivery carried for a route that still exists

func StoredServers

func StoredServers(ctx context.Context) map[string]any

Server entries the profile's config.yaml holds, references unexpanded so an entry can be shown, edited and saved back as written

func StripBearerPrefix

func StripBearerPrefix(token string) string

Pasted token without a leading Bearer word and surrounding whitespace

func SuppressInteractiveOAuth

func SuppressInteractiveOAuth(ctx context.Context) context.Context

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

func ToolServerName(tool string) (string, bool)

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

func ToolsFromCacheEntry(entry map[string]any) []any

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

func UninstallEntry(ctx context.Context, name string, purgeInstallDir bool) (bool, error)

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

func UtilityToolsFromCacheEntry(entry map[string]any) []any

Cached schema and handler_key utility rows

func ValidateClientRedirectURI

func ValidateClientRedirectURI(uri string) (string, error)

Accepts only plain http loopback URLs and returns the normalized redirect

func ValidateMCPNames

func ValidateMCPNames(ctx context.Context, env *tools.Env, action string, names []string) string

The reason names do not fit action, install taking catalog entries and the rest configured servers

func ValidateServerEntry

func ValidateServerEntry(name string, entry map[string]any) []string

Security warnings for one server entry, empty when it is not one of the three blocked shapes

func WaitForDiscovery

func WaitForDiscovery(ctx context.Context, env *tools.Env, timeout *time.Duration, singleQuery bool)

Waits for the home's discovery up to the resolved bound

func WriteCacheEntry

func WriteCacheEntry(ctx context.Context, serverName, fingerprint string, tools, utilityTools []any, ttlMs *float64, cacheScope string) error

Persists a server's tool schemas after a live connect, the TTL hints anchored at the write time

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

type AppAvailability struct {
	State      string
	MinVersion string
	Version    string
	Path       string
}

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 AppProbe

type AppProbe struct {
	Running         *bool
	EndpointPresent bool
}

AppProbe is a local resolver probe, Running nil when unknown

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

type AttemptPoll struct {
	Status         string
	Error          string
	Tools          []string
	DiscoveryError string
}

AttemptPoll is an attempt's status with its tools and discovery error once approved

type AuthSpec

type AuthSpec struct {
	Type     string
	Env      []EnvVarSpec
	Provider any
	Scopes   []any
	EnvVar   any
	OAuth    map[string]any
}

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 reacts to a 401 or 403, true when the request should be retried
	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

type CacheHints struct {
	TTLMs      *float64
	CacheScope string
}

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 and _meta with keys in wire order and integers of any size kept exact integers

type CardOAuthOptions

type CardOAuthOptions struct {
	URLTimeout        time.Duration
	ClientRedirectURI *string
	Cfg               map[string]any
	Env               *jsonutil.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

type CatalogDiagnostic struct {
	Name    string
	Kind    string
	Message string
}

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(ctx context.Context, name string) (*CatalogEntry, error)

Catalog entry by name with an optional official/ prefix, nil when absent

func ListCatalog

func ListCatalog(ctx context.Context) ([]*CatalogEntry, error)

Every valid catalog entry sorted by name, recording skipped manifests for CatalogDiagnostics

type CatalogError

type CatalogError struct {
	Msg   string
	Class string
}

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

func (c *Charge) Book()

Books the estimate unconditionally

func (*Charge) CostSentence

func (c *Charge) CostSentence() string

Sentence naming the call's declared cost

func (*Charge) Lines

func (c *Charge) Lines(already float64) []string

Cost and spend sentences for the approval prompt, empty ones dropped

func (*Charge) OverLimit

func (c *Charge) OverLimit(already float64) bool

Reports whether this call would take the chat past its limit

func (*Charge) Refund

func (c *Charge) Refund()

Returns a booked estimate to the chat

func (*Charge) Refusal

func (c *Charge) Refusal(already float64) string

Tool result text for a call refused at the spend limit

func (*Charge) ReserveWithinLimit

func (c *Charge) ReserveWithinLimit() (bool, float64)

Books the estimate when it keeps the chat within its limit, returning whether it booked and the spend before

func (*Charge) SpendSentence

func (c *Charge) SpendSentence(already float64) string

Sentence naming the chat's spend so far or its limit, empty when neither applies

func (*Charge) Spent

func (c *Charge) Spent() float64

Spend the chat booked so far on this policy

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) ([]*jsonutil.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 *jsonutil.Object) (ConnectorAttempt, error)
	Install(ctx context.Context, name string, env *jsonutil.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

type CostPolicy struct {
	Costs map[string]ToolCost
	Limit float64
	Unit  string
}

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

Reports whether two stamps describe the same files

type DiscoveryPass

type DiscoveryPass func(ctx context.Context, env *tools.Env, allowed []string) ([]string, error)

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 EnvVarSpec struct {
	Name     string
	Prompt   string
	Required bool
	Secret   bool
	Default  string
}

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

type HTTPRejection struct {
	Status int
	Method string
	URL    string
	Body   string
}

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

type HTTPStatusError struct {
	Status int
	Method string
	URL    string
	Body   string
}

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 InstallSpec

type InstallSpec struct {
	Type      string
	URL       any
	Ref       any
	Bootstrap []string
}

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

type LiveEndpointUnavailableError struct{ Msg string }

LiveEndpointUnavailableError is a declared runtime file without a usable live endpoint, a connection error

func (*LiveEndpointUnavailableError) Error

type Liveness

type Liveness struct {
	Kind       string
	Path       string
	URLField   string
	TokenField string
	PIDField   string
}

Liveness is one portable plugin liveness declaration, kind static, server_json or interactive_session

func ParseLiveness

func ParseLiveness(raw any) (Liveness, error)

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

type LoopTimeoutError struct {
	Elapsed    time.Duration
	Configured time.Duration
}

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

func DecodeMessages(data []byte) ([]*Message, error)

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

func NewNotification(method string, params any) (*Message, error)

NewNotification builds a notification message

func NewRequest

func NewRequest(method string, params any) (*Message, error)

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

func (m *Message) IsNotification() bool

IsNotification reports whether the message carries a method without an id

func (*Message) IsRequest

func (m *Message) IsRequest() bool

IsRequest reports whether the message carries a method and an id

func (*Message) IsResponse

func (m *Message) IsResponse() bool

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

func (p *OAuthProvider) Prepare(ctx context.Context, req *http.Request) error

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

func BuildPickerRows(ctx context.Context) ([]PickerRow, error)

Catalog rows with install status followed by custom configured servers sorted by name

func (PickerRow) IsCustom

func (r PickerRow) IsCustom() bool

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

type ProbeError struct {
	Err   error
	Class string
}

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

type ProgressFunc func(progress float64, total *float64, message string)

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

func (*RPCError) Error

func (e *RPCError) Error() string

Error renders the code and message the way the Python SDK stringifies MCPError

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

func Reconcile

func Reconcile(ctx context.Context, env *tools.Env) (ReconcileResult, error)

Reconcile tears down this scope's servers removed or disabled in config and connects enabled ones not yet live

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

type Rendered struct {
	Config map[string]any
	// contains filtered or unexported fields
}

Rendered is one server entry after reference rendering with how each templated string resolved

func (*Rendered) EnvUnset

func (r *Rendered) EnvUnset(key string) bool

Reports whether an env entry was one whole reference that resolved to nothing

func (*Rendered) Rerender

func (r *Rendered) Rerender(ctx context.Context, env *tools.Env) (*Rendered, error)

Renders the entry again under the current scope, resolved strings final and missed ones retried

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 SSEEvent

type SSEEvent struct {
	ID    string
	Event string
	Data  string
	Retry string
}

SSEEvent is one parsed server sent event

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

func NewSSEReader(body io.Reader, limit int, source string) *SSEReader

NewSSEReader wraps a stream body, capping each event at limit bytes

func (*SSEReader) Next

func (s *SSEReader) Next() (*SSEEvent, error)

Next returns the next complete event, io.EOF at a clean end, and the cap error on an oversized event

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

func (t *SSETransport) Label() string

Label names the transport

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

func (*SSETransport) Send

func (t *SSETransport) Send(ctx context.Context, msg *Message) error

Send posts one message to the announced endpoint

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

type ServerKey struct {
	Scope string
	Name  string
}

ServerKey is a connection key, the bare name outside a multiplexer and the owning scope with the name under one

func (ServerKey) Scoped

func (k ServerKey) Scoped() bool

Reports whether the key carries an owning registry scope

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

func Status

func Status(ctx context.Context, env *tools.Env, configured map[string]*Rendered, includeRuntime bool) []ServerStatus

Status reports each configured server as connected, disabled, connecting, failed, lazy or configured from cached state, never connecting

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

func (s *Session) Close() error

Closes the transport and waits for the reader to fail pending requests

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

func (s *Session) Err() error

Why the session ended, nil while it runs

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

func (s *Session) ListPrompts(ctx context.Context) ([]*Prompt, error)

Every prompt the server lists across pages

func (*Session) ListResources

func (s *Session) ListResources(ctx context.Context) ([]*Resource, error)

Every resource the server lists across pages

func (*Session) ListTools

func (s *Session) ListTools(ctx context.Context, hints *CacheHints) ([]*Tool, error)

Every tool the server lists across pages, the first page's cache hints in hints when given

func (*Session) Name

func (s *Session) Name() string

Name of the server the session talks to

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

func (s *Session) Ping(ctx context.Context) error

Ping round trip, the optional utility a keepalive probes

func (*Session) ProtocolVersion

func (s *Session) ProtocolVersion() string

Protocol revision later requests are shaped for

func (*Session) ReadResource

func (s *Session) ReadResource(ctx context.Context, uri string) (*ReadResourceResult, error)

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

func (t *StdioTransport) Label() string

Label names the transport

func (*StdioTransport) PGID

func (t *StdioTransport) PGID() int

PGID returns the child's process group id, zero when groups are unsupported

func (*StdioTransport) PID

func (t *StdioTransport) PID() int

PID returns the child's process id

func (*StdioTransport) Receive

func (t *StdioTransport) Receive() <-chan *Message

Receive returns the inbound message channel

func (*StdioTransport) Send

func (t *StdioTransport) Send(ctx context.Context, msg *Message) error

Send writes one message as a single line to the child's stdin

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

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

func HeadlessUI

func HeadlessUI() TerminalUI

Terminal UI that writes to stdout and never prompts

type TimeoutError

type TimeoutError struct{}

TimeoutError is a connect that outlived its connect_timeout

func (*TimeoutError) Error

func (*TimeoutError) Error() string

What the user is told about a connect that outlived its deadline

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

func (*TokenStorage) TokensPath

func (s *TokenStorage) TokensPath() string

Token file path

type Tool

type Tool struct {
	Name         string           `json:"name"`
	Title        string           `json:"title,omitempty"`
	Description  string           `json:"description,omitempty"`
	InputSchema  *jsonutil.Object `json:"inputSchema"`
	OutputSchema *jsonutil.Object `json:"outputSchema,omitempty"`
	Annotations  *ToolAnnotations `json:"annotations,omitempty"`
	Meta         map[string]any   `json:"_meta,omitempty"`
}

Tool is one entry of tools/list

func (*Tool) ReadOnly

func (t *Tool) ReadOnly() bool

ReadOnly reports an exact true readOnlyHint, anything else counts as write capable

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 ToolCost

type ToolCost struct {
	Low  float64
	High float64
	Note string
}

ToolCost is the declared spend of one tool call, a range or a single figure

type ToolPinStore

type ToolPinStore interface {
	UpdateSessionToolNames(sessionID string, pin any) error
}

ToolPinStore persists a session tools pin, nil pin clearing it

type ToolSummary

type ToolSummary struct {
	Name        string
	Description string
}

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

func ProbeSingleServerTimeout

func ProbeSingleServerTimeout(ctx context.Context, env *tools.Env, name string, cfg map[string]any, connectTimeout float64) ([]ToolSummary, error)

Connects one server within a connect timeout in seconds, lists its tools and disconnects

type ToolsSpec

type ToolsSpec struct {
	DefaultEnabled  []string
	DefaultExcluded []string
}

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 TransportSpec struct {
	Type    string
	Command any
	Args    []string
	URL     any
	Version any
	Env     map[string]string
}

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

type UnsetReferenceError struct {
	Server string
	Refs   []string
}

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

type UtilitySchema

type UtilitySchema struct {
	Schema     *jsonutil.Object
	HandlerKey string
}

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

Jump to

Keyboard shortcuts

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