Documentation
¶
Overview ¶
Package mcp exposes an iqlink API specification as a Model Context Protocol server, and imports an MCP server as a typed Go struct.
Serving ¶
Main is the one-line entry point (DESIGN_SPEC.md A1): it curates the implementation and serves it over the process's stdio streams - protocol frames on stdout, nothing else, with every log on stderr (B7) - and shuts down cleanly on stdin EOF (once the calls already read are answered) and on SIGINT/SIGTERM. Main owns the process: the clean outcomes return, so the process exits zero, and any failure - a curation problem, a bad flag, a port that cannot be bound, a failed session - is reported on stderr and exits 1. Run is its returning form, for a program that reports failures its own way. Serve is the library form of the same path: it takes a context.Context (A6) and a Transport, so the caller owns cancellation; Stdio is the process-streams transport and StdioOver the injectable one. Handler is the HTTP form: the implementation as an http.Handler (A1), hardened with the default limits (E25); Main's -addr flag serves it on a listener instead of stdio. Every entry point takes an API implementation, a Backend imported by FromREST or FromOpenAPI, or a Surface already curated with Curate - DESIGN_SPEC.md §4's second snippet's shape - and reports a surface or backend with deferred problems (Surface.Err, Backend.Err) instead of serving it; Handler panics with that report, its documented construction bargain. Both of the specification's one-liners compile and serve as written (decision 0049):
mcp.Main(mcp.FromREST[GitHub]("https://api.github.com"))
mcp.Main(mcp.Curate(mcp.FromREST[GitHub]("https://api.github.com"),
mcp.Only("Issues.List", "Issues.Create"),
mcp.Fix("Issues.List.per_page", 20),
mcp.Auth(oauth.PerUser(githubTokenExchange)),
))
Directives address an operation by its tool name ("issues.list") or its Go field path ("Issues.List"); see Curate. Tool results can choose the text the model reads through Renderer, or return rich content blocks (B12, G33): one Content - Text, Image, Audio, ResourceLink, EmbeddedResource - a []Content slice of them, or an io.Reader stream, each rendered with its text fallback (E26 redacts every text surface). Prompt messages carry one block through PromptMessage.Content; nil keeps the text-only shape.
Structured output ¶
Every tool that returns data advertises an outputSchema composed from its Go result type and answers with the result as structuredContent (B11). Both are always JSON objects, as every protocol revision before 2026-07-28 requires and the official TypeScript SDK's client enforces: a result that is not an object - a string, number, boolean, slice or array, or a pointer, whose null makes it nullable - travels in the envelope {"result": <value>} under the schema {"type":"object","properties": {"result": <schema>},"required":["result"],"additionalProperties":false}, at every negotiated version (decision 0046). A struct or map result is advertised and sent as it is. A nil slice, map or []byte - the result itself or a value nested in it, such as a struct's field - structures as its empty form ([], {} or "") wherever its schema admits no null, and a nil pointer as null, so a tool with an output schema always answers with structured content that validates against it; the text content item still renders the result itself, never the envelope. Import unwraps the envelope for its facade's result types (an interface result type receives it as sent); Client.Call returns the structured content as sent.
The server serves under fail-closed defaults: the default authorization engine, no approval (destructive operations denied), no hooks, and no identity - every call is anonymous, so a protected operation is denied. A call refused only because nothing is configured says so: a per-user delegation refused for an anonymous caller names WithStdioIdentity and ForHTTP(WithBearerAuth), and a destructive operation denied for want of an approver names WithApprover and WithClientApproval. The curation can change the credential provider: Auth on a Curate call selects the per-user delegated source (the oauth package's PerUser) whose exchange produces each call's backend token - bound, with no entries of its own, to the curated backend's host - or a server-configured provider wrapped by policy.ProviderSource, and the entry points wire it onto the runner. Everything else is an Option; see "Configuring the server".
Configuring the server ¶
Every entry point takes the same options (decision 0047). The list is validated as a whole before anything serves, and every problem is one collected startup report (A5): a nil option; an option given twice where both would apply; an option's own argument problem (a nil validator, an engine that fails the canary below); and an option the served transport does not honour - it is never silently dropped. The security-weakening MCPGODEBUG switches of the protocol engine (disablelocalhostprotection, disablecontenttypecheck, allowsessionsinstateless) are refused at every HTTP and SSE construction, options or not; the pinned engine (go-sdk v1.8.0) no longer reads the first two, and the refusal keeps them because an application's build can replace the engine with an earlier release that does. Serve and Run return the report, Main prints it and exits 1, Handler and ServeSSE panic with it (NewHandler and NewSSEHandler return it), and the testing harness fails the test.
Which transport honours which option:
option stdio Streamable HTTP legacy SSE harness WithObserver yes yes yes yes WithAuditSink yes yes yes yes WithAuthorization yes yes yes yes WithApprover yes yes yes yes WithClientApproval yes yes yes yes WithServerInfo yes yes yes yes WithInstructions yes yes yes yes WithLogger yes yes yes yes WithBulkheads yes yes yes yes WithBreakers yes yes yes yes WithRetries yes yes yes yes WithBackendKey yes yes yes yes WithIdempotency yes yes yes yes WithHooks yes yes yes yes WithTasks yes yes*** no yes WithTaskStore yes yes*** no yes WithLimits yes* yes yes yes* WithBearerAuth no yes no no WithProtectedResourceMetadata no yes no no WithAllowedOrigins no yes yes no WithAllowedHosts no yes yes no WithHealthPath no Run/Main only Run/Main only no WithSessions no yes** no no WithStdioIdentity yes no no no WithSSE no no required no
(*) stdio and the harness enforce WithLimits' CallTimeout and MaxRequestBytes, the two the call pipeline reads; the rest are validated. WithHealthPath configures the listener Run and Main own, so NewHandler, Handler, NewSSEHandler and ServeSSE refuse it. (**) WithSessions needs an event store at NewHandler and Handler; Run and Main build and close a memory one for nil. (***) WithTasks serves the tasks extension of protocol 2026-07-28, which the engine serves on the stateless wire only, so it is refused beside WithSessions; WithTaskStore needs WithTasks on the same transport. The Timeout curation directive, which gives one operation its own call deadline, applies wherever the surface is served.
A program serving more than one transport scopes an option with ForStdio, ForHTTP or ForSSE: a block is validated against its own transport at every entry point - a broken block fails every serve - and applied only when that transport is served. ForSSE(WithSSE()) permits -sse-addr while the same binary serves stdio and -addr. One rule spans transports: a list that authenticates Streamable HTTP must not serve SSE, which cannot carry bearer authentication, beside it. One rule spans options: WithProtectedResourceMetadata needs WithBearerAuth on the same transport, whose validator - when it reports an audience - names exactly the published resource; WithSessions' event store, when it reports the limits it was built over, shares the server's session bounds; WithBackendKey needs WithBulkheads or WithBreakers; and WithRetries names a destructive operation only when WithIdempotency keys it. WithRetries and WithIdempotency name operations the way the curation directives do, by SOURCE name or Go field path, and each name must address one exposed operation.
Sessions ¶
Streamable HTTP is stateless by default (B7): every POST is answered on its own, and GET and DELETE are refused 405. WithSessions opts into explicit sessions - an Mcp-Session-Id, a session's GET stream and DELETE, the negotiated logging level kept for the session, and streams resumed from a client's Last-Event-ID through an EventStore (MemoryEventStore, or the store/redis and store/sql modules). A session ID is an address, never a credential (B10): each request presents its own bearer token and runs as that token's identity, and a session answers only the tenant and subject that created it. MaxSessions caps the live sessions, and the store records only each session's GET stream - a call is answered as one JSON body, never recorded - each replay checked against the event IDs the server issued. Sessions live in the serving process whatever the store - another replica, or the same one after a restart, answers 404 - so scaling out needs sticky routing on Mcp-Session-Id; a durable store gives no cross-replica or post-restart resume.
Server identity, instructions and logging ¶
The initialize handshake announces the server's name and version (A6): WithServerInfo's, or by default the API's api: name - "Weather" for api.Specification `api:"Weather"` - else the last element of the program's module path, else "iqmcp", and the version the build information records, else "(devel)" (decision 0052). A derived name is letters, digits, '_', '.' and '-' only, so it carries no space, control or bidirectional-override character, and an OpenAPI document's title never becomes one. The testing harness announces "mcp-testing".
Server instructions - the text a client hands the model on how to use the server - come from WithInstructions alone (E26): trusted, operator-authored text, up to 16 KiB. Nothing the server serves derives them: not the docs: tags, not an OpenAPI document, not any backend's content, which stay in the tool descriptions where a client treats them as the backend's. Without the option the handshake carries none.
The server's own records - a refused bearer token's cause (its token redacted), a recovered engine or approver panic, the startup warnings - go to the process's default slog logger, which Run and Main route to stderr. WithLogger sends them, the per-call lifecycle records and the listener's net/http errors to a logger of the program's own, whose level decides what it keeps. The expose-all warning goes there too when the entry point curates the implementation itself; a Surface handed in from Curate had its warning written to the default logger as it was curated. On stdio that logger must never write to standard output, which carries protocol frames only.
Identity, authorization and credentials ¶
Each transport has one identity source, always server-side: the verified bearer token on Streamable HTTP (WithBearerAuth - over oauth.NewJWKSValidator for an IdP's JWT access tokens, policy.NewAPIKeyValidator for opaque keys, or a policy.Validator of your own, with WithProtectedResourceMetadata telling OAuth clients where to obtain a token), the operator's assertion on stdio (WithStdioIdentity), and the testing harness's Client.As. Nothing a client sends - an argument, _meta, a header other than the verified Authorization - reaches it. WithAuthorization replaces the engine that decides both discovery (what tools/list shows) and every execution; construction probes it once with synthetic "iqmcp.canary" decisions and refuses an engine that grants a protected operation to the anonymous identity, ignores tenant:required, or panics; a panic on a real decision later is recovered as a denial, and the server keeps serving. Inside a call, IdentityFromContext returns the identity authorization used and CredentialFromContext the credential the Auth selection resolved. Inside a tool call, ListedTools returns the other tools the caller can list and call - discovery's own answer for that identity, less any tool whose call the same engine denies it - for a tool that reasons about the surface beside it, such as the router module's search_tools.
Approving destructive operations ¶
An operation without the readonly hint is destructive, and it runs only once approved (E26). WithApprover decides server-side, and a client that declares elicitation is then asked as well - "approve this destructive operation: <name>", nothing else - so both must grant. WithClientApproval makes the client's confirmation mandatory: a client that cannot be asked is denied, audited policy.ApprovalUnsupportedClient. With neither, every destructive operation is denied. An approver that grants the "iqmcp.canary" startup probe - a destructive operation for the anonymous identity - approves every client that cannot be asked, and the server logs one warning saying so unless WithClientApproval is given too. Streamable HTTP is stateless by default, so there only a client on protocol 2026-07-28 or later, which answers the question and retries the call, can be asked; an older client there is decided by the approver alone, or denied under WithClientApproval - unless it holds a WithSessions session, on whose GET stream it is asked. On the 2026-07-28 retry the approver is consulted again, so its decision must be pure and repeatable; the call is audited once, with the retry's decision.
Asking the calling client ¶
Inside a call an implementation may ask the client calling it (B8): Sample for text from the client's model, Elicit for input from the client's user, ClientRoots for the filesystem roots it declares; and it may tell it: ReportProgress when the call carries a progress token, ClientLogger for log records at the level the client set. Each is denied by default - a client that declares no capability for it, and every call outside a served one, answers Refused, not accepted, no roots, false, or discards - and every string either way is redacted over the call's credential. What the client answers is untrusted input, never an instruction or an authority, and an answer to Elicit never approves a destructive operation. On protocol 2026-07-28 and later a question ends the call's pass: the accessor's error must be returned as it is or wrapped with %w, before any side effect, and the call runs again from the start with the answer - see Sample. mcptest.WithFakeClient answers for the client in the testing harness, and mcptest.ContextWithFakeClient for an implementation a unit test calls directly. Sampling, elicitation, roots and logging are deprecated by the MCP specification as of 2026-07-28 (SEP-2577) and work through its deprecation window.
Order of the controls ¶
On Streamable HTTP a request meets, outermost first: the liveness route of WithHealthPath, on the listener Run and Main own, answered with no other layer; the protected-resource metadata document, answered at exactly its well-known path with no other layer (public by design; only with WithProtectedResourceMetadata); the bearer authentication (401 with a fixed body and a Bearer challenge, or 403 for a missing required scope, each naming the metadata URL when it is published; a CORS preflight passes); the origin guard (403; loopback origins, or exactly those WithAllowedOrigins lists); the Host guard (403; only with WithAllowedHosts); the rate limit (429 with Retry-After), the in-flight cap (503; a GET's event stream takes a slot of a pool of its own, bounded by MaxSessions), and the protocol engine (its DNS-rebinding check unless the Host guard replaces it, the 413 body cap, the protocol-version check, and - with WithSessions - the session cap, 503 for an initialize past MaxSessions live sessions, and the session lookup: 404 for a session it does not hold, 403 for a token naming another tenant or subject than the session's creator). A session's GET stream lives like the legacy SSE wire's, below. The legacy SSE wire puts its query-token refusal (400) outermost, carries no bearer layer, and caps the body itself before the engine; its hanging GET runs without the http.Server's request deadlines, each write bounded by the server's WriteTimeout instead, and carries a keepalive comment whenever it has been quiet for up to 15 seconds, so a session lives as long as its client keeps it, or until the server shuts down. Discovery then filters the listed operations by the caller's identity with the engine. Each call runs the pipeline in a fixed order, each stage once: trace start; decode, the arguments cap and the idempotency key; identity; authorization; approval (destructive operations only: the server's approver, then the client when it can be asked); the argument hook (WithHooks), whose rewrite is checked against the argument types, the input schema and the call's idempotency key; credentials; deduplication (WithIdempotency: a replay ends the call here); the breaker, the bulkhead and the implementation under its deadline, then error mapping - the one span that runs again for each attempt WithRetries makes, within the same deadline; the result hook (WithHooks), on the final successful attempt's result; trace end, audit and metrics. Result shaping and rendering follow, outside the pipeline. The backend key (WithBackendKey) and both hooks see the identity but not the credential. Only the credential stage, the implementation and the bridge's outbound transport see the resolved credential; the pipeline redacts it from every result, error, log line, progress message and audit record it produces, and the idempotency store records a result as its call answered it, already redacted, beside digests of the key and the arguments - no credential, and no argument value beyond what that answer carries; a credential a context carried into the call is never reported as the call's own. The verified caller's presented token reaches the credential provider alone, as policy.CredentialRequest.SubjectToken: the server keeps it beside the verified token information, never in it, so nothing this package or the protocol engine plants on the call context carries it - not even for reflection - and no audit record or metrics sample does; a provider refusal that echoes it is redacted like the credential.
Deadlines, cancellation and side effects ¶
Every call runs under a deadline (DESIGN_SPEC.md F27) on every served transport: its operation's own Timeout, else the server's CallTimeout - 30 seconds, the default limits', unless WithLimits replaces it (stdio included since decision 0051; the testing harness runs none unless it is configured). The call's context is also cancelled when the caller gives up on it: the client cancels the request, or the HTTP request carrying it goes away - on the legacy SSE wire, the session's stream, which a server shutdown ends. Either way the call is answered at once with the "timeout" error - retryable when the deadline passed, not when the caller gave up - and the implementation's context is done; the implementation keeps running until it notices.
Cancellation cannot undo side effects. Whatever the implementation already did - a row written, a message sent, a payment captured - stays done, and a request it already sent to a backend may complete there after the call was answered with a timeout. A timed-out destructive call may therefore have succeeded, and a client that retries it may perform it twice. Pass ctx to every backend call so work stops as early as it can; make destructive operations idempotent, or check the backend's state before repeating one; and give an operation that legitimately runs long a Timeout of its own rather than raising every call's deadline.
Resilience and idempotency ¶
Every resilience control is off until its option is given, on every transport (F29). WithBulkheads bounds the calls one backend runs at once and the calls that may wait, refusing the rest at once as a retryable "unavailable" tool error; WithBreakers stops calling a backend that failed repeatedly until a cooldown's trial calls succeed; WithBackendKey names each call's backend - without it the whole server is one. WithRetries retries the operations it names, and no other, when a failure is classified retryable (below), every attempt and wait within the call's one deadline; a destructive operation only when WithIdempotency keys it and the call carries its key, since a timed-out write may have succeeded. WithIdempotency replays, instead of running the implementation again, the outcome a protected operation's call with the same key, identity and arguments recorded within its window, and refuses a key reused with other arguments. Only a verdict is recorded: a call a gate refused, whose deadline passed or that failed retryably records nothing, so its repeat with the same key runs again. The key is an argument the operation declares, so the implementation can hand it to its backend - which is what makes a retried write safe. The dedup window is one server's, in memory: another replica or a restart does not see it, and nothing here is exactly-once execution.
Transforming arguments and results ¶
WithHooks installs two typed hooks (J41): Hooks.Arguments rewrites a call's decoded arguments - its Go values, by name - after authorization and approval and before the credential is resolved, and Hooks.Result rewrites the typed result the implementation returned before it is shaped and rendered. Each runs once per call, never per attempt. A rewrite keeps the operation's contract or fails the call: arguments of the declared types that pass the input schema, as a caller's must, the caller's idempotency key unchanged, a result of the declared result type. Neither hook's context carries the call's credential, but the result hook receives the implementation's result unredacted - a credential the implementation echoed into it included - so it must pass what it reads on only through the value it returns, which is redacted like any result. A hook's error maps like an implementation's, below.
Errors an implementation returns ¶
An implementation error is mapped to a safe, model-visible message with the call's correlation ID; its own text reaches the operator's audit diagnostics only, redacted. To tell the model why a call failed, return a ToolError: its Message, redacted and bounded, is the text the model reads, and its class, retryability and retry-after ride the result's _meta. A tool-result error of any kind carries that _meta. An error - anywhere in its errors.As chain - with both a Code() string and a Retryable() bool method is classified by them: Code names one of the closed classes ("decode", "auth", "approval", "credential", "invocation", "timeout", "unavailable", "unknown"; any other value is "invocation"), and Retryable says whether a repeated call may succeed - honoured for every class but "invocation", which is never retryable. When that error is retryable and also has a RetryAfter() time.Duration method, a positive duration is the least a retry by WithRetries waits. Otherwise context.DeadlineExceeded is a retryable "timeout", context.Canceled a "timeout" that is not (the caller gave up), and any other error a non-retryable "invocation" failure - which is why WithRetries retries an implementation's own failure only when it declares a retryable class, such as "unavailable" for a backend that is not taking calls.
Wrapping the handler ¶
The supported escape hatch is http.Handler composition (decision 0048): a program wraps the handler NewHandler or Handler returns in its own middleware or mounts it on its own mux. Such middleware runs before every control above - it sees unauthenticated requests and the raw Authorization header, which it must not log; anything it answers itself bypasses them all; and it cannot plant a verified identity or a credential - a served call reports only the ones its own pipeline resolved. A wrapper that replaces the http.ResponseWriter must expose the one it wraps with an Unwrap() http.ResponseWriter method, the net/http convention http.ResponseController follows: the legacy SSE wire lifts the server's deadlines for its streams through it, and behind a wrapper without one the server's timeouts cut every session. There is no public access to the underlying protocol server.
The testing package drives the same pipeline in process, without ports: an implementation in, list/call/inspect out.
The module is pre-1.0 (v0.x): its public API can still change between minor versions. The README's Project status and Compatibility sections record what is supported and on which toolchains and clients.
See DESIGN_SPEC.md for the product requirements, IMPLEMENTATION_PLAN.md for the current state, and AGENT.md for the development workflow.
Index ¶
- Variables
- func ClientLogger(ctx context.Context) *slog.Logger
- func CredentialFromContext(ctx context.Context) (policy.Credential, bool)
- func Handler(impl any, opts ...Option) http.Handler
- func IdentityFromContext(ctx context.Context) (policy.Identity, bool)
- func Import[T any](client *Client) (T, error)
- func Main(impl any, opts ...Option)
- func NewHandler(impl any, opts ...Option) (http.Handler, error)
- func NewSSEHandler(impl any, opts ...Option) (http.Handler, error)
- func ReportProgress(ctx context.Context, progress, total float64, message string) bool
- func Run(impl any, opts ...Option) error
- func Serve(ctx context.Context, t Transport, impl any, opts ...Option) error
- func ServeSSE(impl any, opts ...Option) http.Handler
- func ToolSpecs(surface *Surface) []protocol.ToolSpec
- type Argument
- type Audio
- type AuditRecord
- type AuditSink
- type AuditSinkFunc
- type Backend
- type CallResult
- type CallSample
- type Client
- type ClientHTTPOptions
- type ClientOption
- type ClientRoot
- type ClientTransport
- type Content
- type Deprecation
- type Directive
- func Alias(source, alias string) Directive
- func Auth(src policy.CredentialSource) Directive
- func Budget(name string, maxBytes, maxItems, maxTokens int) Directive
- func Deprecate(source string, info Deprecation) Directive
- func Describe(name, docs string) Directive
- func Except(names ...string) Directive
- func Fields(name string, paths ...string) Directive
- func Fix(path string, value any) Directive
- func Hide(name string) Directive
- func Only(names ...string) Directive
- func Paginate(name string, size int) Directive
- func Production(names ...string) Directive
- func Redact(name string, paths ...string) Directive
- func Rename(from, to string) Directive
- func Timeout(name string, d time.Duration) Directive
- type ElicitRequest
- type ElicitResult
- type EmbeddedResource
- type Error
- type EventStore
- type FromOpenAPIOption
- func FromOpenAPIWithClient(c *http.Client) FromOpenAPIOption
- func FromOpenAPIWithEgressGuard(guard policy.Destinations) FromOpenAPIOption
- func FromOpenAPIWithHeader(name, value string) FromOpenAPIOption
- func FromOpenAPIWithOperations(ids ...string) FromOpenAPIOption
- func FromOpenAPIWithSkipUnsupported() FromOpenAPIOption
- type FromRESTOption
- type Hooks
- type Image
- type ListedTool
- type MemoryEventStore
- func (s *MemoryEventStore) After(ctx context.Context, sessionID, streamID string, index int) iter.Seq2[[]byte, error]
- func (s *MemoryEventStore) Append(ctx context.Context, sessionID, streamID string, data []byte) error
- func (s *MemoryEventStore) Close()
- func (s *MemoryEventStore) Limits() policy.Limits
- func (s *MemoryEventStore) Open(ctx context.Context, sessionID, streamID string) error
- func (s *MemoryEventStore) SessionClosed(ctx context.Context, sessionID string) error
- type MemoryTaskStore
- func (s *MemoryTaskStore) Create(ctx context.Context, id, owner string, expires time.Time, data []byte) error
- func (s *MemoryTaskStore) CreateListed(ctx context.Context, id, owner string, expires time.Time, data, listing []byte) error
- func (s *MemoryTaskStore) ListTasks(ctx context.Context, owner string) (map[string][]byte, error)
- func (s *MemoryTaskStore) Load(ctx context.Context, id string) ([]byte, int64, error)
- func (s *MemoryTaskStore) Swap(ctx context.Context, id string, version int64, data []byte) (int64, error)
- func (s *MemoryTaskStore) SwapListed(ctx context.Context, id string, version int64, data, listing []byte) (int64, error)
- func (s *MemoryTaskStore) TaskConfig() policy.TaskConfig
- type Observer
- type Operation
- type Option
- func ForHTTP(opts ...Option) Option
- func ForSSE(opts ...Option) Option
- func ForStdio(opts ...Option) Option
- func WithAllowedHosts(hosts ...string) Option
- func WithAllowedOrigins(origins ...string) Option
- func WithApprover(a policy.Approver) Option
- func WithAuditSink(sink AuditSink) Option
- func WithAuthorization(e policy.Engine) Option
- func WithBackendKey(key func(ctx context.Context, operation string) string) Option
- func WithBearerAuth(v policy.Validator, scopes ...string) Option
- func WithBreakers(cfg policy.BreakerConfig) Option
- func WithBulkheads(cfg policy.BulkheadConfig) Option
- func WithClientApproval() Option
- func WithHealthPath(path string) Option
- func WithHooks(h Hooks) Option
- func WithIdempotency(cfg policy.IdempotencyConfig, keyArguments map[string]string) Option
- func WithInstructions(text string) Option
- func WithLimits(l policy.Limits) Option
- func WithLogger(logger *slog.Logger) Option
- func WithObserver(observer *Observer) Option
- func WithProtectedResourceMetadata(m ProtectedResourceMetadata) Option
- func WithRetries(p RetryPolicy, operations ...string) Option
- func WithSSE() Option
- func WithServerInfo(name, version string) Option
- func WithSessions(events EventStore) Option
- func WithStdioIdentity(id policy.Identity) Option
- func WithTaskStore(store TaskStore) Option
- func WithTasks(cfg policy.TaskConfig, operations ...string) Option
- type Problem
- type Prompt
- type PromptMessage
- type PromptRole
- type ProtectedResourceMetadata
- type Renderer
- type Resource
- type ResourceLink
- type RetryPolicy
- type SampleMessage
- type SampleRequest
- type SampleResult
- type ServerInfo
- type Surface
- type TaskLister
- type TaskStore
- type Text
- type ToolError
- type TraceEnd
- type TraceStart
- type Transport
Constants ¶
This section is empty.
Variables ¶
var ( // ErrTaskNotFound reports a task the store does not hold: never // created, or discarded at its expiry. ErrTaskNotFound = errTaskNotFound // ErrTaskConflict reports a write that lost to another: the record // changed since it was read, or the task ID is already in use. ErrTaskConflict = errTaskConflict // ErrTaskStoreFull reports a create past MaxTasks or // MaxTasksPerIdentity: the call then runs synchronously. ErrTaskStoreFull = errTaskStoreFull // ErrTaskRecordTooLarge reports a record past // policy.TaskConfig.MaxRecordBytes, which a store refuses to keep or // read back. ErrTaskRecordTooLarge = errTaskRecordTooLarge )
The refusals a TaskStore wraps, which the server matches with errors.Is.
var ErrEventsPurged = errEventsPurged
ErrEventsPurged is the error an EventStore's After wraps when events after the resume index were evicted from the stream's retention window: the resume is refused rather than replayed partially, and the client that asked is answered 400. It is the protocol engine's own sentinel, so errors.Is matches it however a store wraps it.
Functions ¶
func ClientLogger ¶
ClientLogger returns the current call's client-visible logger: each record logged through it with the call's context becomes a logging notification to the calling client (DESIGN_SPEC.md B8), at the level the client negotiated - none until it asks for one - with the record's message and attributes redacted over the call's credential. The records go to the calling client only, never to WithLogger's logger; treat them as output the client's user may read. It is never nil: outside a served call it discards.
Logging, like sampling, elicitation and roots, is deprecated by the MCP specification as of protocol 2026-07-28 (SEP-2577) and stays functional through its deprecation window of at least twelve months.
func CredentialFromContext ¶
func CredentialFromContext(ctx context.Context) (policy.Credential, bool)
CredentialFromContext returns the backend credential the call resolved through the surface's Auth selection (DESIGN_SPEC.md D21), and true; false when none was resolved - a credential a context carried into the call, such as one wrapping middleware planted, is never reported as the call's own. The pipeline redacts the credential's value from everything it produces - results, errors, logs, progress, the audit record - but not from what the implementation writes elsewhere; the backend-key and audit hooks never see it. Present it only where policy.Credential.Permit accepts the destination.
func Handler ¶
Handler curates impl and returns its MCP server as an http.Handler (DESIGN_SPEC.md A1), hardened with the default limits or those WithLimits configures (E25) and serving the stateless Streamable HTTP baseline (B7) - or explicit sessions over the event store WithSessions hands it:
http.Handle("/mcp", mcp.Handler(Weather{Current: current}))
impl is an API implementation or a Backend - curated the default way - or a Surface already curated with Curate and taken as-is, DESIGN_SPEC.md §4's second snippet shape: http.Handle("/mcp", mcp.Handler(mcp.Curate(impl, mcp.Only(...), mcp.Fix(...)))).
With no options the handler runs under the fail-closed runner defaults - the default authorization engine, no approver (destructive operations denied), no hooks - with the default limits' CallTimeout enforced per call, and the credential provider the curated surface's Auth selection built wired onto the runner ([entryRunner]); a surface curated without Auth serves credential-less. Every call is then anonymous - the handler verifies no client identity - so a protected operation is denied and a per-user delegation refused, the fail-closed shape. WithBearerAuth makes every request present a verified bearer token and runs each call as its identity; WithAuthorization replaces the engine. The E25 hardening chain - request-size cap, concurrency and rate ceilings, origin protection, the engine's own DNS-rebinding check - is on with the default limits; WithLimits, WithAllowedOrigins and WithAllowedHosts tune it, and the chain and its status codes are documented under "Configuring the server" in the package documentation.
The caller owns the http.Server, and with it the connection timeouts: give it a ReadHeaderTimeout against slowloris, and Read and Write timeouts longer than the longest per-call deadline the handler serves (its CallTimeout, 30 seconds by default, or a longer Timeout) - net/http cancels a request whose read deadline passes while its call still runs. The example gallery's mux example shows one.
opts configure the Streamable HTTP server: every unscoped option must be honoured there - WithStdioIdentity, WithSSE and WithHealthPath are not - and a ForStdio or ForSSE block is validated, then inert (decision 0047).
A curation or construction problem - an implementation the contract refuses, a tool the adapter refuses, a handed-in surface carrying deferred problems, or an option problem - is a programmer error at this entry point: A1's signature has no error to return, so Handler panics with fmt.Errorf("mcp.Handler: %w", err) over the one collected report (A5), the template.Must bargain; errors.As reaches the *Error. NewHandler is the same handler with the report returned instead, for a program whose options come from runtime configuration. Run and Serve return the report, and Main reports it on stderr and exits 1. The bargain covers every shape the same way (decisions 0013 and 0049): an implementation or a Backend Curate defers problems onto, and a *Surface that arrives with Surface.Err set, panic with the collected report before the handler serves a single request.
func IdentityFromContext ¶
IdentityFromContext returns the identity the pipeline authorized the current call as, and true, inside a served tool call, prompt or resource read - the anonymous identity included - and the zero identity and false anywhere else. Only the configured identity source sets it: the verified bearer token (WithBearerAuth), the operator's stdio assertion (WithStdioIdentity), or the testing harness's Client.As. No client input - an argument, _meta, a header - can reach it.
func Import ¶
Import binds the connected client to the typed facade T: a struct whose function fields carry the same mcp:/args: tags curation reads. Each field must take context.Context first and return a trailing error, with zero or one data result; resource- and prompt-kind fields are unsupported mappings with actionable errors. The returned facade's functions call the remote tools by their resolved names: a nil args marshals to the empty arguments object, an isError tool result returns as a Go error carrying the safe text, and a protocol-level refusal returns the client error unchanged. There is no automatic retry and no JSON guessed from prose: structured output is authoritative, and a missing structured result is an actionable error unless the target is a supported text result.
A result whose type is not an object - a string, number, boolean, slice or array, or a pointer - travels from a server of this package in the object envelope {"result": <value>} (decision 0046), and the facade function returns the value inside it: a structured result that is an object whose one key is "result" decodes that key's value. The exceptions are the result types whose own JSON can be exactly that object - a map, and a struct declaring a "result" property - which decode it as it is, and an interface result type (such as any), which receives the structured content as sent, envelope included, exactly as Client.Call reports it. Any other structured result decodes as it is, so a server that sends bare values keeps working. A pointer to a struct is unwrapped like every pointer; declare the struct value when a server that does not wrap sends a bare object whose only property is "result".
func Main ¶
Main runs impl as an MCP server over stdio (DESIGN_SPEC.md A1: one line from struct to server; stdio by default) and owns the process the caller's main hands over to:
func main() { mcp.Main(Weather{Current: current}) }
impl is an API implementation - curated the default way, exactly as the zero-ceremony path has always served it - a Backend an import returned, curated the same way (DESIGN_SPEC.md D17's one line), or a Surface already curated with Curate, DESIGN_SPEC.md §4's second snippet shape:
mcp.Main(mcp.FromREST[GitHub]("https://api.github.com"))
mcp.Main(mcp.Curate(mcp.FromREST[GitHub]("https://api.github.com"),
mcp.Only("Issues.List", "Issues.Create"),
mcp.Fix("Issues.List.per_page", 20),
mcp.Auth(oauth.PerUser(githubTokenExchange)),
))
Main is Run plus the process's exit status, in the style of log.Fatal (decision 0011's amendment). The clean outcomes - stdin reaching EOF once the calls already read are answered, a SIGINT/SIGTERM, -h/-help - return normally, so the process exits zero when main returns. Every failure is reported once on stderr, prefixed with the program's name, and the process exits with status 1 without returning: a curation or construction problem (the collected A5 report), a command-line error, a listener that cannot bind (a busy -addr port), a failed session (a client that closed stdout before its answers were written among them), or calls the stdin-EOF drain deadline cut. Nothing is written to stdout but protocol frames, so a failed startup never corrupts the wire. Because Main exits on failure, deferred functions in the caller's main do not run on that path; a program that must clean up, or report its own way, calls Run and decides for itself.
The lifecycle, the command line (-addr, -sse-addr), the logging routing, the options and the serving defaults are Run's; see Run. opts are validated before the command line is read and again against the transport it selects, so a problem is Main's startup failure whichever flag was passed; ForStdio, ForHTTP and ForSSE scope an option to one transport.
func NewHandler ¶
NewHandler is Handler with its construction problems returned instead of panicked (decision 0011's addendum): the same curated, hardened Streamable HTTP handler, or the one collected report (A5) - an *Error carrying the curation and option problems together - or the boundary error for a nil implementation. It is the form for a program whose options are built from runtime configuration, where a bad value is an error to report, not a programmer error.
func NewSSEHandler ¶
NewSSEHandler is ServeSSE with its construction problems returned instead of panicked (decision 0011's addendum): the same isolated legacy SSE handler, or the one collected report (A5), or the boundary error for a nil implementation.
func ReportProgress ¶
ReportProgress sends one progress notification for the current call - the progress so far, the total it counts toward (zero when unknown) and an optional message, redacted over the call's credential - and reports whether the client asked for progress by sending a progress token with the call (DESIGN_SPEC.md B8). Without a token, and outside a served call, it sends nothing and returns false. Delivery is best effort: a notification the client cannot receive is dropped, and it never fails the call. A tool returning a stream reports progress for each element on its own.
func Run ¶
Run is Main's returning form: it serves impl exactly as Main does - the process's argv, stdin and stdout, and signals - and returns the outcome instead of turning it into the exit status. A program that owns its own reporting (the iqmcp command's serve, a main with cleanup to run) calls Run and decides what a failure means; Main is Run plus the stderr report and exit status 1.
Lifecycle (B7) ¶
The curated API serves over the process's stdin and stdout - protocol frames on stdout, ONLY protocol frames - until stdin reaches EOF or a SIGINT/SIGTERM arrives; both end the server cleanly and Run returns nil. On EOF the calls already read are answered and their responses written before the server stops (the stdin-EOF drain), so a client that writes its requests and closes its end still gets every answer. The drain is bounded by the longest per-call deadline the server serves - the CallTimeout, policy.DefaultLimits' 30 seconds unless WithLimits replaces it, or a longer Timeout - plus a five-second margin, so every call is answered after EOF: by its implementation within its deadline, or with the timeout error once the deadline passes. A call still unanswered when the drain expires - a handler outside the call pipeline that ignores its cancellation - is cut and reported as the error, so a hung handler cannot keep the process alive after its client has gone.
A signal stops the server taking new calls and ends it once the calls already in flight have finished. Over stdio every call runs under its deadline (decision 0051), so a hung implementation is answered with the timeout error when its deadline passes and holds the process no longer; once stdin has reached EOF a signal ends the drain at once. The -addr and -sse-addr services bound their shutdown with a grace instead (see [serveHTTP]); an open legacy SSE session is not waited for - its stream ends when the shutdown begins (see ServeSSE).
Every other outcome is the error returned: a curation or construction problem (one collected report, A5 - reported before anything else when the caller hands in a surface or a backend, because either with deferred problems never serves), a command-line error, a listener that cannot bind, or a failed session - a malformed stream, or a client gone while its answers were still being written: Run takes SIGPIPE while it serves, so a write to a closed stdout is that failed session rather than a process killed by the signal.
Logging (B7) ¶
Run routes the process's default slog handler to stderr explicitly: the expose-all warning, the server's own records and anything the embedder's code logs reach stderr, never the protocol's stdout. It changes no handler but the process default - the caller's own loggers are its own, and WithLogger sends the server's records, the expose-all warning of an implementation Run curates among them, to one of them (which, on stdio, must not write to stdout either).
Flags and HTTP ¶
Run parses the process's argv for the -addr and -sse-addr flags: with no flags it serves stdio, with -addr host:port it serves Streamable HTTP instead, and with -sse-addr host:port the isolated legacy SSE wire (decision 0039) - the server's lifecycle, the fail-closed defaults and the anonymous identity are the same, and the E25 hardening is on with the default limits or those WithLimits configures. See [parseMainAddrs] for the command-line contract: Run owns the process's argv, so anything it does not understand is a startup error (after the usage is printed on stderr), -h/-help prints the usage and returns nil, and a bare port binds on 127.0.0.1. Binding a public interface is possible - the caller named the host - but never silent: the expose-all warning still reaches stderr (or WithLogger's logger), a listener that is not loopback-only serving with no identity source logs one warning that every caller reaching it is anonymous, and the handler's origin posture stays the conservative localhost one unless WithAllowedOrigins lists origins (see Handler). An embedder that parses its own flags should serve through Serve or Handler instead of Run.
Run owns the listener's http.Server for -addr and -sse-addr: a 10-second ReadHeaderTimeout, and read and write timeouts of the longest per-call deadline the server serves - its CallTimeout or a longer Timeout - plus 30 seconds, so every call's answer can be written; the legacy SSE wire's hanging GET is exempt, its deadlines lifted for the session's lifetime, and it ends when the server shuts down. WithHealthPath adds a liveness route to that listener, outside every other control.
Options ¶
opts configure whichever transport the command line selects - stdio, -addr and -sse-addr alike - so an observer or audit sink wired here sees every call however the process is served. Run validates them twice (decision 0047): the transport-independent rules before the command line is read - a nil or duplicated option, an option's own argument problems, a block whose options its transport does not honour - reported together with a handed-in surface's deferred problems; and, once the flag selected the transport, every unscoped option must be honoured there, before any listener is bound. An option that configures one transport only (WithBearerAuth for -addr, WithStdioIdentity for stdio) is therefore scoped with ForHTTP or ForStdio in a binary that serves both.
WithSSE is the program's opt-in to the isolated legacy SSE wire (decision 0039): -sse-addr is refused without it, so a command line can never enable SSE on a program whose author did not. Unscoped, WithSSE selects SSE, so stdio and -addr refuse it - the fail-fast mutual exclusion Serve and Handler apply; ForSSE(WithSSE()) instead permits -sse-addr while the program keeps serving stdio and -addr.
Serving defaults ¶
The server announces the name and version WithServerInfo documents - derived from the API's api: name and the program's build information unless the option sets them - and, with no options, serves under the zero pipeline defaults: the fail-closed authorization engine (WithAuthorization replaces it), no approval - destructive operations denied until WithApprover or WithClientApproval approves them - no hooks, and random correlation IDs. The curation can change the credential provider: a curated Surface whose Auth selection built one has it wired onto the runner ([entryRunner]), and an implementation curated the default way serves credential-less. Every transport adds the default limits to that same runner (E25, F27): each call's deadline - 30 seconds, or its operation's own Timeout - and the arguments cap, on stdio too (decision 0051); WithLimits replaces them. With no identity option every call runs anonymous - stdio carries no identity and the HTTP wiring verifies none - so a protected operation is denied and a per-user delegation refused: WithStdioIdentity asserts the stdio peer, and WithBearerAuth verifies every -addr request's bearer token.
func Serve ¶
Serve curates impl and serves it over t until the wire ends or ctx is done - the library form of Main (DESIGN_SPEC.md A1), with the context the stdlib shape asks for (A6) so the caller owns cancellation: tests inject streams and cancel the context; an HTTP supervisor cancels on its own lifecycle. Like Main it serves under the zero pipeline defaults, the default limits' 30-second call deadline and the anonymous identity unless opts configure otherwise.
impl is an API implementation or a Backend - curated the default way - or a Surface already curated with Curate and taken as-is. A surface or backend with deferred problems (Surface.Err, Backend.Err) is reported instead of served.
The outcome is the transport run's: nil for a clean EOF shutdown (a stdio transport answers the calls already read first, bounded by the drain deadline - see Run), the context error for a cancelled context, an error for a failed session, and - before any of that - the single collected problem report (A5) when impl could not be curated into a servable server or opts do not serve stdio, or an explicit error for a nil transport or a nil implementation. Run is the process form: it adds the argv, the signals and the stderr log routing and maps the signal shutdown to a clean nil; Main adds the exit status.
opts configure the stdio server: every unscoped option must be honoured on stdio - WithBearerAuth and WithSSE are not - and a ForHTTP or ForSSE block is validated, then inert (decision 0047).
func ServeSSE ¶
ServeSSE curates impl and returns its MCP server as the isolated legacy SSE handler (decision 0039): the 2024-11-05 SSE wire served alone, hardened with the default limits or those WithLimits configures (E25) - query-token refusal, origin protection, rate and concurrency ceilings, the engine's own DNS-rebinding check. The opt-in WithSSE is required, unscoped or in ForSSE: without it ServeSSE refuses rather than serve, so SSE is impossible to enable implicitly, and the zero option list leaves every other entry point byte-identical.
A session lives as long as its hanging GET, which the handler keeps open whatever the caller's http.Server timeouts: it lifts the server's read and write deadlines for the stream (a server WriteTimeout then bounds each event write instead, so a client that stops reading is still cut), and it writes an SSE comment line to a stream that has been quiet for up to 15 seconds - never longer - so a proxy's idle timeout above that does not cut it either. Every other request - each message POST - keeps the server's timeouts, which must exceed the longest per-call deadline the handler serves. The deadlines are lifted through http.ResponseController, so middleware that wraps the handler must expose the writer it wraps with an Unwrap() http.ResponseWriter method, the net/http convention; behind a wrapper without one the server's timeouts still cut every session.
The open streams hold slots of their own, bounded by the limits' MaxSessions (a stream past it is refused 503), apart from the MaxInFlight slots every message POST takes, so open sessions never starve their own messages. When the http.Server the handler is mounted on begins shutting down, every open stream ends at once, so Shutdown need not wait out its context on streams that never go idle: the sessions close, and a call still running on one is cancelled, its answer unwritten - the legacy SSE wire answers on the stream.
opts configure the SSE server: every unscoped option must be honoured there. WithBearerAuth is not - the SSE wire runs each message POST under the stream opener's context, so it cannot bind a verified identity to each call - and a list that authenticates Streamable HTTP in ForHTTP while serving SSE is refused too, rather than serve SSE anonymously beside it (decision 0047).
Like Handler the signature has no error to return, so a missing opt-in, a curation or option problem, or a wiring failure panics with fmt.Errorf("mcp.ServeSSE: %w", err) over the one collected report (A5) before anything serves; NewSSEHandler returns it instead. The caller mounts the handler on their own http.Server and owns the bind: Main's -sse-addr fills a bare port's host with 127.0.0.1 (the loopback default), and an explicitly public address is the caller's documented choice.
func ToolSpecs ¶
ToolSpecs maps the curated surface onto the adapter's startup view: one tool spec per exposed operation, carrying the final name, the final docs, the resolved contract operation and the recorded defaults. It is the ONE mapping the server entry points and the in-process testing harness share, so the two cannot drift apart - the root owns it because the surface type is the root's and the adapter cannot import it back without a cycle.
The result type is the adapter's vocabulary, so this function is an in-repository seam: an external consumer can call it but cannot name what it returns. It is one of the in-repository seams decision 0053 lists. Tests pin the mapping field by field against the canonical loop in serve_test.go.
Types ¶
type Argument ¶ added in v0.5.0
type Argument struct {
// Name is the argument's name - its property in the input schema - or
// "" for an operation whose one argument is a struct, whose fields are
// the properties.
Name string
// Value is the decoded value, of the argument's Go type: the struct
// itself for a struct argument, never a pointer to it.
Value any
}
Argument is one decoded argument of a call, as Hooks.Arguments sees it.
type Audio ¶
Audio is an audio block: binary data with its MIME type. The wire form is `{"type":"audio",...}`, the engine's own marshaling of the converted block.
func (Audio) MarshalJSON ¶
MarshalJSON writes the wire shape the protocol carries for an Audio block.
type AuditRecord ¶
type AuditRecord struct {
// Subject is who ran the call, or "" when anonymous.
Subject string
// Tenant is the tenant the identity belongs to, or "" when none.
Tenant string
// Tool is the SOURCE name of the invoked operation.
Tool string
// Requested is the alias wire name the call arrived over, or "" for a
// direct canonical call.
Requested string
// Approval is the approval stage's decision for the call.
Approval policy.Approval
// Outcome is "ok" or the failing error's code.
Outcome string
// CorrelationID ties the record to the call's error.
CorrelationID string
// Duration is the pipeline's wall time.
Duration time.Duration
// Attempts counts how many times the implementation ran.
Attempts int
// Replayed reports whether the call observed a recorded outcome
// instead of running the implementation.
Replayed bool
}
AuditRecord is one call's finished audit record (DESIGN_SPEC.md H35): the secret-free accountability the pipeline's finished outcome carries. It mirrors the internal record's H35 fields so the mapping is field-for-field; the pipeline constrains every value before it arrives here - the outcome is the neutral code, the approval one of the closed vocabulary, the requested name one of the registration-bound alias names or empty - so a record can never carry a secret the pipeline refused to ship.
type AuditSink ¶
type AuditSink interface {
// Append stores one finished audit record.
Append(record AuditRecord) error
}
AuditSink is the operator's durable audit boundary (DESIGN_SPEC.md H35, J41): the narrow hook a durable audit system fills. It receives the finished public record of every call, success or failure, exactly once per call, on the final outcome. The zero value records nothing: a nil sink maps to nil, so a server built without one runs exactly as before. Use WithAuditSink to wire one onto an entry point. The hook must be safe for concurrent use and must never block - front it with a policy.Stream for bounded best-effort delivery.
type AuditSinkFunc ¶
type AuditSinkFunc func(record AuditRecord) error
AuditSinkFunc adapts a function to AuditSink.
func (AuditSinkFunc) Append ¶
func (f AuditSinkFunc) Append(record AuditRecord) error
Append stores one finished audit record.
type Backend ¶
type Backend[API any] struct { // contains filtered or unexported fields }
Backend is one imported backend: the typed API a bridge linked - FromREST over an iqlink API structure, FromOpenAPI over an OpenAPI document - ready to hand to Curate or straight to an entry point, or the construction problems that stop it serving.
A backend is a single value, so an import composes in one expression, as DESIGN_SPEC.md §4's second snippet and D17 write it:
mcp.Main(mcp.FromREST[GitHub]("https://api.github.com"))
mcp.Main(mcp.Curate(mcp.FromREST[GitHub]("https://api.github.com"),
mcp.Only("Issues.List", "Issues.Create"),
mcp.Fix("Issues.List.per_page", 20),
mcp.Auth(oauth.PerUser(githubTokenExchange)),
))
Construction problems are deferred onto the value instead of a second return (decision 0049, the decision 0013 pattern): Backend.Err reports them, and Curate, Main, Run, Serve, NewHandler, Handler, NewSSEHandler, ServeSSE and the testing package's harness fold them into the one collected report (A5) instead of serving - a backend with problems never serves. Curating one still validates the directives against the API's operations wherever the API's shape is known, so one report names every problem to fix.
Curating a backend also tells the curation where the backend is: an entry-less oauth.PerUser delegation binds to the backend's own destination - the scheme, host and port of its base URL - and no other (policy.PerUserSource.ForBackend). A backend whose options set a static Authorization header cannot also be curated with Auth: one credential presents per backend, never whichever a binding happens to permit.
Backend.API hands out the typed API for code that calls the backend itself - a facade composing several backend calls, a test - and a program that checks Backend.Err first may use it like any iqlink import. A Backend is immutable and safe for concurrent use.
func FromOpenAPI ¶
func FromOpenAPI(spec []byte, baseURL string, opts ...FromOpenAPIOption) *Backend[any]
FromOpenAPI binds one OpenAPI JSON document as a runtime-linkable API against the operator-selected baseURL and returns it as one Backend value - the same single-value shape FromREST has (decision 0049) - to curate or serve directly:
mcp.Main(mcp.Curate(mcp.FromOpenAPI(spec, "https://api.example.com"),
mcp.Only("listIssues")))
Load validates the spec against the frozen profile (unsupported/unknown constructs fail with their classification) - every operation, or only those FromOpenAPIWithOperations names, and with FromOpenAPIWithSkipUnsupported a refused operation is left out and reported (Backend.OpenAPISkipped) instead; Compile maps every operation to its StructOf argument/result model with no generated source; the bridge then builds one anonymous API struct and links it with rest.API over the composed client. Binding performs no network I/O - an unreachable baseURL is a call-time failure the outbound mapping classifies honestly - and writes no source file. baseURL is authoritative: the spec's servers entries were counted and ignored at load. Security requirements ride as metadata (Backend.OpenAPIOperations: CompiledOperation.Security and SecurityCarried): the operator satisfies them with FromOpenAPIWithHeader/WithClient configuration, never with tool arguments - credential-bearing parameter names were rejected at load.
Binding problems - every unusable option, an empty base URL, a spec the profile refuses, an operation that cannot be bound - are deferred onto the returned backend (A5): Backend.Err reports them, and the curation and the entry points report them in their one collected report instead of serving. The profile's typed refusal stays reachable through that report: errors.As finds its *openapi.ProfileError (Error.Unwrap). Backend.API is the bound document's anonymous struct, as a pointer; the operations' tool names are their operationIds, and their Go field paths - the directive addresses Curate also accepts - the exported field names the bridge derives from them.
func FromREST ¶
func FromREST[API any](host string, opts ...FromRESTOption) *Backend[API]
FromREST imports the REST backend at host as a typed Go API - it fills API's function fields with REST clients over the real api.Import driven by rest.API - and returns it as one Backend value, DESIGN_SPEC.md D17's one line:
mcp.Main(mcp.FromREST[GitHub]("https://api.github.com"))
and §4's second snippet, curated and delegated per user:
mcp.Main(mcp.Curate(mcp.FromREST[GitHub]("https://api.github.com"),
mcp.Only("Issues.List", "Issues.Create"),
mcp.Fix("Issues.List.per_page", 20),
mcp.Auth(oauth.PerUser(githubTokenExchange)),
))
The options are the ones decision 0006 records: WithHeader for a static key or service credential, WithClient for mTLS or a custom transport - plus the backend destinations guard (WithEgressGuard, E25) production hardening added. Per-user delegated credentials (D21, the §4 snippet's Auth stage, decision 0015) ride the pipeline's credential stage into this bridge: a credential the call resolved - through Auth on the curation - is presented as a Bearer token, per request, only where its binding's policy.Credential.Permit accepts the request's destination, so never across hosts or redirects. An entry-less oauth.PerUser binds to host's own destination when the backend is curated (decision 0049), so the snippet needs no destination of its own.
Construction problems are collected, not buried (A5), and deferred onto the returned backend instead of a second return (decision 0049): an empty host, every unusable option, and a rest: tag the linker refuses are reported by Backend.Err and, when the backend is curated or served, in the one collected report - a backend with problems never serves. Import never dials the backend at construction - an unreachable host is a call-time failure, which is exactly what the bridge's error mapping (below) classifies honestly. A nil option is ignored.
Serving the backend needs an identity for a per-user delegation and an approval for a destructive operation, which the entry points' options supply: mcp.WithStdioIdentity or mcp.ForHTTP(mcp.WithBearerAuth(...)), and mcp.WithApprover or mcp.WithClientApproval. Without them the served calls fail closed with an error naming those options.
Egress guard (DESIGN_SPEC.md E25) ¶
Every backend request is judged before it leaves, and every redirect hop again - through the client's CheckRedirect before the hop is followed and through the transport before the wire carries it, with at most ten hops followed. The judgment takes the destination the URL names, resolved when it is a hostname and classified straight from the string when it is an IP literal. The posture:
- Always refused, whatever the configuration: cloud-metadata, link-local, multicast and unspecified destinations. They are never legitimate backends, so no option - an allowlist entry included - can enable them.
- Loopback and private destinations are reachable with no guard configured: offline tests and local development target loopback backends, and E22's production posture expects the operator's explicit allowlist rather than an invented one. With a guard configured through WithEgressGuard, the guard's own precedence judges them: an empty allowlist means every resolved address must be global, an explicit entry waives the class rule for the destination it names, and the denylist overrides.
A hostname destination must resolve in both tiers: a name that fails to resolve, or lands on no address, is refused without evidence of where it lands. Resolution rides the request's context through net.DefaultResolver - WithClient is the seam for a caller who resolves differently. The guard composes outermost: a refused destination never sees a header, a credential or a wire byte. The judgment binds the addresses the resolver returns at check time; every new connection's dial is pinned to exactly those addresses, and a pooled connection is reused without a dial (R3). A transport that is not an *http.Transport, or whose dial bypasses DialContext (DialTLS/DialTLSContext, an external HTTP/2 or HTTP/3 dialer), is judged but not pinned.
Backend-error mapping (decision 0006, RL-2) ¶
The bridge does NOT forward the REST client's error. It wraps every imported function once, at construction, so that a failed backend call reaches the tool pipeline as the bridge's own mapped error: the backend's status, its message and any Retry-After are preserved (upstream 5fb3b401 restored exactly this material - RL-2), classification is chosen by status and Retry-After - never by message text - and the configured credentials are scrubbed from the error text. The mapping is type-based: no schema, no tag parsing, no JSON re-decode per call (J43). It is not reflection-free - the wrapper adds one reflect.Value.Call or reflect.Value.CallSlice per invocation on top of the linker's MakeFunc trampoline; that per-call cost is measured by the repository's benchmarks, not asserted here.
Safe-message stance (F28) ¶
The backend's body is untrusted backend content (E26: trusted server instructions versus untrusted backend content are separated), so the bridge never renders it into the model-visible message. The invoke pipeline owns the safe message ("the operation failed") and files the mapped error's text - which carries the status and the backend's message; the Retry-After is not part of the text, it is reachable through the mapped error's RetryAfterHTTP method - as redacted operator diagnostics, with the classification (invocation, retryable) set from the status through the Code and Retryable methods the pipeline's error mapping reads. The configured credentials are scrubbed from the mapped text here, and the call's resolved credential is scrubbed by the pipeline's redactor, which is built from that same resolved value. The mapped error carries everything a mapping of the backend's detail into the tool-result message needs (status, message, retry-after), so F28's stable code, safe message and retryability are realizable for a REST-bridged backend without guessing from message text - the outcome decision 0006's post-5fb3b401 update anticipated; a public typed hook for that mapping is not provided. See TestCuratedSnippetShapeOverREST.
Residual exposure in operator diagnostics ¶
Two surfaces of a mapped failure are NOT scrubbed, and both are operator-facing only - the model never sees them (F28). The mapped error's Unwrap exposes the backend's raw cause: a caller who unwraps past the mapping (errors.As through the neutral error's cause chain) reaches the original error text, which may carry a credential the scrubbed mapped text does not. And a host with embedded userinfo (https://user:token@backend.example) is not scrubbed from a transport failure's text. An operator who forwards raw causes or host configuration onward should treat both as unredacted.
The exported function fields of API must carry rest: tags describing each endpoint, and args: tags naming their arguments - unless the package that declares API embeds its source for iqlink (a Source() fs.FS method, decision 0045). The on-disk fallback that names the arguments of a program built with its source on disk does not reach an import: it locates the source through the functions bound in the structure, and FromREST binds every one of them through the linker, so an API with neither is refused at curation, naming both fixes. See the restGitHub fixture in fromrest_test.go for the shape.
func (*Backend[API]) API ¶
func (b *Backend[API]) API() API
API returns the typed API the bridge linked: its function fields call the backend through the bridge's client, with its egress guard, its error mapping and the call's resolved credential. A backend whose construction found problems (Backend.Err) returns the zero API, whose functions are nil; check Err before calling through it. For FromOpenAPI the API is the bound document's anonymous struct, as a pointer.
func (*Backend[API]) Err ¶
Err reports the backend's construction problems: nil when the backend is linked and servable, or the one collected *Error - every problem the import found, headed "invalid backend" - when it is not. The entry points and Curate report the same problems in their own collected report, so a program that hands the backend straight to them need not check Err itself.
func (*Backend[API]) OpenAPIOperations ¶
func (b *Backend[API]) OpenAPIOperations() []openapi.CompiledOperation
OpenAPIOperations returns the operations FromOpenAPI compiled and bound, in operation-ID order: the classification, placements and result types each tool uses. It is nil for a FromREST import and for a binding that found problems. The slice is a copy.
func (*Backend[API]) OpenAPISkipped ¶
OpenAPISkipped reports the operations FromOpenAPIWithSkipUnsupported left out of a FromOpenAPI binding, each with the profile's refusal, by path then method. It is nil when nothing was skipped, for a FromREST import, and for a binding without the option. The slice is a copy.
type CallResult ¶
type CallResult struct {
// Text is the first text content block the result carried, or ""
// when it carried none.
Text string
// Structured is the structured result's captured JSON bytes, or
// nil when the tool produced no data. They are the structuredContent
// as the server sent it: a non-object result from a server of this
// package arrives in its object envelope {"result": <value>}
// (decision 0046), which [Import] unwraps and Call does not.
Structured json.RawMessage
// IsError reports whether the tool answered with an isError
// result: the model-visible failure, not a protocol refusal.
IsError bool
}
CallResult is one successful tool call's outcome: the text content the server rendered and the structured JSON's captured bytes. The bytes are kept raw so the typed binding decodes numbers exactly over the values the SDK handed over losslessly; nested integers at or above 2^53 arrive rounded (a documented known limitation).
type CallSample ¶
type CallSample struct {
// Operation is the SOURCE name of the invoked operation.
Operation string
// Outcome is "ok" or the failing error's code.
Outcome string
// Gate is "", "breaker", "bulkhead" or "backend".
Gate string
// Attempts counts how many times the implementation ran for this call.
Attempts int
// Replayed reports whether the call observed a recorded outcome instead
// of running the implementation.
Replayed bool
// Duration is the pipeline's wall time.
Duration time.Duration
// Backend is the implementation's wall time summed over attempts.
Backend time.Duration
// QueueDepth is the bulkhead's waiting count when the call entered the
// gate.
QueueDepth int
}
CallSample is the one metrics event a call emits (DESIGN_SPEC.md H34): the bounded labels and wall times the pipeline's finished outcome carries. It mirrors the internal sample's fields so the mapping is field-for-field; the internal constructor clamps the outcome and gate onto their vocabularies, so a label can never carry a raw message.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the explicitly connected, caller-owned production session: what Connect returns and Import binds against. The caller closes it - usually with defer - after Import and every call completes.
func Connect ¶
func Connect(ctx context.Context, transport ClientTransport, opts ...ClientOption) (*Client, error)
Connect connects to the remote server over the given transport, performing the initialize handshake under ctx: cancellation aborts the handshake and cleans up - no leaked session or goroutine. The returned client is caller-owned: the caller closes it.
func (*Client) Call ¶
func (c *Client) Call(ctx context.Context, name string, args json.RawMessage) (CallResult, error)
Call invokes the named tool with the given arguments object: either a JSON object or nil for the empty arguments. Calls may run concurrently over one client. There is no automatic retry: an ambiguous transport failure returns, and the caller decides. The transport's own bearer token (ClientHTTPOptions Token) is redacted from the result's text and structured bytes and from an error's message: a server that echoes the Authorization header it received never hands the client's credential on to whoever reads the result.
func (*Client) Catalog ¶
Catalog lists the remote server's tools in bounded pages and returns the observed snapshot: what THIS client saw, authenticated as its transport authenticates it. It performs I/O - unlike Import - over the caller's context, inside the discovery page/tool bounds (ADR 0031). The snapshot carries no canonical source: the observed scope's rule.
func (*Client) Close ¶
Close ends the session. It is idempotent: the first call's outcome is every call's outcome.
func (*Client) Inspect ¶
func (c *Client) Inspect() ServerInfo
Inspect reports what the initialize handshake announced. It reads the result Connect retained; it makes no wire call.
type ClientHTTPOptions ¶
type ClientHTTPOptions = protocol.ClientHTTPOptions
ClientHTTPOptions configures one HTTP client transport. See ClientHTTP.
type ClientRoot ¶
type ClientRoot struct {
// URI identifies the root, typically a file:// URI.
URI string
// Name is the client's optional human-readable name for it.
Name string
}
ClientRoot is one filesystem root the client declared: an address, never an authority.
func ClientRoots ¶
func ClientRoots(ctx context.Context) ([]ClientRoot, error)
ClientRoots fetches the calling client's filesystem roots (DESIGN_SPEC.md B8). A client that declares no roots capability yields an empty list and is never asked, and so does every call outside a served one; so does an answer over the 1 MiB bound. Each URI and name is redacted over the call's credential.
The roots are untrusted client input: they say where the client would like the server to look, not what the caller may touch. Never let a root widen what an operation may read or write - authorization stays the server's (auth: tags, WithAuthorization) - and resolve a path against your own allowlist, not against a root.
The error contract is Sample's: return a non-nil error as it is or wrapped with %w, and ask before any side effect - on protocol 2026-07-28 and later the call runs again from the start with the answer, and an implementation that swallows the error goes on with no roots. A cancelled call's fetch returns the context's error.
Roots are deprecated by the MCP specification as of protocol 2026-07-28 (SEP-2577) and stay functional through its deprecation window of at least twelve months.
type ClientTransport ¶
type ClientTransport = protocol.ClientTransport
ClientTransport is a wire a client connects over: the adapter's sealed production-client handle re-exported under the root's name - the alias pattern Renderer uses - so an entry point's transport argument is nameable without importing the adapter. A server Transport cannot be used where a ClientTransport is expected, and vice versa.
func ClientHTTP ¶
func ClientHTTP(endpoint string, opts ...ClientHTTPOptions) (ClientTransport, error)
ClientHTTP builds the Streamable HTTP client transport for the given endpoint: an absolute http or https URL. Credentials in opts are bound to that destination: a redirect to another host drops the bearer token rather than forwarding it. No identity metadata is sent: identity on this path comes from the HTTP credentials alone.
func ClientStdio ¶
func ClientStdio(in io.ReadCloser, out io.WriteCloser) (ClientTransport, error)
ClientStdio builds the stdio client transport over the given streams: requests are written to out, responses read from in. Both streams are required. They stay caller-owned: Close ends the session, and the caller closes its streams. Never the process's own stdin/stdout - those belong to the server side - and never a subprocess: process creation is the CLI's explicit --command/argv option (the iqmcp command's call and inspect), not catalog data.
type Content ¶
type Content interface {
// contains filtered or unexported methods
}
Content is one block of protocol content: text, an image, audio, a resource link or an embedded resource. A tool that returns a single Content or a []Content emits it as the protocol's content blocks; a tool that returns something else never produces these blocks.
type Deprecation ¶
type Deprecation struct {
// Message explains why the operation is deprecated and what to do.
Message string
// Replacement names the canonical successor, or "" when none exists.
Replacement string
// Since and Removal are informational version strings, or "" when
// unset. Neither drives a timed removal.
Since string
Removal string
}
Deprecation carries one operation's deprecation metadata (ADR 0033): a human-readable message, an optional replacement name and optional since/removal version strings. It publishes in descriptions and catalog metadata; it never removes anything implicitly.
type Directive ¶
type Directive interface {
// contains filtered or unexported methods
}
Directive is one element of a Curate call: a curation directive - Only, Except, Rename, Describe, Fix or Hide - the production exposure selection, Production, the credential source selection, Auth, or an operation's own call deadline, Timeout. The set is sealed: these constructors are the only way to build one, so a Curate call reads as a complete statement of intent.
The type is deliberately not a type alias of policy.Directive. Policy's directive set is sealed to its own constructors and cannot admit a root-implemented mode selection or a credential source, yet the exposure mode and the credentials must join the same stream so that one Curate call stays one statement: two Production selections or two Auth selections are one collected problem each, and no selection at all is the expose-all default with no credential provider. Wrapping each policy directive here keeps policy's seal intact while giving callers one sealed set at the root; the two root-implemented selections are stripped before policy sees the stream, so the policy directive engine never sees either.
func Alias ¶
Alias names one additional public name for the canonical operation addressed at source (a SOURCE name or a Go field path; see Curate). The alias inherits the canonical operation's auth, approval, credentials, retry, dedup and budget behavior; it is listed and callable under its own final name and resolves to the canonical operation at execution.
func Auth ¶
func Auth(src policy.CredentialSource) Directive
Auth selects the credential source the server resolves its calls' backend credentials from (DESIGN_SPEC.md D21, §4's second snippet, decision 0015): the public oauth package's PerUser builds the per-user delegated source whose exchange produces the backend token - bound, when it names no destination of its own, to the curated Backend's host (decision 0049) - policy.ProviderSource wraps a server-configured provider - static credentials, a secret manager - and the entry points wire the source's provider onto the runner they serve with. Auth is the one way a served program configures backend credentials, so no option can contradict it.
Auth is a selection like Production, not a policy curation directive: the policy directive engine never sees it. It joins the same directive stream so one Curate call stays one statement of intent, and it obeys the same collected-problem discipline: a second Auth is an ambiguity problem (which source governs is not decidable), a nil source is a problem of its own, and the selected source's construction problems - a nil or broken exchange, an entry that binds no destination, an entry-less PerUser with no curated backend to bind to - are collected onto the surface and reported through Surface.Err, so a broken delegation is a startup failure at the entry points, never a broken call.
func Budget ¶
Budget caps the serialized output of the operation addressed at name (a SOURCE name or a Go field path): at most maxBytes serialized bytes, maxItems items and maxTokens approximate tokens, each within its ADR 0032 bound.
func Deprecate ¶
func Deprecate(source string, info Deprecation) Directive
Deprecate marks the operation addressed at source (a SOURCE name or a Go field path) as deprecated with the given metadata. Deprecation is advisory: it never removes the operation or schedules one.
func Describe ¶
Describe replaces the documentation of the operation addressed at name (a SOURCE name or a Go field path). Describing one operation twice with different text is a collected problem.
func Except ¶
Except removes the named operations from the surface; every other operation keeps its exposure. Names are SOURCE names or Go field paths. Excepting an operation that Only keeps is a conflict and is reported as a collected problem.
func Fields ¶
Fields keeps exactly the named output fields of the operation addressed at name (a SOURCE name or a Go field path; see Curate). Paths are dot-separated property paths into the result object (e.g. "owner.login"); an empty path list is a collected problem, not "keep everything".
func Fix ¶
Fix pins one argument of an operation to value (DESIGN_SPEC.md D20, decision 0049): the argument leaves the tool's input schema - a prompt's argument list likewise - every call runs with value, and a call that supplies the argument itself is refused with an error naming it, so the model can never move what the curation fixed. The path is "<source name>.<argument name>": its final dot-separated segment is the argument name and everything before it is the SOURCE name, because source names may contain dots themselves - "admin.deep.purge" is an operation, so "admin.deep.purge.dry_run" would fix its dry_run argument. The operation may be written as its Go field path instead, as DESIGN_SPEC.md §4 writes "Issues.List.per_page" for the per_page argument of issues.list; the argument keeps its own name. A path that more than one operation-and-argument split can resolve is refused as ambiguous: argument names may not contain dots, or address the argument differently. Fixing a resource argument its URI template binds is a collected problem, since every read would supply it.
func Hide ¶
Hide removes the operation addressed at name (a SOURCE name or a Go field path) from the surface. Hiding is not authorization (DESIGN_SPEC.md E24): enforce authorization separately.
func Only ¶
Only keeps exactly the named operations and denies exposure to every other one. Names are SOURCE names - the resolved names the contract produced, such as "current" or "admin.reset" - or the operations' Go field paths, such as "Admin.Reset" (see Curate). Two Only directives must name the same set of operations; an Only with no names exposes nothing.
func Paginate ¶
Paginate normalizes pagination for the operation addressed at name (a SOURCE name or a Go field path) with an explicit page size in (0, 100].
func Production ¶
Production selects the deny-by-default exposure mode: only the named operations (SOURCE names or Go field paths) are exposed, and every other one is refused. An empty allowlist, an allowlist name that matches no operation, and a second Production selection - which would make the mode ambiguous - are all collected problems. Without Production, Curate exposes everything and logs a loud warning once.
func Redact ¶
Redact redacts exactly the named output fields of the operation addressed at name (a SOURCE name or a Go field path). Redaction replaces the value with the redaction marker and never removes the key.
func Rename ¶
Rename gives the operation addressed at from - a SOURCE name or a Go field path - the new final name to. Renaming never changes addressing: later directives still use the SOURCE name or the field path.
func Timeout ¶
Timeout gives the operation addressed at name - a SOURCE name or a Go field path, see Curate - its own per-call deadline d (DESIGN_SPEC.md F27), in place of the server's CallTimeout: policy.DefaultLimits' 30 seconds on every served transport unless WithLimits replaces it. d may be shorter than the server's, to fail a call fast, or longer, for an operation that legitimately runs long without raising every call's deadline; Run and Main widen their http.Server timeouts, and the stdio drain its wait, to the longest one served. It applies to the operation however it is served - as a tool, prompt or resource, under every alias, and in the testing harness.
d must be positive and at most one hour, the ceiling policy.Limits puts on every call deadline, and an operation takes one Timeout: an unknown name, a duration outside those bounds and a second Timeout for one operation are collected problems. A call past its deadline is answered with the retryable "timeout" error while its implementation's context is cancelled; see "Deadlines, cancellation and side effects" in the package documentation for what cancellation cannot undo.
type ElicitRequest ¶
type ElicitRequest struct {
// Prompt is the question the client shows its user.
Prompt string
// Schema is the answer's shape: a flat JSON Schema object of
// primitive properties, as the MCP elicitation vocabulary allows (a
// client refuses any other, which reads as a failure); nil asks for a
// bare confirmation.
Schema map[string]any
}
ElicitRequest asks the calling client for input the server will not invent (DESIGN_SPEC.md B8).
type ElicitResult ¶
type ElicitResult struct {
// Accepted reports that the client supplied the input. False covers
// every other case alike: declined, dismissed, cancelled or timed out,
// answered over the 1 MiB bound, a client without elicitation, or a
// question still on its way to it (see [Elicit]).
Accepted bool
// Values is the supplied input, keyed by the schema's property names.
Values map[string]any
}
ElicitResult is the client's untrusted answer; Values is set only when Accepted.
func Elicit ¶
func Elicit(ctx context.Context, req ElicitRequest) (ElicitResult, error)
Elicit asks the calling client's user for input (DESIGN_SPEC.md B8) and returns the answer. A client that declares no elicitation capability answers with Accepted false and is never asked, and so does every call outside a served one. The prompt and the schema are redacted over the call's credential before they leave the server, and so are the values that come back.
The values are untrusted client input: the client may send anything, and on protocol 2026-07-28 and later nothing on the server checks them against Schema, so check each value's type and range before using it. The question is keyed apart from the server's own approval question: no answer to it ever approves a destructive operation, which only WithApprover and WithClientApproval decide, and asking "may I?" through Elicit is not approval.
The error contract is Sample's: return a non-nil error as it is or wrapped with %w, and ask before any side effect - on protocol 2026-07-28 and later the call runs again from the start with the answer, and an implementation that swallows the error goes on with Accepted false.
Elicitation is deprecated by the MCP specification as of protocol 2026-07-28 (SEP-2577) and stays functional through its deprecation window of at least twelve months.
type EmbeddedResource ¶
type EmbeddedResource struct {
Resource *Resource `json:"resource"`
}
EmbeddedResource is a block embedding a resource's contents: its Resource's Text carries text (a redactable surface) and its Blob carries binary data (never text-redacted).
func (EmbeddedResource) MarshalJSON ¶
func (e EmbeddedResource) MarshalJSON() ([]byte, error)
MarshalJSON writes the wire shape the protocol carries for an embedded resource block.
type Error ¶
type Error struct {
Problems []Problem
// contains filtered or unexported fields
}
Error reports every problem found while curating, and - at an entry point - while validating its options. Curate collects them all rather than stopping at the first (DESIGN_SPEC.md A5, E22), so one run tells the author everything they have to fix; the problems are deferred onto the Surface Curate returns, and the entry points report them instead of serving a surface that carries any. An entry point folds its option problems into the same report (decision 0047): Problem.Where then names the option, as "option WithBearerAuth" or "option ForHTTP(WithBearerAuth)". A Backend's construction problems join the same report when it is curated or served (decision 0049); Problem.Where then names the bridge, as "FromREST" or "FromREST option WithHeader".
func (*Error) Error ¶
Error renders every collected problem as a deterministic bullet list, headed "invalid curation", "invalid server configuration" when the report carries option problems, or "invalid backend" for Backend.Err.
func (*Error) Unwrap ¶
Unwrap returns the typed errors behind the report's problems, where a problem was rendered from one: a FromOpenAPI document the profile refused (its *openapi.ProfileError, with the stable code and class), or a rest: tag the iqlink linker refused in FromREST. errors.Is and errors.As reach them through the one collected report, from Backend.Err, Surface.Err and the entry points alike (decision 0049). It is nil when no problem carries a typed cause.
type EventStore ¶
type EventStore interface {
// Open ensures the stream's storage exists, ready to record and replay.
Open(ctx context.Context, sessionID, streamID string) error
// Append records one event's data - nil included: the engine appends a
// nil priming event so the store's indexes align with the wire's event
// IDs - at the next index of the stream.
Append(ctx context.Context, sessionID, streamID string, data []byte) error
// After replays the stream's events after index, which the engine
// parses out of a client's Last-Event-ID (-1 replays the whole
// stream). It yields either every event after index or one immediate
// error - never a partial replay: an error wrapping [ErrEventsPurged]
// when events after index were evicted, and an error for an unknown
// session or stream, or an index past the stream's last event.
After(ctx context.Context, sessionID, streamID string, index int) iter.Seq2[[]byte, error]
// SessionClosed discards the session and every stream it held. The
// engine calls it when a session ends, but a store must not rely on
// it: it reclaims idle sessions on its own too.
SessionClosed(ctx context.Context, sessionID string) error
}
EventStore records a stateful session's stream events so a client that loses a stream resumes it from its Last-Event-ID (DESIGN_SPEC.md B7, B10). Its method set is the pinned protocol engine's event-store contract, which MemoryEventStore and the store/redis and store/sql modules implement; WithSessions hands one to the Streamable HTTP wire.
Every method must be safe for concurrent use. A session ID and a stream ID are opaque addresses, never credentials: the store keys by them and authorizes nothing (B10).
type FromOpenAPIOption ¶
type FromOpenAPIOption func(*fromOpenAPIConfig)
FromOpenAPIOption configures one FromOpenAPI binding. The set mirrors the FromREST seam the bridge reuses: a static header for a service credential (FromOpenAPIWithHeader, D21), a caller-supplied client for mTLS or a custom transport (FromOpenAPIWithClient), and the backend destinations guard (FromOpenAPIWithEgressGuard, E25). A nil option is ignored.
func FromOpenAPIWithClient ¶
func FromOpenAPIWithClient(c *http.Client) FromOpenAPIOption
FromOpenAPIWithClient uses a caller-supplied HTTP client - for mTLS, a custom transport, or a shared connection pool. A nil client is a configuration problem FromOpenAPI collects (A5). The client is never mutated: the bridge composes its transports on shallow copies. Every new connection's dial is pinned to exactly the judged addresses through the bridges' pinned dial; a pooled connection is reused without a dial (R3); a transport that is not an *http.Transport, or whose dial bypasses DialContext (DialTLS/DialTLSContext, an external HTTP/2 or HTTP/3 dialer), is judged but not pinned.
func FromOpenAPIWithEgressGuard ¶
func FromOpenAPIWithEgressGuard(guard policy.Destinations) FromOpenAPIOption
FromOpenAPIWithEgressGuard configures the destinations guard the bridge enforces on every backend request and every redirect hop (E25) - the same guard FromREST takes: refused destinations never see a header, a credential or a wire byte, and the always-blocked classes are refused with or without it. The zero policy.Destinations passed explicitly is a configured guard that permits nothing.
func FromOpenAPIWithHeader ¶
func FromOpenAPIWithHeader(name, value string) FromOpenAPIOption
FromOpenAPIWithHeader sets a header on every request to the backend - how a static key or service credential is supplied (D21). Credentials come from server configuration, never from tool arguments; the value is put on the wire (via the FromREST header stage) - to the base URL's own destination only, never a redirect's other host - and appears nowhere in the tool catalogue. Two headers with the same name are a collected binding problem, and so is a static Authorization header curated with Auth (decision 0049).
func FromOpenAPIWithOperations ¶
func FromOpenAPIWithOperations(ids ...string) FromOpenAPIOption
FromOpenAPIWithOperations binds only the named operations (their operationIds) and validates only them against the profile: a construct outside the profile in an operation you did not name - or in a path or security scheme none of them uses - no longer fails the whole document. Repeated options add to the selection. An empty or blank operationId, an empty selection, and an operationId the document does not declare are binding problems. The selection is what is bound, not what is exposed: curate the backend as usual (Curate, Production, Only).
func FromOpenAPIWithSkipUnsupported ¶
func FromOpenAPIWithSkipUnsupported() FromOpenAPIOption
FromOpenAPIWithSkipUnsupported leaves out every operation the profile refuses - at load or at compilation - instead of failing the binding, and reports each one, with its refusal, in Backend.OpenAPISkipped. A document whose every operation is refused still fails, and so does a refusal of the document itself (its version, its bounds, a duplicate operationId). Combined with FromOpenAPIWithOperations, a selected operation the profile refuses is skipped and reported too.
type FromRESTOption ¶
type FromRESTOption func(*fromRESTConfig)
FromRESTOption configures one FromREST import. The set is the minimum decision 0006 records - what api.Import's connection parameter can express - plus what production hardening added to it: a static header for a service credential (WithHeader, D21), a caller-supplied client for mTLS or a custom transport (WithClient), and the backend destinations guard (WithEgressGuard, E25). A nil option is ignored.
func WithClient ¶
func WithClient(c *http.Client) FromRESTOption
WithClient uses a caller-supplied HTTP client - for mTLS, a custom transport, or a shared connection pool. A nil client is a configuration problem FromREST collects (A5). Header options compose over this client's transport and its settings are kept, whichever order the options appear in. The client is never mutated: the bridge clones a *http.Transport through the bridges' shared pinning transport and composes its transports on shallow copies, so the caller's transport settings ride the clone. CloseIdleConnections reaches the clone's own idle pool through the composed stack, not the caller's transport instance. Every new connection's dial is pinned to exactly the judged addresses through the bridges' pinned dial; a pooled connection is reused without a dial (R3); a transport that is not an *http.Transport, or whose dial bypasses DialContext (DialTLS/DialTLSContext, an external HTTP/2 or HTTP/3 dialer), is judged but not pinned.
func WithEgressGuard ¶
func WithEgressGuard(guard policy.Destinations) FromRESTOption
WithEgressGuard configures the destinations guard the bridge enforces on every backend request and every redirect hop (DESIGN_SPEC.md E25's SSRF-resistant backend destinations). The guard composes outermost - a refused destination never sees a header, a credential or a wire byte - and the always-blocked classes (cloud metadata, link-local, multicast, unspecified) are refused with or without it: they are never legitimate backends, and no configuration can permit them. What the guard adds is the configuration-dependent half: loopback and private destinations, reachable with no guard configured (offline tests and local development target loopback backends, and E22's production posture expects the operator's explicit allowlist rather than an invented one), are judged by policy.Destinations.CheckEgress's precedence once a guard is here. The zero policy.Destinations passed explicitly is a configured guard that permits nothing - fail closed, as everywhere in this package.
func WithHeader ¶
func WithHeader(name, value string) FromRESTOption
WithHeader sets a header on every request to the backend - how a static key or service credential is supplied (DESIGN_SPEC.md D21). Credentials come from server configuration, never from tool arguments; the value is put on the wire and appears nowhere in the generated tool catalogue. The header reaches the host's own destination only - its scheme, host and port - and never a redirect's other host (decision 0049). A static Authorization header and a curation's Auth are one credential too many for one backend: curating the two together is a collected problem. Headers compose: several WithHeader options each contribute their header, on a request clone - the bridge never mutates a caller's request (upstream RL-14's defect, worked around here locally). Composition is order-independent: the headers ride on whatever client the options configure, WithClient included, because FromREST composes them once after the option loop. Two headers with the same name are a collected construction problem (A5) - which of two values for one header name should win is not decidable, so the bridge refuses the combination rather than resolving it by option order.
type Hooks ¶ added in v0.5.0
type Hooks struct {
// Arguments rewrites a call's decoded arguments before the
// implementation receives them. args is the call's own copy, in the
// implementation's parameter order: rewrite an argument by assigning
// its Value. A fixed argument (Fix) is the curation's and is not
// offered.
//
// It runs after authorization and approval and before the credential
// is resolved and the call deduplicated: only a call the server would
// run reaches it, it reads the caller with [IdentityFromContext], and
// [CredentialFromContext] reports none - none is resolved yet. Every
// attempt of a retried call receives its rewrite. A call
// [WithIdempotency] replays runs it too, but deduplication compares the
// arguments as the caller sent them, never the rewrite.
//
// The rewrite must keep the operation's contract: the arguments keep
// their names and order, each Value must be assignable to the
// argument's type (nil only where the type admits it), the rewritten
// arguments must pass the input schema's constraints as a caller's
// must - a named argument rewritten to nil is absent - and a keyed
// call's idempotency key must stay as the caller sent it. A slice, a
// map or a pointee changed in place is a rewrite and is checked too.
// What is checked is the caller's arguments with the hook's changes
// applied: a field the hook left alone stands as the caller sent it,
// so a struct field tagged omitempty that the caller left out, or an
// omitzero field the caller sent at its zero, is never judged by the
// form encoding/json would write for it. A
// rewrite that breaks any of these fails the call with an "unknown"
// tool error that says the server's hook produced it, and the
// implementation does not run.
Arguments func(ctx context.Context, operation string, args []Argument) error
// Result rewrites a call's typed result after the implementation
// returned it, and returns the result the call answers with. It runs
// once, on the final successful attempt's result - a streamed result
// drained into its slice, a nil iter.Seq or iter.Seq2 as the nil slice
// - and before result shaping and rendering. A
// call that failed, an operation that returns no data, and a call
// [WithIdempotency] replays never reach it: a replay answers what the
// recorded call answered, rewrite included.
//
// Its context carries the caller ([IdentityFromContext]) but never the
// call's credential: [CredentialFromContext] reports none. The result
// it receives is not redacted - a typed value cannot be scanned safely
// - so a credential the implementation echoed into it is there in the
// clear: keep result, and anything read from it, out of logs, stores
// and outgoing calls, and pass it on only through the value returned.
// What it returns is rendered and redacted against the call's
// credential like the implementation's own result, so such a
// credential never reaches a client through the rewrite.
// The value must be assignable to the operation's result type (nil
// only where the type admits it) - the output schema advertises that
// type - or the call fails with an "unknown" tool error. In the
// testing harness under its WithReplay option, result is the recorded
// value, as the operation's result type when the recording decodes
// into it.
Result func(ctx context.Context, operation string, result any) (any, error)
}
Hooks are the typed transform hooks WithHooks installs (DESIGN_SPEC.md J41). Each is optional; each runs once per call - never once per attempt of a call WithRetries retries - for every operation the server serves, tools, resources and prompts alike, and receives the operation's SOURCE name, the name WithRetries and the curation directives take. A call that asks its client a question on the multi-round-trip protocol revision (see Sample) runs again from the start with the answer, the hooks included. Concurrent calls run the hooks concurrently, so they must be safe for concurrent use.
type Image ¶
Image is an image block: binary data with its MIME type. The wire form is `{"type":"image",...}`, the engine's own marshaling of the converted block.
func (Image) MarshalJSON ¶
MarshalJSON writes the wire shape the protocol carries for an Image block.
type ListedTool ¶ added in v0.5.0
type ListedTool struct {
// Name is the tool's wire name, the one a call addresses.
Name string
// Description is the description tools/list advertises.
Description string
// Properties are the names of the tool's input schema's top-level
// properties, in order; none for a tool without arguments.
Properties []string
// AliasOf is the wire name of the canonical tool an alias resolves to
// ([Alias]) when the caller can list that tool too; empty for a
// canonical tool, and for an alias whose canonical tool the caller
// cannot list, which then stands as a tool of its own.
AliasOf string
}
ListedTool is one tool a caller can list and call, as tools/list describes it to that caller.
func ListedTools ¶ added in v0.5.0
func ListedTools(ctx context.Context) ([]ListedTool, bool)
ListedTools returns the tools the current call's caller can list and call on the server serving the call, in name order, and true: the tools tools/list answers that caller with - the curated, exposed tools, under their final names and descriptions, aliases included, filtered by the same authorization engine (WithAuthorization, or the default) for the identity the call was authorized as - less any whose call that engine denies the caller, and less the calling tool itself, under every name it has. Outside a served tool call - a unit test calling the implementation directly, a prompt or a resource read - it returns nil and false.
Discovery asks the engine about a tool by the name it is listed under, a call by the SOURCE name of the operation it runs (policy.Protected). The default engine, and any engine that decides alike for every name of an operation, answers both the same, so the answer is exactly the caller's tools/list less the calling tool; an engine that decides by name can list a renamed tool or an alias whose call it denies, and the answer leaves that tool out.
The answer is not a grant (E24): a listed tool is one the caller may see and call now, and its own call is authorized again when it is made. Each call computes its answer afresh, and the slices are the caller's own.
type MemoryEventStore ¶
type MemoryEventStore struct {
// contains filtered or unexported fields
}
MemoryEventStore is the bounded in-process EventStore: every session's streams live in this process's memory, bounded by the limits it was built over, and are lost when the process ends. Run and Main build and close one for WithSessions(nil); a program serving NewHandler or Handler builds it with NewMemoryEventStore, owns it, and closes it once the server has stopped. Its methods are safe for concurrent use.
func NewMemoryEventStore ¶
func NewMemoryEventStore(limits policy.Limits) (*MemoryEventStore, error)
NewMemoryEventStore builds the memory store over limits: SessionTimeout is the idle time after which a session's events are reclaimed - the same timeout the engine expires the session at, when the server serves the same limits - MaxSessions caps the sessions it holds (past it the least recently used is evicted), and MaxStreamEvents caps the events one stream retains for a resume (past it the oldest are evicted, and a resume into them is refused with ErrEventsPurged), and MaxRequestBytes caps one event (a larger one is refused), so the retained bytes of one stream are bounded by MaxStreamEvents × MaxRequestBytes. It refuses limits that fail policy.Limits.Validate, with that error, so a store is never unbounded. It starts one janitor goroutine, which MemoryEventStore.Close stops.
func (*MemoryEventStore) After ¶
func (s *MemoryEventStore) After(ctx context.Context, sessionID, streamID string, index int) iter.Seq2[[]byte, error]
After implements EventStore; each replayed event is a copy.
func (*MemoryEventStore) Append ¶
func (s *MemoryEventStore) Append(ctx context.Context, sessionID, streamID string, data []byte) error
Append implements EventStore; the data is copied, and data larger than the MaxRequestBytes the store was built over is refused.
func (*MemoryEventStore) Close ¶
func (s *MemoryEventStore) Close()
Close stops the store's janitor, waiting for it to exit, releases every retained event, and refuses every further operation rather than resurrecting state. It is idempotent.
func (*MemoryEventStore) Limits ¶
func (s *MemoryEventStore) Limits() policy.Limits
Limits reports the limits the store was built over, which WithSessions checks against the server's own.
func (*MemoryEventStore) Open ¶
func (s *MemoryEventStore) Open(ctx context.Context, sessionID, streamID string) error
Open implements EventStore.
func (*MemoryEventStore) SessionClosed ¶
func (s *MemoryEventStore) SessionClosed(ctx context.Context, sessionID string) error
SessionClosed implements EventStore.
type MemoryTaskStore ¶ added in v0.6.0
type MemoryTaskStore struct {
// contains filtered or unexported fields
}
MemoryTaskStore is the in-process TaskStore: the records live in this process's memory, bounded by the configuration it was built over, and are lost when the process ends. Without WithTaskStore each server keeps its tasks in one of its own; one store handed to several servers in one process makes them share their tasks, as replicas sharing a store module's store do. It holds no goroutine and needs no closing. Its methods are safe for concurrent use.
func NewMemoryTaskStore ¶ added in v0.6.0
func NewMemoryTaskStore(cfg policy.TaskConfig) (*MemoryTaskStore, error)
NewMemoryTaskStore builds the memory store over cfg - the configuration WithTasks is given: MaxTasks caps the live tasks it holds and MaxTasksPerIdentity one owner's share of them (past either a create is refused with ErrTaskStoreFull), each record is discarded at its expiry, and a record past cfg.MaxRecordBytes() is refused. It refuses a cfg that fails policy.TaskConfig.Validate, with that error.
func (*MemoryTaskStore) Create ¶ added in v0.6.0
func (s *MemoryTaskStore) Create(ctx context.Context, id, owner string, expires time.Time, data []byte) error
Create implements TaskStore; the data is copied.
func (*MemoryTaskStore) CreateListed ¶ added in v0.6.0
func (s *MemoryTaskStore) CreateListed(ctx context.Context, id, owner string, expires time.Time, data, listing []byte) error
CreateListed implements TaskLister; the data and listing are copied.
func (*MemoryTaskStore) ListTasks ¶ added in v0.6.0
ListTasks implements TaskLister; each listing is a copy.
func (*MemoryTaskStore) Swap ¶ added in v0.6.0
func (s *MemoryTaskStore) Swap(ctx context.Context, id string, version int64, data []byte) (int64, error)
Swap implements TaskStore; the data is copied.
func (*MemoryTaskStore) SwapListed ¶ added in v0.6.0
func (s *MemoryTaskStore) SwapListed(ctx context.Context, id string, version int64, data, listing []byte) (int64, error)
SwapListed implements TaskLister; the data and listing are copied.
func (*MemoryTaskStore) TaskConfig ¶ added in v0.6.0
func (s *MemoryTaskStore) TaskConfig() policy.TaskConfig
TaskConfig reports the configuration the store was built over, which WithTaskStore checks against WithTasks'.
type Observer ¶
type Observer struct {
// ObserveCall receives the pipeline's finished call sample, once per
// call, on the final outcome.
ObserveCall func(sample CallSample)
// RejectRateLimit counts a transport refusal under the rate budget (HTTP
// 429): no call exists to sample, so the pipeline's hook cannot see it.
RejectRateLimit func()
// RejectConcurrency counts a transport refusal under the in-flight cap
// (HTTP 503): no call exists to sample, so the pipeline's hook cannot
// see it.
RejectConcurrency func()
// Trace opens the span for one call (DESIGN_SPEC.md H34): the server
// runs the call under the returned context - decode through audit - so
// the implementation receives the span through its own context. A nil
// hook traces nothing.
Trace TraceStart
}
Observer is the operator's metrics boundary (DESIGN_SPEC.md H34, J41): the narrow hook an external backend fills. The zero value records nothing: every hook nil-checks, so a server built without one runs exactly as before. Use WithObserver to wire one onto an entry point.
type Operation ¶
type Operation struct {
// Name is the final, possibly renamed, name a client sees.
Name string
// Source is the pre-curation resolved name every directive addresses; it
// never changes.
Source string
// Docs is the final documentation after Describe.
Docs string
// Risk classifies the operation: a resource or a prompt is read-only by
// its kind, since reading a resource and rendering a prompt have no
// mutating protocol verb, and a tool is read-only only with a readonly
// hint - destructive otherwise. Hints are evidence, never authorization
// controls (DESIGN_SPEC.md E26).
Risk policy.Risk
// Fixed holds the argument values Fix pins, keyed by argument name; nil
// when no Fix applies. A fixed argument is not part of the tool's input
// schema: every call runs with the value (decision 0049).
Fixed map[string]any
// Alias reports whether this entry is an alias: an additional public
// name resolving to the canonical operation named by Source. Aliases
// inherit the canonical operation's auth, approval, credentials, retry,
// dedup and budget behavior.
Alias bool
// Deprecated reports whether the canonical operation is deprecated.
// Deprecation carries the advisory metadata; it never removes the
// operation.
Deprecated bool
// Deprecation carries the advisory metadata when Deprecated is true.
Deprecation Deprecation
// Contract is the resolved contract operation. Its Name repeats Source,
// and its slices are cloned on read like every other accessor here;
// Contract.Func.Root is the shared, read-only structure the function
// belongs to.
Contract contract.Operation
}
Operation is one exposed operation on a curated Surface: its final public name and documentation, its risk classification, the argument values Fix pins, and the resolved contract data - kind, function, arguments - that schema construction and invocation consume.
type Option ¶
type Option func(*options)
Option configures one entry-point server (Serve, NewHandler and Handler, NewSSEHandler and ServeSSE, Run and Main, and the testing package's harness). The zero option list serves the documented defaults. The list is strict (DESIGN_SPEC.md A5, decision 0047): a nil option, the same option given twice where both would apply, an option the served transport does not honour, and an option's own argument problems are each a collected startup problem, never skipped or silently overridden. ForStdio, ForHTTP and ForSSE scope options to one transport.
func ForHTTP ¶
ForHTTP scopes opts to the Streamable HTTP transport (NewHandler and Handler; Run and Main with -addr), with ForStdio's rules: validated for Streamable HTTP everywhere, applied only there.
func ForSSE ¶
ForSSE scopes opts to the isolated legacy SSE transport (NewSSEHandler and ServeSSE; Run and Main with -sse-addr), with ForStdio's rules. ForSSE(WithSSE()) is how a program permits -sse-addr while it keeps serving stdio and -addr: the opt-in then applies only when -sse-addr is chosen.
func ForStdio ¶
ForStdio scopes opts to the stdio transport: validated for stdio at every entry point - a broken option inside fails every serve, whatever it serves - applied only when stdio is served, and inert on every other transport. It is how one binary configures each transport Main can serve:
mcp.Main(impl, mcp.ForStdio(mcp.WithStdioIdentity(operator)), mcp.ForHTTP(mcp.WithBearerAuth(validator, "mcp")), )
Blocks do not nest, and an empty block is a problem. The same option may appear in blocks of different transports; given unscoped and in a block, or twice in blocks of one transport, it is a duplicate.
func WithAllowedHosts ¶
WithAllowedHosts admits a request whose Host header, port ignored, is a loopback name - "localhost" or a loopback IP literal - or one of hosts, and refuses every other Host with 403, on every listener (DESIGN_SPEC.md E25): the DNS-rebinding defence a reverse proxy in front of a loopback listener needs to forward its public name, and one a public listener otherwise lacks. Without it the protocol engine's own check applies: a request whose connection arrived on a loopback address and whose Host is not a loopback name is refused 403 - whatever address the listener was bound to, so a wildcard 0.0.0.0 listener reached by a proxy on the same host over 127.0.0.1 is refused too - and only a connection that arrived on another address is served under any Host. A proxy that forwards "Host: mcp.example.com" over loopback is therefore refused until that name is listed here, or the proxy sends "Host: localhost"; binding a wildcard address does not get past the rule. With it, the engine's check is replaced by this stricter one, never stacked on it.
Each host is a DNS name or an IP literal, IPv6 bracketed or not, matched exactly - case and one trailing dot ignored, no wildcard, no suffix match, no DNS lookup - and an internationalized name is listed in its A-label ("xn--") form. An empty list, a wildcard, a scheme, a port, a path, an IPv6 zone and a duplicate are startup problems. Streamable HTTP and the legacy SSE transport only: stdio and the testing harness refuse it.
func WithAllowedOrigins ¶
WithAllowedOrigins replaces the loopback-only browser-origin posture (DESIGN_SPEC.md E25) with an exact allowlist: a browser request - one carrying an Origin header - whose origin is not listed is refused 403 before any other work, whatever address the server binds, and a request without Origin, which no browser sends, is never refused by it. Each origin is an absolute http or https origin - "https://app.example", "http://localhost:5173" - matched on its scheme, host and port, case ignored and the scheme's default port filled in; a loopback origin is admitted only when it is listed too.
An empty list, a wildcard ("*", "https://*.example"), the opaque "null" origin, userinfo, a path, any other scheme and a duplicate are startup problems. Streamable HTTP and the legacy SSE transport only: stdio and the testing harness refuse it, so a binary that also serves stdio scopes it with ForHTTP or ForSSE.
func WithApprover ¶
WithApprover decides destructive operations server-side (DESIGN_SPEC.md E26): without it, and without WithClientApproval, every destructive operation is denied - a mutating verb with no readonly hint is destructive - and with it a is asked, after authorization and before any credential resolves, for each one. When the calling client can be asked it is asked as well, after a grants, and both must grant: the client is shown "approve this destructive operation: <name>" and nothing else - no arguments, no credential. A client that cannot be asked is decided by a alone unless WithClientApproval is also given, which denies it instead. It is honoured on every transport.
A client can be asked when it declares elicitation, with one limit on Streamable HTTP without WithSessions: the handler is then stateless, so it can ask only a client on protocol 2026-07-28 or later. An older client there cannot be asked - even one that declared elicitation - and a alone decides its call. In a WithSessions session an older client is asked on its session's GET stream and answers with a POST, within the call's deadline, which the question and the operation share.
At protocol 2026-07-28 and later the question travels as an input request: the client answers it by retrying the whole call, and a is consulted again on the retry. A decision must therefore be pure and repeatable - no side effect, no second prompt to a human for the same call. Only the retry's decision is audited.
Construction probes a once with a destructive operation named "iqmcp.canary" for the anonymous identity. An approver that grants it approves every client that cannot be asked, so the server logs one warning through the process's default logger naming WithClientApproval; an approver that panics on the probe is a startup problem. A panic on a real decision later is recovered as a denial, logged, and the server keeps serving. A nil or typed-nil a is a problem.
func WithAuditSink ¶
WithAuditSink wires the operator's durable audit sink onto the entry-point server, on every transport (Serve, NewHandler and Handler, NewSSEHandler and ServeSSE, Run and Main, and the testing harness). A nil sink is the default: the server records nothing beyond the author's pipeline hook. Like every option it is given at most once where it applies (decision 0047).
func WithAuthorization ¶
WithAuthorization replaces the default authorization engine (policy.DefaultEngine) for identity-aware discovery and the execution re-check alike, on every transport (DESIGN_SPEC.md E24). Construction probes e once with two synthetic decisions on an operation named "iqmcp.canary" and refuses an engine that grants a protected operation to the anonymous identity, ignores tenant:required, or panics on either probe - the two rules the policy.Engine contract demands. A panic on a real decision later is recovered as a denial: the operation is hidden from discovery and denied at execution, the panic is logged through the process's default logger, and the server keeps serving. A nil or typed-nil e is a problem.
func WithBackendKey ¶
WithBackendKey names the backend each call's bulkhead and breaker guard (DESIGN_SPEC.md F29): key receives the call's context and its SOURCE operation name and returns a stable, non-empty name for the backend the call reaches - its host, say - so one saturated or failing backend is bounded and broken on its own and cannot starve another. Without it the whole server is one backend.
Each distinct key keeps a bulkhead and a breaker for the life of the server: key must name one of a small, fixed set of backends - never a value derived from the caller's identity or arguments, which would grow the gates, and their diagnostics, with every caller. Isolating callers from one another is authorization's and the limits' job, not the gates'.
key runs once per call, after authorization, approval, credential resolution and deduplication, and every attempt of a retried call runs under the backend it named. Its context carries the caller's identity (IdentityFromContext) but never the call's credential: CredentialFromContext reports none there, so no key is derived from a secret or carries one into the gates' diagnostics. A call whose key is empty, or whose key panics - recovered, and logged through the server's logger - is refused before its implementation runs.
It needs WithBulkheads or WithBreakers on the same transport - alone it would key nothing - and a nil key is a startup problem. It is honoured on every transport, the testing harness included.
func WithBearerAuth ¶
WithBearerAuth requires a verified "Authorization: Bearer" token on every Streamable HTTP request and runs every call and listing as the identity v returns for it (DESIGN_SPEC.md E23). It is the chain's outermost layer: a request with no bearer token, a token v refuses, a token whose validation panics, or a token v accepts as the anonymous identity is answered 401 with the fixed body "invalid token" (or "no bearer token") and a Bearer challenge before any other layer runs - v's own error goes to the process's default slog logger with the presented token redacted, never to the client. A verified token lacking any of scopes is answered 403, and scopes are named in the challenge; per-operation requirements stay on the auth: tags, which the pipeline enforces at discovery and execution (E24). The presented token is handed to the surface's credential provider as policy.CredentialRequest.SubjectToken and to nothing else: it is kept off the call context, so no accessor, hook or reflection over the context hands it to an implementation. Each kind of refusal writes at most one log line per second, counting the ones suppressed in between: the bearer layer runs before the rate limit, so the refusal rate is the client's to choose (and so is the validator's work - bound a remote validator with its own timeouts).
Streamable HTTP only: on stdio, which carries no Authorization header, and on the legacy SSE transport, which cannot bind a verified identity to each call, it is a startup problem - scope it with ForHTTP in a binary that serves both. A nil or typed-nil v, an empty or repeated scope, and a scope that is not one RFC 6750 scope token are problems too.
func WithBreakers ¶
func WithBreakers(cfg policy.BreakerConfig) Option
WithBreakers adds a circuit breaker per backend (DESIGN_SPEC.md F29): once cfg.Failures consecutive calls of one backend have failed (each attempt of a retried call counts as one; a failure is the implementation's error, its deadline passing, or a bulkhead refusal after the breaker admitted it; a pass that ends asking the calling client a question - see Sample - is neither a failure nor a success), the backend's breaker opens and refuses every call, as a retryable "unavailable" tool error that runs nothing, for cfg.Cooldown; then it admits cfg.Trials trial calls, closing on the first that succeeds and reopening on the first that fails. The breaker judges a call before the bulkhead does, so a refused call spends no slot. cfg.Clock may replace the process clock, as a test's (the testing package's TestClock.Now). The backend is the whole server unless WithBackendKey names one per call.
The zero configuration, which never opens, and every problem policy.NewBreakers reports are startup problems. It is honoured on every transport, the testing harness included, and every server built from the option list has breakers of its own.
func WithBulkheads ¶
func WithBulkheads(cfg policy.BulkheadConfig) Option
WithBulkheads bounds the calls each backend runs at once (DESIGN_SPEC.md F29): at most cfg.MaxConcurrent calls of one backend run their implementation at the same time, and at most cfg.MaxQueue more wait for a slot, each for no longer than its own deadline - the wait spends the deadline the implementation then runs under, and a call still waiting when it passes is answered as a "timeout" that never ran. A call over both bounds is refused at once - backpressure, never an unbounded queue - as a retryable "unavailable" tool error, and its implementation never runs. The backend is the whole server unless WithBackendKey names one per call.
The zero configuration, which admits nothing, and every problem policy.NewBulkheads reports are startup problems. It is honoured on every transport, the testing harness included, and every server built from the option list has gates of its own.
func WithClientApproval ¶
func WithClientApproval() Option
WithClientApproval runs a destructive operation only after the calling client confirms it through elicitation (DESIGN_SPEC.md E26): the client is asked "approve this destructive operation: <name>" and only an accept that confirms runs it - a decline, a dismissal, an answer that does not confirm, a failure reaching the client, and a call cancelled while the question is open are all denied. A client that cannot be asked - one that declares no elicitation capability - is denied and audited policy.ApprovalUnsupportedClient. With WithApprover both must grant, the server's approver first; alone, the client decides. It is honoured on every transport, with one limit on Streamable HTTP without WithSessions: the handler is then stateless, so it can ask only a client on protocol 2026-07-28 or later, which answers the question and retries the call; an older client there cannot be asked, even one that declared elicitation, and is denied. In a WithSessions session an older client is asked on its session's GET stream, the question and the operation sharing the call's one deadline: one that never answers is refused when it passes, the operation never run. A question that travels as an input request is audited once, with the retry's decision. In the testing harness, the testing package's WithFakeClient answers for the client.
func WithHealthPath ¶
WithHealthPath answers GET and HEAD at path with a constant 200 "ok" for liveness probes - a Kubernetes httpGet probe, a load balancer's health check - on the listener Run and Main serve -addr or -sse-addr on. The route sits outside every other control: no bearer token, no Host or origin check, no rate or in-flight budget, so a probe is never refused by a control and never spends a caller's budget, and it reveals nothing but that the process accepts connections. Any other method at path is 405. path is matched exactly against the request's path, whatever its query: it must be absolute and clean, neither "/" nor under /.well-known/, where discovery documents live, with no query, fragment, percent escape, space or control character.
Run and Main only: NewHandler, Handler, NewSSEHandler and ServeSSE return a handler the caller mounts on a listener of its own, so they refuse it - serve a probe from your own mux beside the handler, as the example gallery's mux example does. stdio has no listener and the testing harness serves none, so both refuse it too: a binary that also serves stdio scopes it with ForHTTP (and ForSSE for -sse-addr).
func WithHooks ¶ added in v0.5.0
WithHooks installs the typed transform hooks h (DESIGN_SPEC.md J41). A hook's error fails the call and is mapped like an implementation's - see "Errors an implementation returns": a ToolError's message reaches the model, a plain error is an "invocation" failure whose text reaches the audit record only, redacted - and a panicking hook is recovered as an "unknown" failure. An argument hook's failure ends the call before the credential is resolved, so it costs no credential exchange, and is never recorded by WithIdempotency; a result hook's failure on a keyed call is the call's outcome like any other, recorded when it is not retryable, because the implementation already ran. WithRetries never retries a hook's failure: the argument hook runs before the attempts, the result hook after the last.
The hooks transform; they control nothing. Authorization and approval have decided before either runs, and neither can grant what they refused - though either can refuse. The call's deadline bounds the implementation, not the hooks, so keep them fast and stop when ctx ends.
A Hooks that sets neither hook is a startup problem. It is honoured on every transport, the testing harness included.
func WithIdempotency ¶
func WithIdempotency(cfg policy.IdempotencyConfig, keyArguments map[string]string) Option
WithIdempotency deduplicates keyed calls (DESIGN_SPEC.md E26, F30): keyArguments maps each operation it keys - by SOURCE name or Go field path - onto the top-level string argument its callers carry an idempotency key in. The key is one of the operation's own declared arguments, so the implementation receives it too and can hand it to its backend; no field of the protocol carries it. A call that carries a key replays, instead of running its implementation, the outcome recorded within cfg.TTL by a call of the same operation for the same identity - subject, tenant and scopes - with the same key and the same other arguments, a success or a failure (see below for which are recorded), audited as replayed with zero attempts. A duplicate that arrives while the first call still runs waits for its outcome. A key reused with other arguments is refused, running nothing, with a "decode" tool error asking for a new key: a key names one call. The other arguments are compared as the caller sent them - property order and spacing aside, a null property as an absent one - so arguments that differ in any other way ("1.0" and "1") are refused rather than replayed. A call that sends no key, a null one or "" runs without deduplication; a key that is not a string or is longer than 255 bytes is a decode error, as is a keyed call whose arguments name one property twice in spellings that differ only in case, which a struct argument would decode last-one-wins where the comparison could not tell. Authorization, approval and credential resolution run for every call, so a replay never passes a control that would refuse the call now.
Only a verdict is recorded: a success, and a failure the implementation answered that a repeat would not change. A call a gate refused before it ran, whose deadline passed, whose caller gave up, that failed retryably, or whose implementation asked the client for input is answered as itself and records nothing, so a repeat with the same key and arguments runs again - the implementation handing its backend the same key - and a duplicate that was waiting on it runs instead of observing it. A success is recorded as its call answered it, rendered and redacted against the credential that call resolved: a replay answers exactly that, even after the credential has rotated.
The dedup window is one server's: each server built from the option list keeps its own store, in process memory, of at most cfg.MaxKeys outcomes, the least recently used evicted first - not shared by another replica (route each caller to one) and not kept across a restart. A bucket keeps the operation, the identity, SHA-256 digests of the key and of the other arguments, and the recorded answer; never a credential, and no argument value beyond what the answer itself carries. It is not exactly-once execution: a call that timed out may have written already, cancellation cannot undo a side effect, and a call whose outcome was never recorded - unanswered, lost with the process, evicted, expired - runs again. Only a protected operation (a non-empty auth: requirement) may be keyed: every anonymous caller shares one identity, so an unprotected operation's outcome would replay from one anonymous caller to another.
The zero configuration, a non-positive MaxKeys or TTL and every other problem policy.NewIdempotencyStore reports, an empty map, an operation that is empty, unexposed, ambiguous, keyed twice or unprotected, and an argument the operation does not declare as a top-level string are startup problems. It is honoured on every transport, the testing harness included.
func WithInstructions ¶
WithInstructions sets the server instructions the initialize handshake carries to every client (DESIGN_SPEC.md E26): operator-authored text telling the model how to use this server, which clients typically place in the model's context. Instructions are trusted text, and this option is their only source: nothing the server serves derives them - not the docs: tags, not an OpenAPI document's title or descriptions, not any backend's content - so a backend cannot speak to the model with the server's authority. Without it the handshake carries none.
text must be 1 byte to 16 KiB of valid UTF-8 without a NUL character; anything else is a startup problem. Write it as you would any prompt the model reads: it reaches every client on every connection, and it grants nothing - authorization, approval and the other controls apply whatever it says. It is honoured on every transport.
func WithLimits ¶
WithLimits replaces the hardening limits (DESIGN_SPEC.md E25) and the server-wide per-call deadline (F27) the served transport runs under, policy.DefaultLimits() otherwise. Streamable HTTP and the legacy SSE transport enforce the request-size cap MaxRequestBytes (413), the rate limit RateRequests per RateInterval (429 with Retry-After), the in-flight cap MaxInFlight on every request but an event stream's GET (503), the cap MaxSessions on the event streams open at once - each legacy SSE session is one - (503), the origin posture BindLocalhost selects, and CallTimeout on every call; Run and Main size their http.Server's read and write timeouts from CallTimeout. SessionTimeout, MaxSessions and MaxStreamEvents also bound the explicit Streamable HTTP sessions WithSessions serves - the idle timeout, the live sessions (an initialize past MaxSessions is refused 503) and the events an event store retains per session - and an event store must be built over the same limits. stdio and the testing harness enforce the two fields the call pipeline reads: CallTimeout, each call's deadline, and MaxRequestBytes, the cap on one call's arguments; the other fields are validated all the same, so one list serves every transport. A Timeout directive gives one operation a deadline of its own.
l must pass policy.Limits.Validate: start from policy.DefaultLimits() and adjust the fields. Every problem it reports, and the zero Limits, is a startup problem. It is honoured on every transport; in the testing harness, given together with the testing package's own WithLimits, it is a duplicate.
func WithLogger ¶
WithLogger routes the server's own records to logger instead of the process's default slog logger (DESIGN_SPEC.md A6):
- the security records: a refused bearer token's cause, its presented token redacted (WithBearerAuth); a panicking authorization engine or approver, recovered as a denial; and the startup warnings - the expose-all warning of an implementation or a Backend the entry point curates itself, an approver that grants the anonymous probe, sessions no identity pins, and Run's anonymous listener on an address that is not loopback-only;
- the lifecycle records, which the server writes only to a logger given here, at the info level: "server.ready" as it is built, "call.start" and "call.end" around every call, "serve.start" and "serve.stop" around a stdio serve, and with WithTasks the "task.*" records of each task's start, end, cancellation, expiry and refused foreign access - bounded fields only (the operation, the outcome class, the attempts and the durations), never an argument, an identity or a credential;
- with Run and Main serving -addr or -sse-addr, the listener's net/http error records (a failed TLS handshake, a recovered handler panic), at the error level.
The logger's handler decides what it keeps: a record below its level is never handed to it, so a logger at the warning level takes the startup warnings and the recovered panics but neither the lifecycle records nor a refused bearer token's cause, which are written at the info level.
Without it the security records go to the process's default logger - which Run and Main route to stderr - and no lifecycle record is written. The records a call's implementation logs through the client's logging are the client's and do not come here. Nor does the expose-all warning of a Surface curated before the entry point sees any option - one handed in from Curate, or the testing package's own curation: Curate wrote it to the process's default logger when it ran.
A logger whose handler writes to standard output corrupts the stdio transport, whose standard output carries protocol frames only: a server that may serve stdio logs to standard error, a file or a collector, never os.Stdout. This cannot be checked, so it is the caller's to keep. A nil logger is a startup problem. It is honoured on every transport.
func WithObserver ¶
WithObserver wires the operator's observer - the metrics backend - onto the entry-point server, on every transport (Serve, NewHandler and Handler, NewSSEHandler and ServeSSE, Run and Main, and the testing harness). A nil observer is the default: the server records nothing. Like every option it is given at most once where it applies (decision 0047).
func WithProtectedResourceMetadata ¶
func WithProtectedResourceMetadata(m ProtectedResourceMetadata) Option
WithProtectedResourceMetadata publishes m at its RFC 9728 well-known path and names that URL in every 401 and 403 bearer challenge ("resource_metadata"), so an MCP client that meets WithBearerAuth discovers where to obtain a token (DESIGN_SPEC.md E23). The document is public - discovery happens before a client holds a token - so it is served outside every other layer of the chain, with a permissive CORS posture, to GET (and the preflight) alone; every other path meets the full chain unchanged. The path is matched exactly: a program that mounts the handler under a prefix mounts it at the well-known path too, and never strips the prefix,
h := mcp.Handler(api, mcp.WithBearerAuth(v), mcp.WithProtectedResourceMetadata(m))
mux.Handle("/mcp", h)
mux.Handle("/.well-known/oauth-protected-resource/mcp", h)
It needs WithBearerAuth on the same transport - metadata describing authentication the server does not demand is a startup problem - and when that validator reports the audience its tokens must name, as oauth.NewJWKSValidator's and every policy.ClaimsValidator do through Audience, m.Resource must be exactly that audience: otherwise clients would obtain tokens for the published resource that the validator refuses, or the validator would accept tokens minted for another resource. Every field problem the ProtectedResourceMetadata fields document is a startup problem too.
Streamable HTTP only: stdio and the legacy SSE transport carry no bearer authentication for the metadata to describe, and the testing harness serves no wire, so each refuses it - scope it with ForHTTP in a binary that serves more than one transport.
func WithRetries ¶
func WithRetries(p RetryPolicy, operations ...string) Option
WithRetries retries the named operations under p (DESIGN_SPEC.md F29) and nothing else: an operation is retried only when it is named here, by its SOURCE name or its Go field path - the names a curation directive takes - and every alias of it is retried alike. A failed attempt is retried only when the pipeline classified the failure retryable: a bulkhead or breaker refused it ("unavailable"), the implementation's error declares a class other than "invocation" through Code() and a repeatable failure through Retryable() - see "Errors an implementation returns" in the package documentation, which also names the RetryAfter() a failure may ask to wait - or the attempt timed out ("timeout") on a deadline of its own, shorter than the call's, that the implementation returned while the call still had time. The call's own deadline ends the call: every attempt runs under it, so an attempt it cuts is the call's last. A plain error, a decode, authorization, approval or credential refusal, and a caller's cancellation are never retried; nor is a FromREST or FromOpenAPI backend's failed answer, which is an "invocation" failure - such an operation is retried on a gate's refusal only.
A retry re-runs the implementation alone: decoding, authorization, approval and credential resolution run once per call, each attempt meets the breaker and the bulkhead afresh, and the audit record counts the attempts. Every attempt and every wait share the call's one deadline - its operation's Timeout, else the CallTimeout - so a retried call is answered by the time an unretried one would be, and a wait the time left cannot cover ends the call with the last failure.
A timed-out write may have succeeded (F29), so a destructive operation may be named only when WithIdempotency keys it, and even then a call is retried only when it carries its key: the implementation receives the key as its argument and should hand it to the backend, which can then tell a repeat for the write it already made. An unkeyed call of a destructive operation runs once.
A name that addresses no exposed operation or more than one, a destructive operation WithIdempotency does not key in the same scope, no name, an empty or repeated name, and a p outside RetryPolicy's bounds are startup problems. It is honoured on every transport, the testing harness included.
func WithSSE ¶
func WithSSE() Option
WithSSE opts into the isolated legacy SSE transport (decision 0039): the 2024-11-05 SSE wire, served alone - never alongside stdio or Streamable HTTP - with the query-token, origin, rate and concurrency guards the adapter wires. SSE is impossible to enable implicitly: NewSSEHandler, ServeSSE and Run's -sse-addr refuse to serve without the opt-in, and every other entry point serves its existing transport exactly as before.
Unscoped, WithSSE selects the SSE wire: Serve, NewHandler and Handler refuse it, and so do Run and Main served over stdio or -addr - the fail-fast mutual exclusion. Scoped with ForSSE it is a permission instead: ForSSE(WithSSE()) lets Run and Main serve -sse-addr when that flag is chosen, while the same binary keeps serving stdio and -addr.
func WithServerInfo ¶
WithServerInfo sets the name and version the initialize handshake announces (DESIGN_SPEC.md A6). Without it both are derived:
- the name is the served API's api: specification name - "Weather" for api.Specification `api:"Weather"` - else the last element of the program's main module path from its build information ("weather" for example.com/acme/weather, or for example.com/acme/weather/v2), else "iqmcp"; a candidate is taken only when it is 1 to 64 letters, digits, '_', '.' or '-' starting with a letter or digit, so no derived name carries a space, a control or a bidirectional-override character. FromOpenAPI's synthesized structure has no api: name, so a specification document's title never becomes the name.
- the version is the main module's version from the build information
- the tag go install fetched, or the version the toolchain stamped from the repository - else "(devel)".
The testing package's harness announces "mcp-testing" "v0.0.0" unless this option is given there too. name and version must each be non-empty, at most 128 bytes of valid UTF-8, printable - no control character, no format character such as a bidirectional override, no space but the ASCII one - and not start or end with a space: a client shows them to its user. Anything else is a startup problem. It is honoured on every transport.
func WithSessions ¶
func WithSessions(events EventStore) Option
WithSessions switches Streamable HTTP from the stateless default to explicit sessions (DESIGN_SPEC.md B7): initialize issues an Mcp-Session-Id, the session's GET stream and DELETE are served, the level logging/setLevel negotiates lasts for the session, and a client that loses a stream resumes it from its Last-Event-ID, replayed from events (at protocol versions before 2026-07-28, which removes stream resumption). A session idles out at the server's SessionTimeout; the server holds at most MaxSessions of them - an initialize past that is refused 503 - and their open streams share the MaxSessions pool, each apart from the MaxInFlight slots the requests take, kept alive with a comment at least every 15 seconds while quiet, and ended when the server shuts down; Run and Main end every session still open when they return.
What events holds is bounded however a client drives its session: every call is answered as one JSON body, which carries no event ID to resume from, so only the session's GET stream - the notifications and questions sent outside any call's answer - is recorded, never a call's result, and an event larger than MaxRequestBytes is delivered live but not retained. Every replay is checked against the event IDs the server issued: a store that lost a live session's events - evicted, expired, or failed mid-write - gets the resume refused (400), never a replay of other events under IDs the client already holds.
A session ID is an address, never a credential (B10): with WithBearerAuth every request of a session still presents its own token, is served as the identity that token names - a narrower token than the session began with is served with its narrower scopes - and is refused 403 unless the token names the same tenant and subject as the session's creator. Without an identity source no session is pinned to a caller, and the server logs one warning saying so.
A session can ask a client below protocol 2026-07-28 to approve a destructive operation (WithApprover, WithClientApproval) on its GET stream, which the stateless default cannot. The question and the operation share the call's one deadline - its operation's Timeout, else the CallTimeout - started when the question is asked: a client that has not answered by then is refused, the operation never run (the protocol engine cannot close a session, on DELETE, idle expiry or shutdown, while one of its calls is in flight), and an operation approved late gets only what is left, so the whole call fits the timeouts sized from one deadline.
Sessions live in the serving process, whatever the store: the protocol engine answers a session ID it did not issue - another replica's, or its own before a restart - with 404, so a durable store gives no cross-replica or post-restart resume. A deployment of more than one replica must route each session to its replica (sticky routing on the Mcp-Session-Id header).
NewHandler and Handler need a non-nil events the caller builds - with NewMemoryEventStore over the server's limits, or a durable store from the store modules - and closes once the server has stopped; Run and Main build and close a MemoryEventStore for nil. A store that reports the limits it was built over (as every store of this repository does, through Limits) must have been built over the server's SessionTimeout, MaxSessions, MaxStreamEvents and MaxRequestBytes - WithLimits', or policy.DefaultLimits() without it - or it is a startup problem; so is a nil store inside a non-nil interface. Streamable HTTP only: stdio serves one session per connection already, the legacy SSE transport keeps its own sessions, and the testing harness serves no wire, so each refuses it - scope it with ForHTTP in a binary that serves more than one transport.
func WithStdioIdentity ¶
WithStdioIdentity runs every stdio call and listing as id: the operator's assertion of who the single local peer is, not a verification. Stdio only: on a network transport it would grant id to every remote caller, and the testing harness presents identities through its Client.As, so both are startup problems. The anonymous identity is a problem too - omitting the option is how stdio serves anonymously.
func WithTaskStore ¶ added in v0.6.0
WithTaskStore keeps the records of the tasks WithTasks serves in store instead of each server's own memory (decision 0066). Replicas handed stores over one backend and one scope - the store/redis and store/sql modules' NewTaskStore - share their tasks: a task created through one replica is read with tasks/get, answered with tasks/update and cancelled with tasks/cancel through any of them - and, for a 2025-11-25 task, waited on with tasks/result and listed with tasks/list (decision 0068) - and still answered only to the tenant and subject that created it.
The work stays on the replica that created the task; only its record is shared. A tasks/cancel that reaches another replica cancels the task in the store at once - every replica reads it as cancelled - and the creating replica, which reads the record of each run in flight every PollInterval, cancels the work within about one interval. A tasks/update that reaches another replica records the answers in the store; once every question is answered the task reads as working, and the creating replica runs the call again with the answers on its next tasks/get or tasks/update from the task's own tenant and subject - authorized, approved and credentialed as that request, as a multi-round-trip retry is as the request that sends it. The work moves on only once such a request reaches the replica that created the task, which a client that polls does under any routing that eventually reaches every replica.
A replica that shuts down cancels its runs - each records its outcome - and fails the tasks it created that wait for input, or for it to run their answers. A replica that dies without shutting down leaves its tasks as they were - working or waiting - until their TTL discards them. There is no failover and no exactly-once: the work of a cancelled or abandoned task may already have had its side effects.
The store enforces MaxTasks and MaxTasksPerIdentity across every server sharing it (store/sql documents a narrow overshoot under concurrent creates), and each server also holds at most MaxTasks tasks of its own; at either bound a call runs synchronously, as does a call whose record cannot be written. A tasks/* request the store cannot serve is answered with an internal error, never as "not found". A store that reports its configuration (as every store of this repository does, through TaskConfig) must have been built over WithTasks' MaxTasks, MaxTasksPerIdentity, TTL and MaxResultBytes, or it is a startup problem; so is a nil store, and WithTaskStore without WithTasks on the same transport. Replicas sharing a store must serve the same operations under the same configuration and identity source, and their clocks should agree to well within a poll interval: each reads a record's expiry by its own. The caller builds the store and closes it once the servers have stopped. Honoured where WithTasks is.
func WithTasks ¶ added in v0.5.0
func WithTasks(cfg policy.TaskConfig, operations ...string) Option
WithTasks serves the MCP tasks extension (io.modelcontextprotocol/tasks, DESIGN_SPEC.md B8 and F30) for the named tool operations: a call of one of them from a client that declares the extension answers at once with a task handle, and the client polls tasks/get for the outcome, answers mid-flight input with tasks/update and cancels with tasks/cancel. The extension is defined at protocol 2026-07-28, and the server advertises it in that revision's server/discover result only.
The same operations are served as the experimental tasks of protocol 2025-11-25 (decision 0068), on stdio and Streamable HTTP, to a client that initialized at exactly that revision: its initialize result declares the tasks capability, tools/list marks the named operations with execution.taskSupport "optional", and a call it augments with params.task answers a CreateTaskResult it drives with tasks/get, tasks/result (which waits for the outcome while the task waits for its client or runs, asking the client to poll tasks/get once a task whose replica has gone quiet passes the server's longest call deadline, on HTTP once the request has waited that long, and past two waits for one task or a caller's share of waits), tasks/list (declared only when the server resolves its callers' identities - bearer auth, a fixed identity - and its store lists, as every store of this repository does) and tasks/cancel. It is one task, in that revision's wire shape: its client approves and answers it directly, as that revision's synchronous call is asked, and on stdio it is told of each status change with notifications/tasks/status. Augmenting an operation not named here is method-not-found, and a call that cannot become a task now - the store full, the server shutting down - is refused with -32603 rather than run.
Every other call runs synchronously, exactly as without the option: a client that does not declare the extension on the request, or does not augment it at 2025-11-25, another protocol revision, an operation not named here, and a 2026-07-28 call arriving while the store is full. A tasks/* request from a 2026-07-28 client that does not declare the extension is refused with the protocol's -32021 (missing required client capability); at an older revision the methods do not exist. A task is answered only on the revision that created it.
A task's work is the call itself, run by the same pipeline - discovery, authorization, approval, credentials, the operation's deadline, idempotency, audit and redaction - detached from the request that started it. Its outcome is what the synchronous call would have answered: a tool result, an isError one included, completes the task, and a protocol-level refusal fails it. A call that would ask the client for input - client approval, required input, sampling, roots - moves the task to input_required with the same requests, and runs again once tasks/update has answered them all - as the caller that sent that tasks/update, its own token and scopes authorizing the run as a retry's authorize the retry, never the creator's as they were when the task began. Progress the implementation reports (ReportProgress) becomes the task's status message; logging notifications are not sent for a task. The operation's deadline still bounds its work - give a long-running operation its own Timeout - and cancellation cannot undo a side effect the work already had.
A task is answered only to the identity that created it - the same tenant and subject - and is reported as not found to anyone else. On a server without an identity source every caller is anonymous and shares one binding, so the unguessable task ID is the only handle. The store is bounded by cfg - start from policy.DefaultTaskConfig(). By default it is one server's, in process memory, not shared with another replica and not kept across a restart; WithTaskStore names a store replicas share, so a task created through one is read, answered and cancelled through any of them. On stdio and in the testing harness the tasks' work is cancelled when the connection ends; on Streamable HTTP, when the http.Server serving the handler begins shutting down - a call arriving during the shutdown runs synchronously instead - and Run and Main return only once that work has ended, within their shutdown grace, or report the shutdown as cut.
The zero configuration and every bound policy.TaskConfig.Validate refuses, no operation, an empty or repeated name, and a name that is not an exposed tool are startup problems. Honoured on stdio, Streamable HTTP and the testing harness (whose client speaks 2026-07-28 only); refused on the legacy SSE transport, which serves no revision the extension is defined at, and beside WithSessions, whose wire the engine serves only at older revisions - scope it with ForStdio or ForHTTP in a binary that serves those too.
type Problem ¶
type Problem struct {
// Where names the operation, directive or path the problem belongs to; it
// is empty when the problem belongs to the curation itself.
Where string
Message string
}
Problem is one reason an API could not be curated. It carries the same shape as the contract layer's and policy's problems - both are converted here - so one error reports construction and policy failures together. The root defines its own type rather than exposing either package's, because the collected error is public API.
type Prompt ¶
type Prompt struct {
// Messages are the rendered messages, in the order the model reads them.
// An empty or nil slice is legal - prompts/get answers with an empty
// message list - but a prompt that never renders a message is probably a
// mistake, and the prompts/get call surfaces whatever the function
// rendered rather than inventing one.
Messages []PromptMessage
}
Prompt is the rendered result of a prompt function (DESIGN_SPEC.md A3, B8): the messages a client receives when it gets the prompt. A prompt function is a template function - its arguments are the template's inputs, its return the rendered template - so its return type is the value this type carries:
func draft(ctx context.Context, t Topic) (mcp.Prompt, error) `mcp:"prompt"`
The rendered prompt is honest on the wire: every message is emitted exactly as the function returned it, in order, and a prompt whose function returned no messages is served as an empty list - never padded, and never rendered as a Go dump. A message whose Role is not one of the two roles the protocol defines fails the prompts/get call that returned it with a neutral error, because an unknown role is a protocol violation no client can read.
The prompt's own documentation is not part of this value: it comes from the declaration (the api: docs), reaches prompts/list, and stays there. Rich content rides on PromptMessage.Content.
The type is defined in this package deliberately: ADR 0010's prompt inference (an untagged function whose first return type is mcp.Prompt is inferred a prompt) matches it by package path and name, so an alias of a type defined elsewhere would never match.
type PromptMessage ¶
type PromptMessage struct {
// Role is who the message speaks as. It must be [RoleUser] or
// [RoleAssistant]; anything else fails the prompts/get call that returned
// it, with a neutral error naming nothing about the message's content.
Role PromptRole
// Text is the message's text content, exactly as the function rendered
// it. The server redacts it like every other result surface (E26), so a
// resolved credential never reaches the client through it. It is the
// whole message when Content is unset; when Content is set it is
// ignored - one message says one thing, and the rich block is it.
Text string
// Content is the message's rich content (DESIGN_SPEC.md B8, B12): one
// content block whose text surfaces the server redacts like Text and
// whose binary bytes travel untouched. The zero value - nil - is the
// text-only message, rendered from Text alone.
Content Content
}
PromptMessage is one message of a rendered Prompt: who speaks (Role) and what they say. A message says its Text until its rich content (Content) is set: Text is the text-only shape every existing prompt renders, and Content is the rich shape - one content block, the package's public rich-content vocabulary (Image, Audio, EmbeddedResource, Text, ResourceLink) - that replaces it. A message with no Content set renders exactly as it did before Content existed, so a text-only prompt stays byte-identical.
type PromptRole ¶
type PromptRole string
PromptRole is the speaker of one prompt message (DESIGN_SPEC.md B8). The MCP protocol knows exactly two; a prompt function may render either, and nothing else - the value is the author's evidence of who reads the message.
const ( // RoleUser is the user role: the message the model reads as the // conversation's user turn. RoleUser PromptRole = "user" // RoleAssistant is the assistant role: the message the conversation // carries as the assistant's turn, for example a prewritten reply the // client shows for editing. RoleAssistant PromptRole = "assistant" )
type ProtectedResourceMetadata ¶
type ProtectedResourceMetadata struct {
// Resource is this server's resource identifier (RFC 8707): the
// absolute https URL clients reach the MCP endpoint at - http only on a
// loopback host - without userinfo, a query, a fragment or a "." or
// ".." path segment, for example "https://mcp.example/mcp". It fixes
// the well-known path the document is served at (RFC 9728 section 3.1:
// /.well-known/oauth-protected-resource/mcp for that example), and it
// must be exactly the audience the bearer validator requires. Required.
Resource string
// AuthorizationServers are the issuer identifiers (RFC 8414) clients
// obtain tokens from: at least one, each an absolute https URL (http
// only on a loopback host) without a query or fragment, each once.
AuthorizationServers []string
// ScopesSupported are the scopes clients may request for this resource,
// each one RFC 6750 scope token, each once. Advisory: enforcement stays
// on the auth: tags, the validator's rules and WithBearerAuth's scopes.
ScopesSupported []string
// ResourceName is an optional human-readable name for the resource.
ResourceName string
}
ProtectedResourceMetadata is the OAuth 2.0 protected-resource metadata (RFC 9728) the Streamable HTTP wire publishes so an MCP client discovers where to obtain the tokens WithBearerAuth demands: the client reads the URL the 401 challenge names, then asks one of the authorization servers for a token whose audience is Resource. The published document's bearer_methods_supported is always ["header"] - the Authorization header is the only way the wire accepts a token.
type Renderer ¶
Renderer lets a tool's result type choose the text the model reads (DESIGN_SPEC.md B11, G33). Implementing it on the type a tool function returns gives the model a concise summary of the result - units spelled out, empty results explained - instead of the compact JSON the server renders by default. The structured content the client also receives stays the marshaled result either way - in the {"result": …} envelope when the result is not an object (see the package documentation's Structured output) - and the rendered text is never wrapped: the two surfaces coexist.
The precedence over the text content item is fixed: Renderer, then fmt.Stringer, then the unquoted string for a string-kind result, then the compact JSON wire form. A Render error fails the tool call - it is never silently replaced with JSON - and whatever Render produces is redacted with the call's resolved credential like every other result surface.
The interface is structural: a type satisfies it by having the method, and this alias is the same contract the protocol adapter checks, so implementing it needs no import of anything but this package.
type Resource ¶
type Resource struct {
URI string `json:"uri"`
MIMEType string `json:"mimeType,omitempty"`
Text string `json:"text,omitempty"`
Blob []byte `json:"blob,omitempty"`
}
Resource is the contents an EmbeddedResource carries: a URI, an optional MIME type, and either Text or Blob.
type ResourceLink ¶
type ResourceLink struct {
URI string `json:"uri"`
Name string `json:"name,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
MIMEType string `json:"mimeType,omitempty"`
}
ResourceLink is a block linking to a resource by URI instead of embedding its bytes.
func (ResourceLink) MarshalJSON ¶
func (l ResourceLink) MarshalJSON() ([]byte, error)
MarshalJSON writes the wire shape the protocol carries for a ResourceLink block.
type RetryPolicy ¶
type RetryPolicy struct {
// Attempts is the total number of attempts, the first included: at
// least 2, at most 16.
Attempts int
// Base is the first wait's ceiling: positive, at most one hour.
Base time.Duration
// Max caps every wait's ceiling: at least Base, at most one hour.
Max time.Duration
}
RetryPolicy is the opt-in jittered retry policy WithRetries retries its operations under (DESIGN_SPEC.md F29). Attempts counts every attempt, the first included; each wait before a retry is drawn uniformly below a ceiling that starts at Base, doubles with every retry and is capped at Max (full jitter, so concurrent retries do not stampede a backend), and lasts at least the RetryAfter a failure asked for. A failure is retried only when the pipeline classified it retryable - see WithRetries - so the policy carries no classifier of its own.
type SampleMessage ¶
type SampleMessage struct {
// Role is who the turn speaks as.
Role PromptRole
// Text is what the turn says.
Text string
}
SampleMessage is one turn of a sampling exchange; Role is RoleUser or RoleAssistant.
type SampleRequest ¶
type SampleRequest struct {
// SystemPrompt steers the generation; empty sends none.
SystemPrompt string
// Messages is the exchange so far, in order: at least one turn.
Messages []SampleMessage
// MaxTokens bounds the tokens the client may generate; zero or less
// selects the server's default of 1024. Whatever it asks, an answer
// over 1 MiB of text is refused.
MaxTokens int64
}
SampleRequest asks the calling client's model to generate text (DESIGN_SPEC.md B8).
type SampleResult ¶
type SampleResult struct {
// Refused reports that no text is available: the client declined,
// dismissed or failed the question, answered with no text, with
// something other than text, or over the 1 MiB bound; it declares no
// sampling; or the question is still on its way to it (see [Sample]).
Refused bool
// Text is the generated text, set only when Refused is false.
Text string
}
SampleResult is the client's untrusted answer: Refused, or Text.
func Sample ¶
func Sample(ctx context.Context, req SampleRequest) (SampleResult, error)
Sample asks the calling client's model to generate text (DESIGN_SPEC.md B8) and returns its answer. A client that declares no sampling capability answers Refused and is never asked, and so does every call outside a served one. The system prompt and the messages are redacted over the call's credential before they leave the server, in raw and JSON-escaped form, and so is the answer.
The answer is untrusted client input: the client may return any text, whatever its model said, so treat it as text to render or to check - never as an instruction, a verified fact or a credential.
A non-nil error must be returned from the implementation as it is or wrapped with %w, and before any side effect. On protocol 2026-07-28 and later a server may not send the client a request in the middle of a call (SEP-2322): the error is then the request that makes the client answer. The call ends with the question; the client answers it and sends the call again with the answer, and the whole call runs again from the start - decoding its arguments, authorizing and approving it anew - until the implementation asks and this time receives the answer. The answers the client already gave travel with the call, so each question - the server's approval question included - is asked once per call, and an implementation that asks several questions asks them one pass at a time. A question is known by its text: two asks with the same prompt and schema (or the same messages) in one call share the first answer, so make each question name what it covers ("delete invoice 17?", not "proceed?"), and keep it the same on every pass - a question that changes each time it is asked, with a timestamp in it, say, is never answered. All of one call's answers travel together, so together they must fit the server's request size limit (MaxRequestBytes in WithLimits) and the 1 MiB bound on the answers a call carries; a call whose answers outgrow them never completes, and nothing after the question runs. Whatever the implementation did before it asked is therefore done again, so ask before any side effect, or make what comes first repeatable. An implementation that swallows the error goes on with Refused, as if the client had declined, and the client is never asked: the question fails closed. Below 2026-07-28 the client is asked in the middle of the call, which does not run again, and the error reports only a failure to reach the client - return it the same way. Stateless Streamable HTTP - the default, without WithSessions - keeps no session to ask such a client on, so there it reads as a client without the capability. The pass that only asks is not audited: the call is recorded once, by the pass that answers.
A request with no message, or with a role other than RoleUser or RoleAssistant, is not sent: Sample returns Refused and an error saying why, which fails the call when returned.
Sampling is deprecated by the MCP specification as of protocol 2026-07-28 (SEP-2577) and stays functional through its deprecation window of at least twelve months; a server that needs generation beyond it should call a model provider's API itself.
type ServerInfo ¶
type ServerInfo struct {
// Name and Version are the implementation the server announced.
Name string
// Version is the server version the handshake announced.
Version string
// ProtocolVersion is the spec version the handshake negotiated.
ProtocolVersion string
// Capabilities lists the capabilities the server declared.
Capabilities []string
}
ServerInfo is what the initialize handshake announced about the remote server.
type Surface ¶
type Surface struct {
// contains filtered or unexported fields
}
Surface is the curated, exposed API: one immutable entry per exposed operation, sorted by final name, so identical inputs always yield identical surfaces. It is what a server serves and what the later pipeline steps - schema construction and invocation - consume.
A surface carries its construction problems instead of failing them at the entry: [Err] reports them, and the entry points refuse such a surface instead of serving it. A surface whose Err is non-nil exposes no operations, carries no warning and must never be served. A servable surface also carries the credential provider the Auth selection built, which the entry points wire onto the runner they serve with; a surface curated without Auth carries none.
func Curate ¶
Curate reflects over one iqlink API implementation, resolves its contract, applies the exposure policy and the curation directives, and returns the curated Surface: one immutable entry per exposed operation. It returns a single value - DESIGN_SPEC.md §4's second snippet passes a Curate call straight to Main, which only compiles when Curate has exactly one result - and construction problems are deferred onto the surface instead of a second error return: Surface.Err reports them, and the entry points (Main, Serve, Handler) refuse a surface with problems instead of serving it.
target is an API implementation or a Backend - what FromREST or FromOpenAPI returns, curated as the API it linked (decision 0049). A backend's construction problems join the curation's report, and its directives are still validated against the API's operations whenever the API's shape is known, so one report names everything to fix. Curating a backend also binds an entry-less oauth.PerUser delegation to the backend's own destination (policy.PerUserSource.ForBackend).
Addressing ¶
Directives address operations by their SOURCE names - the resolved names the contract produced, such as "current" or "issues.list" - or by their Go field paths, the dotted paths iqlink names the functions by, such as "Issues.List" for the List function of the Issues section (decision 0049). A Fix path addresses the operation either way and keeps the argument's own name: "Issues.List.per_page". A SOURCE name keeps precedence: a name that is some operation's SOURCE name addresses that operation, whatever field path it also spells. A field path that more than one operation spells - two functions named alike through api: tags - is ambiguous and is a collected problem; address such an operation by its SOURCE name. A name that addresses nothing is reported with the nearest SOURCE name as a hint. A Rename never changes addressing, so directives issued against the SOURCE name or the field path keep applying.
The exposure mode comes from the same stream as the directives: with Production only the allowlisted names are exposed; without it every operation is exposed, and unless an Only directive names the operations to serve, the loud expose-all warning is logged once with slog and carried on the surface. The credential source comes from the same stream too: with Auth the surface carries the provider the source built, which the entry points wire onto the runner; without it the server serves credential-less.
Every problem - backend construction problems, contract construction problems, policy problems and directive problems alike - is collected rather than failing at the first (DESIGN_SPEC.md A5, E22), so a bad implementation does not hide what else the directives get wrong: all of them are deferred onto the returned surface's Err. All reflection happens once, here; the surface is immutable afterwards.
Curate takes a single implementation, matching DESIGN_SPEC.md §4's second snippet. Mounting several structures on one server under distinct prefixes (DESIGN_SPEC.md A4) is not provided; the contract layer's mount is the seam such mounting would extend.
func Recurate ¶
Recurate re-curates an already-curated surface with additional shaping directives (ADR 0032): response projection (Fields), field redaction (Redact), pagination normalization (Paginate) and output budgets (Budget). Only shaping directives are accepted - any other directive kind is a collected problem - and the re-curation may only narrow the existing shaping: drop kept fields, add redactions, lower budgets. Widening is rejected; the original surface is never mutated. The returned surface shares the original's operations and credentials and carries the narrowed compiled shape; a surface whose Err is non-nil exposes no operations and must never be served.
func (*Surface) Err ¶
Err reports the curation's collected problems: nil when the surface is servable, or the one collected *Error - every contract, policy and directive problem - when it is not. Curate never returns nil and never fails at the first problem (DESIGN_SPEC.md A5, E22), so the problems are deferred here, and Main, Serve and Handler report them instead of serving the surface.
The accessor is Err, not a Problems slice, because the collected error is the value the entry points return: errors.As unwraps it to *Error for callers that want the individual problems. A non-nil Err is the "do not serve this" mark.
func (*Surface) Lookup ¶
Lookup finds an exposed operation by its final name. The returned operation's Fixed map and contract slices are copies, so a caller cannot mutate the surface.
func (*Surface) Operations ¶
Operations returns the exposed operations in final-name order. The slice, every Fixed map and every contract slice are copies, so a caller cannot mutate the surface.
func (*Surface) Snapshot ¶
Snapshot exports the surface's effective catalog as a configured snapshot: one entry per exposed operation, in canonical (kind, name) order, with the effective registration schemas after Fix, shaping, aliases and deprecation. A surface with deferred problems exports nothing: the collected report is the error. The result owns every map and slice, so a caller cannot mutate the surface through it.
type TaskLister ¶ added in v0.6.0
type TaskLister interface {
// CreateListed is [TaskStore.Create] keeping listing beside the
// record, written with it. It refuses a listing past the bound with an
// error wrapping [ErrTaskRecordTooLarge].
CreateListed(ctx context.Context, id, owner string, expires time.Time, data, listing []byte) error
// SwapListed is [TaskStore.Swap] replacing the listing with the
// record, in the same atomic write. A plain Swap leaves no listing: a
// listing never outlives the record it summarizes.
SwapListed(ctx context.Context, id string, version int64, data, listing []byte) (int64, error)
// ListTasks answers the live tasks owner holds - at most MaxTasks of
// them - each ID mapped onto the listing its record was last written
// with: nil for a record written without one, or one past the bound.
// It never reads a record. A task that expires while the list is read
// may still be named: the server checks every listing's owner and
// expiry, and reads the record of a task listed without one.
ListTasks(ctx context.Context, owner string) (map[string][]byte, error)
}
TaskLister is a TaskStore that can also list one owner's live tasks, which the tasks/list of the 2025-11-25 experimental tasks answers from (decision 0068). MemoryTaskStore and the store/redis and store/sql modules' stores implement it. A store that does not serves every other method; the server then declares no tasks.list capability at 2025-11-25 and answers tasks/list method-not-found.
A listing store keeps a listing beside each record: a short summary of it - opaque bytes of at most policy.TaskConfig.MaxListingBytes - that the server writes with the record, through CreateListed and SwapListed, and lists from, so a tasks/list never reads a record's body.
type TaskStore ¶ added in v0.6.0
type TaskStore interface {
// Create records a new task under id, owned by owner, holding data until
// expires. It refuses with an error wrapping [ErrTaskStoreFull] when the
// store already holds MaxTasks live tasks, or owner holds
// MaxTasksPerIdentity of them, and with one wrapping [ErrTaskConflict]
// when id is in use. The record's version is 1.
Create(ctx context.Context, id, owner string, expires time.Time, data []byte) error
// Load answers the live record id and its version, or an error wrapping
// [ErrTaskNotFound] when there is none or it has expired.
Load(ctx context.Context, id string) (data []byte, version int64, err error)
// Swap replaces the live record id with data when its version is still
// version, and answers the new version. It refuses with an error
// wrapping [ErrTaskConflict] when another writer replaced the record
// first, and with one wrapping [ErrTaskNotFound] when it is gone or
// expired. It never changes the record's owner or expiry.
Swap(ctx context.Context, id string, version int64, data []byte) (int64, error)
}
TaskStore keeps the records of the tasks WithTasks serves (DESIGN_SPEC.md B8, B10, F30). MemoryTaskStore and the store/redis and store/sql modules implement it; WithTaskStore hands one to the server, and replicas handed the same store answer each other's tasks.
A record is opaque bytes of at most policy.TaskConfig.MaxRecordBytes under a task ID, held for its owner - a hash of the tenant and subject that created the task, never the identity itself - until it expires, and versioned so two writers never overwrite each other blindly. The store enforces the bounds and the expiry and authorizes nothing: the server checks every request's caller against the record's owner, and keeps what only it may hold - the call, its credentials, the run - out of the store. Every method must be safe for concurrent use, by every server sharing the store.
type Text ¶
type Text struct {
Text string `json:"text"`
}
Text is a text block: the LLM-readable surface every rich result also carries as its fallback.
func (Text) MarshalJSON ¶
MarshalJSON writes the wire shape the protocol carries for a Text block: the {"type":"text",...} discriminated block the engine writes for its own text block. The method is on the value receiver so both the value and pointer forms marshal through it.
type ToolError ¶
type ToolError struct {
// Code is the failure's class; empty means "invocation".
Code string
// Message is the text the model reads.
Message string
// Retryable reports whether a repeated call may succeed.
Retryable bool
// RetryAfter is the least wait before a repeated call, when Retryable.
RetryAfter time.Duration
// Err is the underlying cause, for operators' diagnostics only.
Err error
}
ToolError is the error a tool implementation returns when the model should read why the call failed (decision 0057). Any other error reaches the model as the generic "the operation failed", because its text may carry internals - a backend's body, a path, a query - that the author never chose to show; a ToolError's Message is text the author wrote for the model, and it is shown:
if errors.Is(err, sql.ErrNoRows) {
return Order{}, &mcp.ToolError{Message: "no order has id " + id + "; list the orders to find one"}
}
if errors.Is(err, errInventoryDown) {
return Order{}, &mcp.ToolError{Code: "unavailable", Message: "the inventory service is down",
Retryable: true, RetryAfter: 5 * time.Second, Err: err}
}
The call answers with an isError tool result whose text is Message, redacted against the call's resolved credential and the caller's presented token and bounded to 1 KiB, followed by the correlation ID line; the result's _meta carries the class, retryability and retry-after under "io.github.iqhive.iqmcp/error". Err is the cause: like any error's text, it reaches the operator's redacted audit diagnostics only, never the model. An empty Message keeps the generic message.
Code is the failure's class in the closed vocabulary the server maps errors into: "decode", "invocation", "timeout", "unavailable" and "unknown" answer with the tool result above; "auth", "approval" and "credential" refuse the call at the protocol level instead, with Message as the refusal's text. Empty, or any other value, is "invocation", which is never retryable. Retryable says a repeated call may succeed, and RetryAfter the least a repeat should wait; WithRetries honours both for every class but "invocation", as it does for the Code()/Retryable() method seam the package documentation describes. A ToolError takes precedence over that seam anywhere in an error's errors.As chain.
Message is shown to the model, so it must not carry what the model must not see: the redaction catches the two secrets the server holds for the call, not everything an author might paste in.
func (*ToolError) Error ¶
Error renders the message, then the cause when there is one: the text operators' diagnostics record, never the text the model reads.
func (*ToolError) ToolFailure ¶
ToolFailure reports the failure as the server reads it: the class, the model-visible message, the retryability and the retry-after.
type TraceEnd ¶
type TraceEnd func(err error)
TraceEnd closes the span the trace hook opened for one call: the server calls it exactly once, on the final outcome. Err is nil on success and the pipeline's neutral error on failure - safe message, redacted diagnostics - so a span can never observe a secret the pipeline refused to ship.
type TraceStart ¶
TraceStart opens the span for one call and returns the context the server runs it under with the span's closer. Operation is the SOURCE name (never the wire rename), so traces never split on a presentation detail. Returning the incoming context unchanged is legal: the call simply runs untraced.
type Transport ¶
Transport is a wire a server serves over (DESIGN_SPEC.md A1). It is the adapter's transport handle re-exported under the root's name - the alias pattern Renderer uses - so an entry point's transport argument is nameable without importing the adapter. The value set is the adapter's to grow: Stdio and StdioOver are the ones v0 ships; Streamable HTTP is served through Handler and NewHandler, not a Transport.
func Stdio ¶
func Stdio() Transport
Stdio returns the process's standard streams as a transport (DESIGN_SPEC.md B7): newline-delimited JSON-RPC on stdin, responses on stdout, nothing else ever written to stdout. It is the transport Main serves by default and the one Serve takes for an explicitly stdio server.
func StdioOver ¶
func StdioOver(in io.ReadCloser, out io.Writer) Transport
StdioOver returns a stdio transport over the given streams - the seam tests and embedders drive instead of the process's own streams. The reader must end at EOF when its peer goes away (that EOF is the clean shutdown), and the writer is never closed by the server. A nil stream is a programmer error: the transport run refuses it before the engine runs, with a collected error naming the nil stream - the engine's read goroutine would otherwise dereference a nil reader and fault the process.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
bridge
|
|
|
openapi
Package openapi loads untrusted OpenAPI 3.0.x/3.1.x JSON documents into a bounded normalized model (ADR 0036).
|
Package openapi loads untrusted OpenAPI 3.0.x/3.1.x JSON documents into a bounded normalized model (ADR 0036). |
|
adapters
module
|
|
|
graphql
module
|
|
|
grpc
module
|
|
|
sqlquery
module
|
|
|
Package catalog is the stdlib-only tooling model for versioned catalog snapshots (ADR 0034): one effective catalog snapshot for lint, client discovery, testing and docs.
|
Package catalog is the stdlib-only tooling model for versioned catalog snapshots (ADR 0034): one effective catalog snapshot for lint, client discovery, testing and docs. |
|
cmd
|
|
|
iqmcp
command
Command iqmcp is the module's command-line tool (DESIGN_SPEC.md I38).
|
Command iqmcp is the module's command-line tool (DESIGN_SPEC.md I38). |
|
examples
|
|
|
curated
command
Command curated is DESIGN_SPEC.md §4's second snippet's shape made runnable: one expression imports a REST backend with mcp.FromREST, curates it with Only and Fix - addressed by the Go field paths the snippet uses - and hands it to mcp.Main.
|
Command curated is DESIGN_SPEC.md §4's second snippet's shape made runnable: one expression imports a REST backend with mcp.FromREST, curates it with Only and Fix - addressed by the Go field paths the snippet uses - and hands it to mcp.Main. |
|
deploy
command
Command deploy is a container-ready MCP server: the shape docs/deployment.md recommends for a Streamable HTTP service behind a platform probe.
|
Command deploy is a container-ready MCP server: the shape docs/deployment.md recommends for a Streamable HTTP service behind a platform probe. |
|
gallery/approval
command
Command approval serves one destructive tool beside one read-only tool and proves the E26 approval gate through the public pipeline: the read-only tool runs with nobody asked, and the destructive tool runs only once the calling client confirms it - mcp.WithClientApproval asks every client that declares elicitation "approve this destructive operation: publish", and denies a client that cannot be asked.
|
Command approval serves one destructive tool beside one read-only tool and proves the E26 approval gate through the public pipeline: the read-only tool runs with nobody asked, and the destructive tool runs only once the calling client confirms it - mcp.WithClientApproval asks every client that declares elicitation "approve this destructive operation: publish", and denies a client that cannot be asked. |
|
gallery/binary
command
Command binary serves one tool returning binary bytes as an io.Reader: the adapter renders the stream as one embedded octet-stream blob.
|
Command binary serves one tool returning binary bytes as an io.Reader: the adapter renders the stream as one embedded octet-stream blob. |
|
gallery/composite
command
Command composite serves one ordinary typed composite tool beside its two constituent tools: reading the shelf and fetching one book compose into a reading summary.
|
Command composite serves one ordinary typed composite tool beside its two constituent tools: reading the shelf and fetching one book compose into a reading summary. |
|
gallery/import
command
Command import proxies a typed specification end to end: a ledger-shaped REST backend described the iqlink way is imported by mcp.FromREST and served over stdio - the typed-import half of DESIGN_SPEC.md K46's import scenarios, dependency-free and offline.
|
Command import proxies a typed specification end to end: a ledger-shaped REST backend described the iqlink way is imported by mcp.FromREST and served over stdio - the typed-import half of DESIGN_SPEC.md K46's import scenarios, dependency-free and offline. |
|
gallery/job
command
Command job serves a long-running job as a streaming tool: the Go implementation returns an iter.Seq of progress strings and the adapter accumulates the elements into the result, reporting progress per element.
|
Command job serves a long-running job as a streaming tool: the Go implementation returns an iter.Seq of progress strings and the adapter accumulates the elements into the result, reporting progress per element. |
|
gallery/mux
command
Command mux mounts the package's Streamable HTTP handler inside an existing net/http mux: the MCP server lives beside the application's own routes - here a /healthz liveness probe, which mcp.WithHealthPath gives only to a listener mcp.Main owns - instead of owning the listener.
|
Command mux mounts the package's Streamable HTTP handler inside an existing net/http mux: the MCP server lives beside the application's own routes - here a /healthz liveness probe, which mcp.WithHealthPath gives only to a listener mcp.Main owns - instead of owning the listener. |
|
gallery/offline
command
Command offline drives a server with the testing harness (mcptest) and nothing else: no listener, no network, no subprocess.
|
Command offline drives a server with the testing harness (mcptest) and nothing else: no listener, no network, no subprocess. |
|
gallery/openapi
command
Command openapi binds one OpenAPI JSON document as a runtime-linkable API value and serves it over stdio - DESIGN_SPEC.md K46's "OpenAPI-to-MCP in 10 lines", dependency-free and offline.
|
Command openapi binds one OpenAPI JSON document as a runtime-linkable API value and serves it over stdio - DESIGN_SPEC.md K46's "OpenAPI-to-MCP in 10 lines", dependency-free and offline. |
|
gallery/search
command
Command search serves a paginated, read-only search tool over an in-memory catalogue: page and per_page arguments slice the matches, and the result carries the total so the caller can page to the end.
|
Command search serves a paginated, read-only search tool over an in-memory catalogue: page and per_page arguments slice the matches, and the result carries the total so the caller can page to the end. |
|
generated
command
Package main is the S3-09 static-generation example (ADR 0036 § static generation): the generated model in api_gen.go is committed source produced from spec.json by the iqmcp gen command below - never hand-written, never fetched from the network.
|
Package main is the S3-09 static-generation example (ADR 0036 § static generation): the generated model in api_gen.go is committed source produced from spec.json by the iqmcp gen command below - never hand-written, never fetched from the network. |
|
github
command
Command github is DESIGN_SPEC.md K46's "GitHub via rest.Import" example and D17's one-line promise made runnable: a GitHub-shaped REST API imported by mcp.FromREST and served over stdio.
|
Command github is DESIGN_SPEC.md K46's "GitHub via rest.Import" example and D17's one-line promise made runnable: a GitHub-shaped REST API imported by mcp.FromREST and served over stdio. |
|
quickstart
command
Command quickstart is DESIGN_SPEC.md §4's first snippet, made runnable: the Weather structure and the one-line mcp.Main call serve stdio exactly as the specification writes them - protocol frames on stdout, run with no flags, or Streamable HTTP with -addr host:port.
|
Command quickstart is DESIGN_SPEC.md §4's first snippet, made runnable: the Weather structure and the one-line mcp.Main call serve stdio exactly as the specification writes them - protocol frames on stdout, run with no flags, or Streamable HTTP with -addr host:port. |
|
internal
|
|
|
bridgekit
Package bridgekit is the shared egress/dial/transport plumbing the bridge modules (bridge/grpc, bridge/graphql, and the future bridge/sqlquery) build on.
|
Package bridgekit is the shared egress/dial/transport plumbing the bridge modules (bridge/grpc, bridge/graphql, and the future bridge/sqlquery) build on. |
|
cli
Package cli is the command dispatch behind cmd/iqmcp (Stage 3 S3-06, ADR 0038): literal subcommand matching with injected context, I/O and narrow client/process seams.
|
Package cli is the command dispatch behind cmd/iqmcp (Stage 3 S3-06, ADR 0038): literal subcommand matching with injected context, I/O and narrow client/process seams. |
|
cli/testhelper
command
Command clitesthelper is the test-only child process the S3-06 process tests own: it speaks fixed modes on explicit argv (never a shell), so the parent can prove env sanitization, no shell expansion, bounded redacted stderr, and grandchild reaping.
|
Command clitesthelper is the test-only child process the S3-06 process tests own: it speaks fixed modes on explicit argv (never a shell), so the parent can prove env sanitization, no shell expansion, bounded redacted stderr, and grandchild reaping. |
|
clientconfig
Package clientconfig generates versioned client configuration profiles (Stage 3 S3-11, ADR 0037): a neutral Profile model plus deterministic JSON rendering for source-verified clients only (claude and cursor, verified against the official client docs ADR 0037 cites per emitted field; anything uncited is omitted).
|
Package clientconfig generates versioned client configuration profiles (Stage 3 S3-11, ADR 0037): a neutral Profile model plus deterministic JSON rendering for source-verified clients only (claude and cursor, verified against the official client docs ADR 0037 cites per emitted field; anything uncited is omitted). |
|
cmd/conformanceserver
command
Command conformanceserver is the fixture the official MCP conformance suite (@modelcontextprotocol/conformance, its server scenarios) drives in CI.
|
Command conformanceserver is the fixture the official MCP conformance suite (@modelcontextprotocol/conformance, its server scenarios) drives in CI. |
|
cmd/readmegen
command
Command readmegen generates README.md from docs/README.tmpl.md and the repository's own records, and validates IMPLEMENTATION_PLAN.md.
|
Command readmegen generates README.md from docs/README.tmpl.md and the repository's own records, and validates IMPLEMENTATION_PLAN.md. |
|
cmd/releasecheck
command
Command releasecheck proves that the release recorded in docs/release.json can be installed by a user outside this repository (DESIGN_SPEC.md K44, J42; decision 0029's S4-19 note).
|
Command releasecheck proves that the release recorded in docs/release.json can be installed by a user outside this repository (DESIGN_SPEC.md K44, J42; decision 0029's S4-19 note). |
|
cmd/taskserver
command
Command taskserver is the fixture the TypeScript SDK interop harness (internal/interop/ts, decision 0046) drives the 2025-11-25 experimental tasks with (S4-44, decision 0068): a stdio server built only from this module's public API that serves Build and Hold as tasks - Build answers after a moment, Hold until it is cancelled - and Echo synchronously, as a fixed local identity, so its callers' tasks can be listed.
|
Command taskserver is the fixture the TypeScript SDK interop harness (internal/interop/ts, decision 0046) drives the 2025-11-25 experimental tasks with (S4-44, decision 0068): a stdio server built only from this module's public API that serves Build and Hold as tasks - Build answers after a moment, Hold until it is cancelled - and Echo synchronously, as a fixed local identity, so its callers' tasks can be listed. |
|
codegen
Documentation emission from the effective catalog snapshot (Stage 3 S3-10 slice a, ADR 0036): CatalogMarkdown and CatalogHTML render the same effective catalog.Snapshot the dynamic and static paths consume.
|
Documentation emission from the effective catalog snapshot (Stage 3 S3-10 slice a, ADR 0036): CatalogMarkdown and CatalogHTML render the same effective catalog.Snapshot the dynamic and static paths consume. |
|
contract
Package contract builds the normalized MCP view of one or more iqlink API structures.
|
Package contract builds the normalized MCP view of one or more iqlink API structures. |
|
contract/testapi
Package testapi holds the API structures the contract tests reflect over.
|
Package testapi holds the API structures the contract tests reflect over. |
|
contract/testapi/a3api
Package a3api holds DESIGN_SPEC.md A3's three tag-driven declarations exactly as the design writes them, so a test can serve them as written: a readonly tool, a resource and a prompt, the last two with no hint: tag and the prompt with no docs: tag.
|
Package a3api holds DESIGN_SPEC.md A3's three tag-driven declarations exactly as the design writes them, so a test can serve them as written: a readonly tool, a resource and a prompt, the last two with no hint: tag and the prompt with no docs: tag. |
|
contract/testapi/flattenapi
Package flattenapi holds the API structures the contract tests use to pin DESIGN_SPEC.md A4's flattening of nested sections into namespaced tool names.
|
Package flattenapi holds the API structures the contract tests use to pin DESIGN_SPEC.md A4's flattening of nested sections into namespaced tool names. |
|
contract/testapi/inferapi
Package inferapi holds the API structures the contract tests use to exercise DESIGN_SPEC.md A3's default-kind inference.
|
Package inferapi holds the API structures the contract tests use to exercise DESIGN_SPEC.md A3's default-kind inference. |
|
contract/testapi/nosource
Package nosource deliberately does not embed its source, so iqlink cannot recover Go parameter names for it.
|
Package nosource deliberately does not embed its source, so iqlink cannot recover Go parameter names for it. |
|
invoke
The server-enforced approval seam (DESIGN_SPEC.md B8, E26, S2-16): the context-carried approver a destructive call consults before it resolves credentials or runs the implementation.
|
The server-enforced approval seam (DESIGN_SPEC.md B8, E26, S2-16): the context-carried approver a destructive call consults before it resolves credentials or runs the implementation. |
|
invoke/testapi
Package testapi holds the API structure the invoke tests curate and invoke.
|
Package testapi holds the API structure the invoke tests curate and invoke. |
|
jose
The issuer discovery (DESIGN_SPEC.md E23; S4-22): reading an external IdP's authorization-server metadata (RFC 8414) or OpenID Connect discovery document for the one value a resource server needs from it - the jwks_uri its signing keys are published at.
|
The issuer discovery (DESIGN_SPEC.md E23; S4-22): reading an external IdP's authorization-server metadata (RFC 8414) or OpenID Connect discovery document for the one value a resource server needs from it - the jwks_uri its signing keys are published at. |
|
outbound
The outbound HTTP call client for bridged OpenAPI operations (Stage 3 S3-08 slice c, ADR 0036): a bounded, stdlib-only executor shared by the dynamic bridge.
|
The outbound HTTP call client for bridged OpenAPI operations (Stage 3 S3-08 slice c, ADR 0036): a bounded, stdlib-only executor shared by the dynamic bridge. |
|
protocol
Package protocol adapts the repository's model to the MCP protocol engine: it constructs the pinned engine's server (decision D1, docs/verification/protocol.md) from the curated surface's operations, drives every tool call through invoke.Runner, and translates the pipeline's neutral errors onto the wire (DESIGN_SPEC.md B12).
|
Package protocol adapts the repository's model to the MCP protocol engine: it constructs the pinned engine's server (decision D1, docs/verification/protocol.md) from the curated surface's operations, drives every tool call through invoke.Runner, and translates the pipeline's neutral errors onto the wire (DESIGN_SPEC.md B12). |
|
protocol/protocoltest
Package protocoltest holds the API structure the protocol adapter tests curate and serve.
|
Package protocoltest holds the API structure the protocol adapter tests curate and serve. |
|
serving
Package serving is the entry points' option configuration (S4-17, decision 0047): the recorded option list behind the root's `type Option func(*options)`, the transport-kind table, the validation that turns every misuse into a collected startup problem (DESIGN_SPEC.md A5), and the translation of the options honoured on the served transport into the invoke runner and the adapter's server, HTTP and SSE options.
|
Package serving is the entry points' option configuration (S4-17, decision 0047): the recorded option list behind the root's `type Option func(*options)`, the transport-kind table, the validation that turns every misuse into a collected startup problem (DESIGN_SPEC.md A5), and the translation of the options honoured on the served transport into the invoke runner and the adapter's server, HTTP and SSE options. |
|
sessionstore
Package sessionstore holds the security-critical derivation the durable session-store backends share (DESIGN_SPEC.md B10; decision 0041): the composite (tenant, identity) scope hash, the opaque key escaping, and the credential redactor.
|
Package sessionstore holds the security-critical derivation the durable session-store backends share (DESIGN_SPEC.md B10; decision 0041): the composite (tenant, identity) scope hash, the opaque key escaping, and the credential redactor. |
|
taskstoretest
Package taskstoretest is the task-store contract every backend is held to (S4-42, decision 0066): the memory store in the core, and the store/redis and store/sql modules' stores, run the same suite, so a backend can never drift from the semantics the tasks layer relies on - the version compare-and-swap, the bounds across every instance sharing a backend, the expiry and the record bound - the way the session stores share their fixtures (internal/sessionstore).
|
Package taskstoretest is the task-store contract every backend is held to (S4-42, decision 0066): the memory store in the core, and the store/redis and store/sql modules' stores, run the same suite, so a backend can never drift from the semantics the tasks layer relies on - the version compare-and-swap, the bounds across every instance sharing a backend, the expiry and the record bound - the way the session stores share their fixtures (internal/sessionstore). |
|
Package oauth is a server's OAuth side: the per-user delegated credential sources it hands to the root package's [Auth] directive (DESIGN_SPEC.md D21, decision 0015), and the resource server's JWKS-backed bearer validator (E23, decision 0050).
|
Package oauth is a server's OAuth side: the per-user delegated credential sources it hands to the root package's [Auth] directive (DESIGN_SPEC.md D21, decision 0015), and the resource server's JWKS-backed bearer validator (E23, decision 0050). |
|
otel
module
|
|
|
Package policy classifies the risk of backend operations (DESIGN_SPEC.md E26) and decides which of them a server exposes (DESIGN_SPEC.md E22), then applies curation directives - Only, Except, Rename, Describe, Fix and Hide (DESIGN_SPEC.md D20) - over a neutral, policy-local view of the operations.
|
Package policy classifies the risk of backend operations (DESIGN_SPEC.md E26) and decides which of them a server exposes (DESIGN_SPEC.md E22), then applies curation directives - Only, Except, Rename, Describe, Fix and Hide (DESIGN_SPEC.md D20) - over a neutral, policy-local view of the operations. |
|
router
module
|
|
|
Package schema turns Go types into JSON Schema (draft 2020-12) for MCP tool arguments and results.
|
Package schema turns Go types into JSON Schema (draft 2020-12) for MCP tool arguments and results. |
|
store
|
|
|
redis
module
|
|
|
sql
module
|
|
|
Package testing is the in-process MCP test client (DESIGN_SPEC.md I36): it drives the public pipeline from an API implementation to a live in-process server and presents the operations a test needs - list the tools, call one, inspect the server - without ports.
|
Package testing is the in-process MCP test client (DESIGN_SPEC.md I36): it drives the public pipeline from an API implementation to a live in-process server and presents the operations a test needs - list the tools, call one, inspect the server - without ports. |