mcp

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 38 Imported by: ? modules, 0 packages

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

README

iqmcp

CI Go Reference Go Report Card Latest release Go version

Serve a Go struct of functions as a Model Context Protocol server, with typed tools, generated schemas and production controls built in.

Why iqmcp?

  • Your Go types are the contract. Write a struct of functions. Tool names, descriptions and the input and output JSON Schemas come from the signatures and a few struct tags, so there is no second schema and no handler boilerplate to keep in sync. Every call is checked against the schema it advertises before your function runs.
  • Bring the backends you already have. Serve a REST API (mcp.FromREST) or an OpenAPI document (mcp.FromOpenAPI) as tools, and call any MCP server through a typed Go struct (mcp.Import).
  • Curate what a model sees. Directives such as Only, Rename, Fix, Hide, Redact and Paginate decide which operations are exposed and in what shape.
  • Safe defaults. A misconfiguration stops the server at startup instead of serving. Bearer authentication (JWKS-validated JWTs or API keys), per-tool scopes, tenant isolation, server-side approval of destructive tools, an egress guard, limits and per-call deadlines are options you turn on; each one has a test that drives it through the public API.
  • Built on the official SDK. The protocol is handled by modelcontextprotocol/go-sdk, over stdio and Streamable HTTP, for MCP revisions 2024-11-05 through 2026-07-28. An in-process harness tests your server without a network.

How it compares

iqmcp is a layer on top of the official Go SDK, not a replacement for it. The table compares the server-building experience. It was checked on 3 October 2026 against the projects' READMEs and repositories, at go-sdk v1.8.0 and mcp-go v1.1.1; iqmcp v0.4.0 pins go-sdk v1.7.0.

iqmcp go-sdk (official) mcp-go
What it is Framework: a Go contract served as an MCP server The official SDK: protocol, server and client Community SDK: server and client
Defining a tool A function field on a struct, with tags mcp.AddTool with typed input and output structs mcp.NewTool with option builders, or typed struct handlers
Schemas Generated from the Go signature and tags Inferred from the input and output types (jsonschema tags) Built with options, or derived from structs
REST and OpenAPI backends Built in (FromREST, FromOpenAPI) Not included Not included
Calling other MCP servers Typed Go facade (mcp.Import) over the SDK client Full client Full client
Transports stdio, Streamable HTTP, legacy SSE (opt-in) stdio, command, Streamable HTTP, SSE, in-memory stdio, Streamable HTTP, SSE, in-process
MCP revisions 2024-11-05 to 2026-07-28 2024-11-05 to 2026-07-28 2024-11-05 to 2025-11-25
Auth Bearer auth over JWKS JWT or API-key validators, RFC 9728 metadata, per-user backend credentials OAuth building blocks (auth, oauthex) RFC 9728 protected-resource metadata
Authorization and approval Per-tool scopes, tenant isolation, server-side approval of destructive tools You build it You build it (hooks and middleware)
Tasks (long-running work) Not yet Not yet (go-sdk#626) Yes
Testing In-process harness (mcptest) In-memory transports mcptest package
Licence Apache-2.0 Apache-2.0 for new code, MIT for existing code MIT
Maturity Pre-1.0, one maintainer v1 releases, maintained with the MCP project v1 releases, widely used

Use the go-sdk directly when you need full control of the protocol or a general-purpose client. Pick mcp-go if you want its builder API or need tasks today. Use iqmcp if you want a Go contract to become a curated, authenticated server with little code. See Status and stability before you depend on it.

Contents

Quick start

You need Go 1.25 or later. A whole server is a struct of functions and one call. This is the complete file, quoted from a tested example:

package main

import (
	"context"

	mcp "github.com/iqhive/iqmcp"
	"github.com/iqhive/runtime.link/api"
)

// Report and current are the snippet's implementation; the specification
// leaves them to the reader.
type Report struct {
	Summary string  `json:"summary"`
	TempC   float64 `json:"temp_c"`
}

func current(_ context.Context, city string) (Report, error) {
	return Report{Summary: "sunny in " + city, TempC: 21.5}, nil
}

type Weather struct {
	api.Specification `api:"Weather" docs:"provides current conditions."`

	Current func(ctx context.Context, city string) (Report, error) `mcp:"tool" hint:"readonly" docs:"returns the current weather for a city"`
}

func main() { mcp.Main(Weather{Current: current}) } // stdio by default, -addr for HTTP

Source: examples/quickstart/main.go.

Save it as main.go in a new directory, then run it:

go mod init example.com/weather
go mod tidy                          # fetches github.com/iqhive/iqmcp and github.com/iqhive/runtime.link
go run .                             # serves MCP over stdio
go run . -addr 127.0.0.1:8080        # or Streamable HTTP on http://127.0.0.1:8080/mcp

Call the tool from a terminal with the iqmcp command:

$ go install github.com/iqhive/iqmcp/cmd/iqmcp@latest
$ go build -o weather .
$ iqmcp call --tool current --args '{"city":"Paris"}' -- ./weather
{"isError":false,"structured":{"summary":"sunny in Paris","temp_c":21.5},"text":"{\"summary\":\"sunny in Paris\",\"temp_c\":21.5}","tool":"current"}

The server also logs a warning on stderr: with no curation, every operation is exposed to every client. The 5-minute quickstart shows how to curate the surface and connect a client.

The argument name city is read from main.go when the program starts, so go run and go build work as written. A binary built with -trimpath, or deployed without its source, refuses to start and says how to fix it: tag the argument (args:"city") or embed the source. The deployment example does the former.

Connect a client

Build the server to a binary first; clients start it with an absolute path. iqmcp gen config prints a client configuration with credentials as environment-variable references, never values (recipe).

Claude Code - add it with the claude command:

claude mcp add weather -- /absolute/path/to/weather                      # stdio
claude mcp add --transport http weather http://127.0.0.1:8080/mcp       # Streamable HTTP

Claude Desktop - generate the entry and merge it into claude_desktop_config.json:

$ iqmcp gen config --client claude --label weather --command /absolute/path/to/weather
{"mcpServers":{"weather":{"command":"/absolute/path/to/weather","args":[],"env":{}}}}

Cursor - generate the entry and merge it into .cursor/mcp.json (or ~/.cursor/mcp.json):

$ iqmcp gen config --client cursor --label weather --url http://127.0.0.1:8080/mcp
{"mcpServers":{"weather":{"url":"http://127.0.0.1:8080/mcp"}}}

VS Code - iqmcp gen config has no verified VS Code profile yet (it prints manual steps and exits 3). Add the server to .vscode/mcp.json by hand, following the VS Code documentation:

{
  "servers": {
    "weather": { "type": "stdio", "command": "/absolute/path/to/weather" }
  }
}

These configuration shapes were checked against each client's documentation. Live-client testing is listed under Compatibility.

Installation

go get github.com/iqhive/iqmcp@latest
go install github.com/iqhive/iqmcp/cmd/iqmcp@latest

The first line adds the library; the core module is the one import most programs need. The second installs the optional iqmcp command.

Optional modules

Integrations that bring third-party dependencies are separate modules, so none of them enters a core consumer's module graph:

Module Purpose Install
github.com/iqhive/iqmcp/otel OpenTelemetry spans and metrics for mcp.WithObserver. go get github.com/iqhive/iqmcp/otel@latest
github.com/iqhive/iqmcp/store/redis Redis event store for mcp.WithSessions (stream resumption; sticky routing still required). go get github.com/iqhive/iqmcp/store/redis@latest
github.com/iqhive/iqmcp/store/sql database/sql event store for mcp.WithSessions; bring your own driver. go get github.com/iqhive/iqmcp/store/sql@latest
github.com/iqhive/iqmcp/bridge/grpc Unary gRPC backend client for tool implementations. go get github.com/iqhive/iqmcp/bridge/grpc@latest
github.com/iqhive/iqmcp/bridge/graphql Curated GraphQL operations over HTTPS; standard library only. go get github.com/iqhive/iqmcp/bridge/graphql@latest
github.com/iqhive/iqmcp/bridge/sqlquery Curated, parameterized SQL read statements over your *sql.DB. go get github.com/iqhive/iqmcp/bridge/sqlquery@latest

All 7 modules are released together at one version (v0.4.0, recorded in docs/release.json), and each optional module requires the core at that same version. Most optional modules use the core's internal packages, which carry no compatibility promise between versions, so use every iqmcp module at the same version and upgrade them together, naming each module you use in one go get:

go get github.com/iqhive/iqmcp@latest github.com/iqhive/iqmcp/otel@latest

Releases up to v0.3.0 were published as github.com/iqhive/mcpserver; the CHANGELOG says how to move to the new module path.

The iqmcp command

Command What it does
iqmcp serve [-addr host:port] Serves a small built-in demo API (one read-only tool) over stdio, or Streamable HTTP with -addr, so a client can be pointed at something immediately; iqmcp serve --spec PATH --base-url URL --op ID... serves chosen operations of an OpenAPI document - only those are checked against the supported OpenAPI profile, and --skip-unsupported skips (and reports) any of them outside it.
iqmcp inspect -- ./server Starts a server binary over stdio, or reaches one with --url - a local one too - and prints its identity and operations; --bearer-env NAME sends the token the environment variable NAME holds.
iqmcp call --tool NAME --args JSON -- ./server Calls one tool and prints the result.
iqmcp lint, iqmcp diff, iqmcp doctor Offline, read-only analysis of catalog snapshots and the local environment (CLI recipe).
iqmcp gen Offline generation: a static Go model from an OpenAPI document, a catalog, OpenAPI documentation, or a client configuration (iqmcp gen config).
iqmcp exec -- BINARY [args...] Runs one allowlisted binary, argv only, bounded.
iqmcp version Prints the build metadata.
iqmcp help Lists every command, one line each, with its flags.

iqmcp inspect and iqmcp call start the server binary with a scrubbed environment (PATH and PWD only), so point them at a built binary, not at go run. The command builds for Linux, macOS and Windows; it has been run on Linux only (not yet supported).

Features

Define tools from Go

  • Function fields on a struct become tools. Arguments and results (structs, slices, maps, pointers, times) map to JSON Schema, while context.Context and error are handled for you (struct tag reference).
  • The bounds, patterns and enums the schema advertises are enforced: a call that breaks one, or sends a property the schema does not list, is refused with a message the model can act on, and your function never runs.
  • hint: tags become MCP tool annotations (readOnlyHint, destructiveHint, idempotentHint, and openWorldHint for imported REST and OpenAPI backends) - hints for the client; the server enforces approval itself.
  • Return an mcp.ToolError to tell the model why a call failed; any other error reaches it only as a correlation ID (tool errors).
  • Streaming results (iter.Seq), binary results (io.Reader), resources and prompts (tools vs. resources).
  • Progress, client logging, sampling, elicitation and roots from inside a call (asking the client).

Bring existing APIs

  • REST backends with mcp.FromREST and OpenAPI documents with mcp.FromOpenAPI (migration).
  • Static Go models generated from OpenAPI by iqmcp gen (code generation).
  • Any MCP server as a typed Go struct with mcp.Import (typed import).
  • gRPC, GraphQL and SQL bridge modules (see Optional modules).

Curate the surface

Secure it

  • Bearer authentication over JWKS-validated JWTs or API keys, and RFC 9728 protected-resource metadata (auth, OAuth resource server).
  • auth: scopes per tool, tenant isolation, server-side approval of destructive tools, and per-user delegated backend credentials.
  • Origin and host allowlists, limits, deadlines and an egress guard for imported backends (threat model).

Run it in production

  • Stateless Streamable HTTP by default; resumable sessions with memory, Redis or SQL event stores.
  • Bulkheads, circuit breakers, retries and idempotency keys (resilience).
  • Audit stream, metrics and tracing (OpenTelemetry module), health endpoint, and a container and Kubernetes example (deployment).

How it works

flowchart LR
    S["Go struct of functions<br/>(runtime.link API)"] --> C
    R["REST API or<br/>OpenAPI document"] -->|"FromREST / FromOpenAPI"| C
    C["Curate<br/>Only, Rename, Fix, Redact ..."] --> P
    P["Policy pipeline<br/>auth, scopes, approval,<br/>limits, audit"] --> E
    E["Protocol engine<br/>official go-sdk"] --> T1["stdio"]
    E --> T2["Streamable HTTP"]
    T1 --> M["MCP clients<br/>Claude, Cursor, VS Code ..."]
    T2 --> M

At startup, iqmcp reflects over your struct with runtime.link, builds one tool per function field, applies your curation directives and options, and refuses to start if any of them is invalid. Each call then runs through the policy pipeline (identity, scopes, approval, limits, deadline, audit) before your function runs.

For example, this field from the quick start:

Current func(ctx context.Context, city string) (Report, error) `mcp:"tool" hint:"readonly" docs:"returns the current weather for a city"`

is listed to a client as this tool (from tools/list):

{
  "name": "current",
  "description": "returns the current weather for a city",
  "annotations": { "readOnlyHint": true, "destructiveHint": false, "idempotentHint": false },
  "inputSchema": {
    "type": "object",
    "properties": { "city": { "type": "string" } },
    "required": ["city"],
    "additionalProperties": false
  },
  "outputSchema": {
    "type": "object",
    "properties": { "summary": { "type": "string" }, "temp_c": { "type": "number" } },
    "required": ["summary", "temp_c"],
    "additionalProperties": false
  }
}

Examples

Every example is a complete program with a test that runs offline. Each directory's README shows how to run it and its real output; the examples index and the gallery index have more detail.

Example What it shows Run
quickstart The smallest server: a struct of functions and mcp.Main go run ./examples/quickstart
curated A REST API imported with mcp.FromREST, cut to two tools with Only and Fix BACKEND=http://127.0.0.1:8080 go run ./examples/curated
github A GitHub REST endpoint served as a tool, with a credential header GITHUB_TOKEN=... go run ./examples/github
generated A Go model generated from an OpenAPI document by iqmcp gen go run ./examples/generated
deploy A production-shaped server with bearer auth and a health path, plus a Dockerfile and Kubernetes manifest go test ./examples/deploy, then see its README
gallery/search Paginated, read-only search with structured results go run ./examples/gallery/search
gallery/approval A destructive tool that runs only after the client confirms go run ./examples/gallery/approval
gallery/binary Bytes returned as an io.Reader, served as a binary resource go run ./examples/gallery/binary
gallery/job A long-running job streaming progress through an iter.Seq result go run ./examples/gallery/job
gallery/mux mcp.Handler mounted in your own net/http mux go run ./examples/gallery/mux
gallery/offline Testing a server in process with the mcptest harness go test -v ./examples/gallery/offline
gallery/import A typed REST backend proxied as tools BACKEND=http://127.0.0.1:8080 go run ./examples/gallery/import
gallery/openapi An embedded OpenAPI document served with mcp.FromOpenAPI BACKEND=http://127.0.0.1:8080 go run ./examples/gallery/openapi
gallery/composite One tool composed from two, with per-step scope checks and an identity source SHELF_OPERATOR=ada SHELF_TOKEN=... go run ./examples/gallery/composite
hero The tooling behind the animation at the top of this page make hero

The curated example shows the REST path in full: import, curate and serve in one statement.

package main

import (
	"context"
	"os"

	mcp "github.com/iqhive/iqmcp"
	"github.com/iqhive/runtime.link/api"
)

// Catalogue is a small read-only REST backend described the runtime.link way:
// every function field carries the rest: tag of its endpoint and the args:
// tags naming its arguments - an imported API's source is not embedded, so
// runtime.link cannot recover the Go parameter names on its own.
type Catalogue struct {
	api.Specification `api:"Catalogue" docs:"a small read-only product catalogue."`

	Products productSection
}

type productSection struct {
	api.Specification `api:"Products" docs:"catalogue queries."`

	List func(ctx context.Context, perPage int) ([]Product, error) `rest:"GET /products?per_page=%v" mcp:"tool" hint:"readonly" args:"per_page" docs:"lists products, newest first."`
	Get  func(ctx context.Context, id string) (Product, error)     `rest:"GET /products/{id=%v}" mcp:"tool" hint:"readonly" args:"id" docs:"fetches one product."`
}

type Product struct {
	ID    string  `json:"id"`
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

func main() {
	backend := os.Getenv("BACKEND")
	if backend == "" {
		backend = "http://127.0.0.1:8080"
	}

	// DESIGN_SPEC.md §4's second snippet's shape: one statement of intent
	// imports, curates and serves. FromREST and Curate each defer their
	// construction problems onto the value they return, and Main prints
	// them on stderr and exits 1 instead of serving. Directives address
	// operations by their Go field paths ("Products.List") or their tool
	// names ("products.list").
	mcp.Main(mcp.Curate(mcp.FromREST[Catalogue](backend),
		mcp.Only("Products.List", "Products.Get"),
		mcp.Fix("Products.List.per_page", 25),
	))
}

Source: examples/curated/main.go.

Compatibility

Supported Notes
Go go 1.25.0 and later Tested with go1.25.0, go1.26.0, go1.27.0, go1.27.1 on linux/amd64
MCP revisions 2026-07-28, 2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05 Negotiated per client; the newest is the default
Protocol engine MCP Go SDK (official) v1.7.0 The only protocol dependency
Clients Tested in CI: MCP TypeScript SDK client (@modelcontextprotocol/sdk) Not yet tested live: Claude Code, Claude, Cursor (configuration shapes checked against their docs)

The evidence for every row, the dependency versions and the known limitations are in docs/compatibility.md. How long older protocol revisions and deprecated features are kept is in the protocol and deprecation policy.

Status and stability

iqmcp is pre-1.0. It follows semantic versioning with the usual pre-1.0 rule: a minor release (v0.x.0) may change the public API, and a patch release (v0.x.y) only fixes. Breaking changes are called out in the release notes. What this README lists as supported is implemented and tested; SECURITY.md says which versions receive security fixes.

Not yet supported

These are known gaps. The roadmap says what is planned.

  • Tasks and long-running work. The MCP tasks extension waits on the official Go SDK, which has no tasks support yet (go-sdk#626). A tool can report progress and stream its results today, but a background job with a handle to poll cannot be served.
  • Job and event adapters, and adapters for existing clients. They are built on tasks.
  • A routing extension for agent builders. Waiting on a design.
  • Typed argument and result transform hooks. Deferred; the hooks that exist today are in the Security table.
  • More than one replica without sticky routing. Sessions, discovery cursors and idempotency windows live in the serving process. Route sticky, or run one replica (deployment).
  • Running on Windows or macOS. Every module, the iqmcp command included, builds and is vetted for windows/amd64 and darwin/arm64, and CI builds them on Windows and macOS runners, but the tests run on linux/amd64 only. On Windows the command holds a started server in a job object so stopping it ends its descendants too.

Documentation

For contributors

Security

Report vulnerabilities privately, never in public issues: SECURITY.md gives the channels, supported versions and response targets. The threat model lists the trust boundaries, the tests behind each control and the accepted residual risks. The deployment guide covers running it safely. CI runs govulncheck on every module for each push to main and each pull request, and the official MCP conformance suite's server scenarios: 27 of 30 pass, and the three that fail - a binary resource read, and resource subscribe and unsubscribe - are listed in its baseline.

The table below lists each production control: whether a program can turn it on through the public API, how, and a test that proves it through a public entry point. The generator checks every row against the code.

Production controls and their public-path proofs
Control Publicly configurable How Public-path proof
Incoming bearer authentication (Streamable HTTP) yes mcp.WithBearerAuth(validator, scopes...) over any policy.Validator; a refused, missing or anonymous token is 401 with a fixed body TestHandlerBearerAuthRunsScopedToolAsVerifiedCaller, TestHandlerBearerAuthRefusesMissingInvalidAnonymousAndPanickingValidators
Local peer identity (stdio) yes mcp.WithStdioIdentity(id), the operator's assertion; refused on every network transport TestStdioIdentityServesScopedTools, TestStdioIdentityRefusedOnNetwork
Identity-aware discovery, execution re-check, tenant isolation yes auth: tags under the default engine; mcp.WithAuthorization(engine) replaces it (probed at startup) TestHandlerBearerAuthHidesAndDeniesUnscopedTool, TestHandlerBearerAuthTenantIsolation, TestWithAuthorizationCanaryRefusesUnsafeEngines
Caller identity and credential inside an implementation yes mcp.IdentityFromContext, mcp.CredentialFromContext TestIdentityFromContextInsideAndOutsideCalls, TestCredentialFromContextOnlyWhenResolved
Per-user delegated backend credentials yes, with an identity source mcp.Auth(oauth.PerUser(exchange, ...)); the exchange receives the verified subject and, over bearer auth, the presented token as a redacting policy.SubjectToken; with no entries the token is bound to the curated mcp.FromREST/mcp.FromOpenAPI backend's host alone TestSnippetShapeServesPerUserOverBearerPublicly, TestSnippetTwoDelegatesOverStdio
Server-configured backend credentials (static per tenant, or your own provider) yes mcp.Auth(policy.ProviderSource(provider)), e.g. over policy.NewStaticCredentials; the one credential path beside oauth.PerUser TestProviderSourceServesEachTenantItsOwnCredential
Static service credentials; egress guard for imported backends yes mcp.WithHeader and mcp.WithEgressGuard on mcp.FromREST, the guard built with policy.NewDestinations; a header reaches the backend's own host only, and the guard judges every request and redirect hop before a byte is sent TestStaticHeadersStayOnTheBackendHost, TestWithEgressGuardJudgesEveryServedCall
Audit stream; metrics and tracing yes mcp.WithAuditSink, mcp.WithObserver TestWithAuditSinkDeniedCallStillAudits, TestWithObserverReceivesTheCallSample
Fail-closed configuration, and refusal of the engine's security-weakening MCPGODEBUG switches always on a nil or duplicated option, an option the served transport does not honour and a weakening switch in the environment are one collected startup report - mcp.Main exits 1, mcp.Run, mcp.Serve, mcp.NewHandler and mcp.NewSSEHandler return it, mcp.Handler and mcp.ServeSSE panic with it TestOptionListIsStrict, TestNewHandlerReturnsTheCollectedReport, TestWeakeningSwitchesAreRefusedThroughThePublicEntryPoints
Server-enforced approval of destructive operations yes mcp.WithApprover(approver) decides server-side (a client that can be asked is asked too; on stateless Streamable HTTP - without mcp.WithSessions - only a client on the multi-round-trip protocol revision, SEP-2322, or later can be, while a session asks an older client on its stream within the call's one deadline); mcp.WithClientApproval() requires the calling client's confirmation and denies a client that cannot be asked; without either, destructive operations are denied TestWithApproverDecidesDestructiveOperations, TestWithClientApprovalRequiresTheClientsConfirmation, TestWithClientApprovalOverStatelessHTTP
OAuth resource server: protected-resource metadata and JWKS-backed JWT validation yes oauth.NewJWKSValidator(rules, jwksURI, opts) under mcp.WithBearerAuth (RS/PS/ES only; issuer, audience, expiry and scopes checked; oauth.DiscoverJWKSURI finds the key set); mcp.WithProtectedResourceMetadata(m) publishes the RFC 9728 document, refused when the validator reports a different audience - see the OAuth resource-server recipe TestJWKSValidatorServesVerifiedCallers, TestJWKSValidatorRefusesEveryUnverifiableToken, TestProtectedResourceMetadataRules
API-key validators yes policy.NewAPIKeyValidator(keys) under mcp.WithBearerAuth: SHA-256 digests only, constant-time comparison TestAPIKeyValidatorServesThroughHandler
Tunable limits, origin allowlist and per-call deadlines yes mcp.WithLimits(l) replaces the default limits on every transport (stdio and the testing harness enforce its call deadline and arguments cap); mcp.WithAllowedOrigins(origins...) replaces the loopback-origin posture with an exact allowlist; every call carries a deadline - 30 s by default, stdio included - and mcp.Timeout(name, d) gives one operation its own TestWithLimitsOnStreamableHTTP, TestWithAllowedOrigins, TestStdioCallsRunUnderADeadline
Host allowlist (DNS rebinding) and health endpoint yes mcp.WithAllowedHosts(hosts...) admits loopback and listed Host names and refuses every other on every listener (without it, the protocol engine's check, which refuses a non-loopback Host on a connection that arrived over loopback); mcp.WithHealthPath(path) answers GET/HEAD with 200 on mcp.Main's -addr/-sse-addr listener, outside every other control TestAllowedHostsBehindALoopbackProxy, TestMainServesTheHealthPath
Explicit sessions and the session event stores yes mcp.WithSessions(events) switches Streamable HTTP from its stateless default to sessions whose GET stream resumes from Last-Event-ID (on protocol revisions before SEP-2575, which removes resumption), over mcp.NewMemoryEventStore(limits) or the store/redis and store/sql modules' event stores (redisstore.NewEventStore, sqlstore.NewEventStore, built over the server's limits; mcp.Main builds a memory one for nil). MaxSessions caps the live sessions (503 past it) and the store retains only each session's stream, never a call's result, each replay checked against the wire's numbering. With mcp.WithBearerAuth each request runs as its own verified token and a session answers only the tenant and subject that created it; without an identity source sessions are unpinned, and startup warns. Sessions live in the serving process: scaling out needs sticky routing on Mcp-Session-Id - see the row below TestWithSessionsServesExplicitSessions, TestSessionPinIsTenantAware, TestEventStoreResumesThroughWithSessions, TestEventStoreResumesThroughWithSessions
Trusted server instructions, announced identity and the server's own logging yes mcp.WithInstructions(text) is the only source of the instructions the handshake carries (up to 16 KiB) - never docs: tags, OpenAPI text or backend content; mcp.WithServerInfo(name, version) replaces the derived identity (the api: name, else the module path; the build's version, else (devel)); mcp.WithLogger(logger) takes the refusal causes (token redacted), the startup warnings and per-call lifecycle records, at its handler's level - a surface handed in from mcp.Curate wrote its expose-all warning to the default logger as it was curated - never a logger on stdout under stdio TestInstructionsNeverComeFromBackendContent, TestWithServerInfoReplacesTheDerivedIdentity, TestWithLoggerReceivesTheServersRecords
Bulkheads, breakers, retries, idempotency yes off until given, on every transport: mcp.WithBulkheads(cfg) bounds each backend's in-flight and waiting calls, refusing the rest as a retryable unavailable error; mcp.WithBreakers(cfg) stops calling a backend after consecutive failures until a cooldown's trial succeeds; mcp.WithBackendKey(fn) names each call's backend (one server-wide by default; its context never carries the credential); mcp.WithRetries(policy, operations...) retries only the named operations, only on a failure classified retryable, within the call's one deadline - a destructive one only under an idempotency key; mcp.WithIdempotency(cfg, keyArguments) replays a protected operation's keyed duplicate - the key a declared string argument the implementation receives - refuses a key reused with other arguments, per server and identity, never exactly-once - see the resilience recipe TestWithBulkheadsRefuseOverTheBound, TestWithBreakersOpenAndHalfOpen, TestWithRetriesRetriesOnlyNamedOperations, TestWithIdempotencyReplaysAndRefusesReusedKeys
Sampling, elicitation, roots, progress and client logging inside an implementation yes mcp.Sample, mcp.Elicit and mcp.ClientRoots ask the calling client, and only one that declares the capability - otherwise refused, not accepted, no roots; mcp.ReportProgress and mcp.ClientLogger notify it (a progress token, the level it set). Answers are untrusted client input, redacted over the call's credential and bounded at 1 MiB; an mcp.Elicit answer never approves a destructive operation. On the multi-round-trip protocol revision (SEP-2322) and later a question ends the pass and the call runs again from the start with the answer, so an implementation returns the accessor's error and asks before any side effect - see the negotiated-features recipe; deprecated upstream (SEP-2577) and working through its window TestNegotiatedFeaturesAskAnOldClientInline, TestNegotiatedFeaturesWithoutTheCapability, TestReportProgressAndClientLogger
Offline tests of the configured server yes mcptest.New(t, impl, mcptest.WithOptions(opts...)) applies the same options in process, refusing the transport-only ones; the harness client presents identities with Client.As, and mcptest.FakeValidator and mcptest.WithFakeClient stand in for a validator and a client TestHarnessWithOptionsAppliesPipelineOptions, TestHarnessWithOptionsRefusesTransportOptions
Raw access to the underlying protocol server no scoped out (decision 0048): the supported hatch is http.Handler composition around mcp.NewHandler - middleware runs before every control, sees unauthenticated requests and the raw Authorization header, and cannot plant a verified identity; anything it answers itself bypasses every control. A custom JSON-RPC method or a protocol feature this package does not expose is out of scope -
An api.Auth adapter no scoped out (decision 0048): implement policy.Validator over the authenticator's token logic and serve it with mcp.WithBearerAuth -
Identity from a proxy header, a client certificate, a session ID or tool arguments no the identity sources are mcp.WithBearerAuth's verified token, mcp.WithStdioIdentity and the harness's Client.As; a header a proxy injects would be a forgery path (decision 0048), and _meta or an argument named after an identity is never consulted -
Bearer authentication on the legacy SSE transport no refused at startup, and so is serving SSE beside an authenticated Streamable HTTP configuration: an SSE message POST runs under the stream opener's context, so no verified identity can be bound to each call (decision 0039) - serve Streamable HTTP -
Typed argument and result transform hooks no deferred, and recorded as unfinished in the implementation plan; the hooks with a public path are the rows above (decision 0048) -
Negotiated tasks and long-running work; existing-client, job and event adapters no blocked upstream: the pinned protocol engine (go-sdk v1.7.0) ships no tasks primitive, and the adapters are built on tasks - qualification record -
Routing extension for agent builders no blocked until the design defines a router contract - the open blocker -
Cross-replica or post-restart session resume; shared discovery cursors and dedup windows no sessions, discovery-cursor keys and idempotency windows live in the serving process, and the pinned protocol engine cannot take a session over from a store, so the store modules give no cross-replica or post-restart resume (decision 0041): more than one replica needs sticky routing - on Mcp-Session-Id with mcp.WithSessions, on a stable client key for the stateless default, which issues no session ID (the caller's identity, not its address, where mcp.WithIdempotency's window must hold: the window is keyed by identity and a retry may change address or session) - or one replica -
Per-call credentials on the gRPC and GraphQL bridge modules no a bridge client presents the one credential its Options carried when it was built, and never the caller's token (decision 0042); a per-caller credential mcp.Auth resolves (mcp.CredentialFromContext) reaches a bridge's wire only through a client built with it -

Privacy

iqmcp collects no telemetry. Neither the library nor the iqmcp command contacts any service of its own: there is no usage reporting, update check or analytics. The only outbound connections are the ones you configure - the backends you import or bridge, a JWKS or issuer URL you give the OAuth validator, the exporter you wire into the OpenTelemetry module, and a --url you pass to iqmcp inspect or iqmcp call.

Contributing

Contributions are welcome. Start with CONTRIBUTING.md for the development setup and checks, and follow the code of conduct. Questions go to SUPPORT.md; plans are in the roadmap; how decisions are made is in GOVERNANCE.md.

README.md is generated: edit docs/README.tmpl.md and run ./scripts/generate.

Licence

iqmcp is licensed under the Apache License 2.0.

iqmcp is an independent project by IQ Hive. It is not affiliated with or endorsed by the Model Context Protocol project or Anthropic.

Documentation

Overview

Package mcp exposes a runtime.link 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. 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
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. 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.

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); 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; trace end, audit and metrics. The backend key (WithBackendKey) sees 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.

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

Constants

This section is empty.

Variables

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

func ClientLogger(ctx context.Context) *slog.Logger

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

func Handler(impl any, opts ...Option) http.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

func IdentityFromContext(ctx context.Context) (policy.Identity, bool)

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

func Import[T any](client *Client) (T, error)

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

func Main(impl any, opts ...Option)

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

func NewHandler(impl any, opts ...Option) (http.Handler, error)

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

func NewSSEHandler(impl any, opts ...Option) (http.Handler, error)

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

func ReportProgress(ctx context.Context, progress, total float64, message string) bool

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

func Run(impl any, opts ...Option) error

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

func Serve(ctx context.Context, t Transport, impl any, opts ...Option) error

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

func ServeSSE(impl any, opts ...Option) http.Handler

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

func ToolSpecs(surface *Surface) []protocol.ToolSpec

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 Audio

type Audio struct {
	Data     []byte `json:"data"`
	MIMEType string `json:"mimeType"`
}

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

func (a Audio) MarshalJSON() ([]byte, error)

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 a runtime.link 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 runtime.link 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 runtime.link (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

func (b *Backend[API]) Err() error

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

func (b *Backend[API]) OpenAPISkipped() []openapi.Skipped

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.

func (*Client) Catalog

func (c *Client) Catalog(ctx context.Context) (catalog.Snapshot, error)

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

func (c *Client) Close() error

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 ClientOption

type ClientOption func(*clientOptions)

ClientOption adjusts one Connect call.

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

func Alias(source, alias string) Directive

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

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

func Budget(name string, maxBytes, maxItems, maxTokens int) Directive

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

func Describe(name, docs string) Directive

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

func Except(names ...string) Directive

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

func Fields(name string, paths ...string) Directive

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

func Fix(path string, value any) Directive

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

func Hide(name string) Directive

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

func Only(names ...string) Directive

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

func Paginate(name string, size int) Directive

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

func Production(names ...string) Directive

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

func Redact(name string, paths ...string) Directive

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

func Rename(from, to string) Directive

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

func Timeout(name string, d time.Duration) Directive

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

func (e *Error) Error() string

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

func (e *Error) Unwrap() []error

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 runtime.link 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 Image

type Image struct {
	Data     []byte `json:"data"`
	MIMEType string `json:"mimeType"`
}

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

func (img Image) MarshalJSON() ([]byte, error)

MarshalJSON writes the wire shape the protocol carries for an Image block.

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

func ForHTTP(opts ...Option) Option

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

func ForSSE(opts ...Option) Option

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

func ForStdio(opts ...Option) Option

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

func WithAllowedHosts(hosts ...string) Option

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

func WithAllowedOrigins(origins ...string) Option

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

func WithApprover(a policy.Approver) Option

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

func WithAuditSink(sink AuditSink) Option

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

func WithAuthorization(e policy.Engine) Option

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

func WithBackendKey(key func(ctx context.Context, operation string) string) Option

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

func WithBearerAuth(v policy.Validator, scopes ...string) Option

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

func WithHealthPath(path string) Option

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

func WithInstructions(text string) Option

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

func WithLimits(l policy.Limits) Option

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

func WithLogger(logger *slog.Logger) Option

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

func WithObserver(observer *Observer) Option

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

func WithServerInfo(name, version string) Option

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

func WithStdioIdentity(id policy.Identity) Option

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.

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.

func (Problem) String

func (p Problem) String() string

String renders the problem as "Where Message", or just Message when no Where is set.

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

type Renderer = protocol.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 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

func Curate(target any, ds ...Directive) *Surface

Curate reflects over one runtime.link 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 runtime.link 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

func Recurate(s *Surface, ds ...Directive) *Surface

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

func (s *Surface) Err() error

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

func (s *Surface) Lookup(name string) (Operation, bool)

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

func (s *Surface) Operations() []Operation

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

func (s *Surface) Shaped() bool

Shaped reports whether the surface carries a compiled shaping selection.

func (*Surface) Snapshot

func (s *Surface) Snapshot() (catalog.Snapshot, error)

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.

func (*Surface) Warning

func (s *Surface) Warning() string

Warning returns the loud expose-all warning, or "" when production was selected or an Only directive names the operations to serve. Curate already logs the warning once; the accessor lets a caller surface it again, for example in its own startup output.

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

func (t Text) MarshalJSON() ([]byte, error)

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

func (e *ToolError) Error() string

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

func (e *ToolError) ToolFailure() (code, message string, retryable bool, retryAfter time.Duration)

ToolFailure reports the failure as the server reads it: the class, the model-visible message, the retryability and the retry-after.

func (*ToolError) Unwrap

func (e *ToolError) Unwrap() error

Unwrap returns the cause, so errors.Is and errors.As reach it.

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

type TraceStart func(ctx context.Context, operation string) (context.Context, TraceEnd)

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

type Transport = protocol.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.

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 runtime.link 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 runtime.link 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).
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 runtime.link API structures.
Package contract builds the normalized MCP view of one or more runtime.link 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 runtime.link cannot recover Go parameter names for it.
Package nosource deliberately does not embed its source, so runtime.link 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.
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.

Jump to

Keyboard shortcuts

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