MCP auth facade SPI — provider and store
The MCP auth facade lets an application front an upstream auth provider (Autheory is the first adapter) on one domain while the upstream stays the sole authorization server and token authority. This page documents the two service-provider interfaces the facade is built on and what ships today.
Status: the SPI layer exists and is consumed by the framework-owned front channel. The provider SPI, the five
store SPIs, the conformance suites, and the fake provider are implemented in Go, TypeScript, and Python. When the
front-channel field set below is declared, the three registrars (RegisterMCPFacade / registerMcpFacade /
register_mcp_facade) mount the client-facing front channel and drive the provider and the stores from a request:
the per-endpoint-kind GET …/authorize terminator, the one stage-global GET /_oauth/mcp/callback, and the
per-endpoint-kind POST …/token authorization_code grant. Nothing outside that field set becomes reachable, and with
Provider absent the facade owns no OAuth surface — the application either supplies its own handler factories or
registers none, exactly as before.
Mounted: the per-endpoint-kind POST …/register RFC 7591 dynamic-client-registration route, and the
refresh_token grant at /token — the brokered refresh (single-flight, rotating, with a configurable grace replay)
answers a handle the code exchange minted. The CDK facade attachment is presence-only by design:
its presence selects the runtime-bearer posture and enables the route derivation and the defense-in-depth floor
checks, while the provider and the five store SPIs are runtime FacadeConfig wiring, not a CDK item
(FRAMEWORK_VS_POLICY.md). See “What the front channel does” below.
What the framework owns, and what the application owns
The framework owns composition and mechanics; the application owns policy. The full per-mechanic verdict is
in docs/development/planning/apptheory/mcp-auth-facade/FRAMEWORK_VS_POLICY.md. In short:
| Concern | Owner |
|---|---|
| Provider SPI shape, Autheory adapter, hardened upstream HTTP (deadline, size cap, SSRF guard) | Framework |
| Store SPI shape, atomic consume/CAS/lock/revoke semantics, in-memory reference stores | Framework |
| Conformance suites (provider + store) and the fake upstream provider | Framework |
Scope vocabulary, offline_access lifecycle scope, account_id hint semantics |
Application |
| Durable store backend (e.g. TableTheory/DynamoDB), encryption key/ARN, table shapes | Application |
| DCR mechanics (RFC 7591 validation, https-or-loopback redirect enforcement, server-assigned ≥128-bit client ids, per-route rate limit, bound-route binding, hash-stored record) | Framework |
| DCR redirect allow-list policy beyond the framework’s https-or-loopback floor, legacy-client adoption | Application |
Provider SPI
One interface per runtime, implemented once per provider. It is deliberately the minimum needed to derive the facade from the requirements; Autheory is the first and only adapter in this program.
| Operation | Purpose | Fails closed on |
|---|---|---|
Discovery |
RFC 8414/OIDC discovery bootstrap; verifies the document issuer equals the configured issuer before any endpoint is trusted |
non-HTTPS, issuer mismatch, cross-origin redirect, missing required fields |
AuthorizationURL |
Builds the upstream authorize URL the browser is redirected to | missing upstream client, callback, PKCE challenge, state, resource, or a non-S256 method |
ExchangeCode |
Server-side upstream code exchange with the facade’s own client and PKCE verifier | non-2xx, missing access_token; the upstream error body is never forwarded |
Refresh |
Upstream refresh presenting the OAuth client that owns the recorded material | non-2xx, secret-bearing error body never forwarded |
ValidateAccessToken |
Reuses the RFC 9728 JWKS/RS256 validator; never mutates the token | issuer/audience/azp/signature/expiry/scope failure |
Every upstream call goes through the same hardened HTTP stack the OIDC discovery and JWKS bootstraps use: a bounded deadline (10 s default), a 1 MiB response cap, a connect-time SSRF guard that refuses non-public addresses, and a redirect refusal. There is no separate, unbounded fetch path.
The JWKS key-set fetch is coalesced in Go and TypeScript, but not in Python. The Go and TypeScript validators
single-flight concurrent key-set fetches for one validator, so validations that miss the key cache at the same moment
share a single upstream fetch. The Python validator does not coalesce: every concurrent unknown-kid validation
performs its own key-set fetch. Each of those fetches is still independently bounded by the same 10-second deadline and
still charges the same global unknown-kid fetch budget, so the difference is upstream request volume, not the bound
and not the accept/reject decision.
Refresh must honor the deadline. The framework’s own adapter calls Refresh through that hardened stack, so
the 10-second deadline bounds the upstream call it makes. An implementer’s Refresh (or a durable store that backs
the lock) must not ignore it: the broker refresh lock’s TTL is 15 seconds — the 10-second deadline plus a 5-second
margin, a relationship a pin test enforces — so an upstream call that runs past the deadline lets the lock expire and
a second caller acquire it, admitting a second concurrent upstream refresh. The rotation stays safe even then: it
completes with a versioned compare-and-swap on the broker record, so exactly one winner lands and the loser discards
the successor it minted (or answers 503), and no success is ever returned for state that was not persisted. The
obligation is nonetheless real — honor the deadline so the single-flight guarantee holds at the store and not only at
the compare-and-swap.
Typed errors map to a closed client-facing vocabulary, so a caller never has to string-match an upstream body:
ProviderError class |
Facade HTTP class |
|---|---|
upstream_error |
502 |
temporarily_unavailable |
503 (retryable; Retry-After) |
invalid_grant |
400 (terminal) |
invalid_request |
400 (adapter-side; never reaches the upstream) |
reauth_required |
503 (recovery-available; retryable) |
Only invalid_grant is a contract-terminal verdict. The token-endpoint error codes are enumerated per code
under the refresh-rotation-recovery contract (theorycloud_refresh_rotation_recovery.v0.1 R6/R7): invalid_grant
is the one code that may carry a family-terminal authority verdict, and every per-request client code —
invalid_scope, invalid_request, access_denied, expired_token, invalid_token, invalid_client,
unauthorized_client — is a request-level refusal that is transient to the family. The adapters report a
per-request code, and any unrecognized code, as an upstream_error; none of them can revoke a family. The
classification is exported for consumers as IsTerminalTokenVerdict / TerminalTokenVerdictCodes /
IsPerRequestTokenVerdict in Go, isTerminalTokenVerdict / terminalTokenVerdictCodes /
isPerRequestTokenVerdict in TypeScript, and is_terminal_token_verdict / terminal_token_verdict_codes /
is_per_request_token_verdict in Python, and it is pinned in both directions by the shared provider conformance
table and by the vendored contract corpus.
The reauth_required class is a defensive mapping, carried identically by all three runtimes (Go
ProviderReauthRequired, TypeScript the reauth_required member of the ProviderErrorClass union, Python
ERROR_REAUTH_REQUIRED). It means “the recorded material is stale or replaced”, which the rotation-recovery
contract classifies as recovery-available: the replaced material is walked to its successor inside the serve
window, so the class is retryable (503 + Retry-After) and never family-terminal. The Autheory adapter reports a
reauth_required upstream answer as temporarily_unavailable for the same reason.
A terminal verdict is revocable only on corroborated evidence. A facade that receives an invalid_grant for a
refresh release-releases the lock and answers transiently unless the verdict is about the family’s current live head
and no rotation attempt of that record is unconfirmed inside the facade’s ambiguity horizon (its configured grace
window). An unconfirmed attempt is a timeout, a lost response, or a process failure after the upstream material was
presented — the 2026-11-11 16:00Z class — and its verdict stays transient. A verdict about superseded material is
also transient. Only the head’s own material being rejected revokes the family, and the revocation is attributed as
upstream_reauth_required, never as client theft.
At the callback the class table above collapses to one outcome. When the framework-owned front channel’s
callback calls the provider, any failure — the server-side ExchangeCode, and the ValidateAccessToken that
follows it — is mapped to the gateway-class 502 upstream_error, over the ProviderError class’s own HTTP
status: an ExchangeCode failure is 502 even when its class table row would say 400. The class table describes
the typed errors the SPI produces; the callback deliberately does not translate an upstream failure into the
facade’s own 400 request-class vocabulary (DESIGN §8.2). This is what keeps the callback’s RFC 9207 iss and
upstream state pins non-vacuous: an implementation that skipped either pin would reach the provider call and
change the pinned result instead of coincidentally reproducing a 400, and the two classes stay distinguishable to
a client.
Autheory adapter (first adapter)
The adapter is discovery-driven: it takes authorization_endpoint, token_endpoint and jwks_uri from the
verified RFC 8414 document rather than hard-coding them. Two Autheory facts are load-bearing:
resourceis required upstream. Autheory’s authorize endpoint refuses a request without it, so the adapter always sends the route’sresource.- Refresh material is bound to the issuing client. The refresh leg presents the client that owns the recorded upstream material (the facade’s own client for facade-opened records; the store is the discriminator).
The adapter does not relax Autheory’s own policy. In particular token_endpoint_auth_method=none public clients
only, and Autheory’s application-type-specific DCR redirect policy is stricter than the framework’s https-or-loopback
floor — the framework keeps the stricter upstream behavior.
UNVERIFIED (carried to the lab milestone)
- Whether discovery-driven clients’ authorize requests reach Autheory’s enforcing Go path (
/auth/authorize) or only the published, render-only/oauth/authorizeused as the discoveryauthorization_endpoint. - The exact deployed
AUTHEORY_OAUTH_ISSUER/AUTHEORY_JWT_ISSUERvalues per stage.
Store SPI
Five stores, each with an in-memory reference implementation. Consume-once and compare-and-swap are required atomic operations, not conventions: replay handling and single-flight refresh depend on them. Production needs a durable store; the framework does not ship one — durable implementations are application-owned.
| Store | Key | Atomic operations | TTL |
|---|---|---|---|
TransactionStore |
hash(upstream state) | Put, Consume (single-use) |
≤ 10 min |
AuthorizationCodeStore |
hash(facade code) | Put, Consume (single-use, retained after consume so a replay is distinguishable from an unknown code) |
≤ 600 s (60 s recommended) |
ClientStore |
hash(client id) | Put, Get, Update (compare-and-swap on version) |
none (age-out policy) |
RouteRefreshBrokerStore |
hash(route handle) | Get, AcquireLock (exclusive, expiring), CompareAndSwap (versioned), Revoke (idempotent, terminal); required transactional family capability (CreateFamily, RotateFamily, ListFamily, RevokeFamily); optional handle-lifetime reporter |
RouteRefreshPolicy.HandleTTL (≤ min(upstream refresh lifetime, session lifetime, local policy)) |
RateLimitStore |
(identifier, resource, operation) | CheckAndIncrement (atomic) |
window |
Every store takes an injected clock, so TTL expiry and lock expiry are deterministic in tests. The in-memory reference stores are non-durable and do not encrypt: they are for tests and local development only.
Encryption is a store obligation. The facade performs no sealing and the framework adds no encryption surface
or key management: it hands the store the upstream material exactly as the provider returned it, which is why one
durable upstream refresh token lives in the broker record and one upstream token response lives in the code record.
A durable store implementation must encrypt every Encrypted* field at rest (for example with
persistence-layer theorydb:"encrypted" tags on a TableTheory-backed store), so nothing upstream is persisted in
the clear. The code record keeping the (encrypted) upstream token response is deliberate: it is what lets the code
exchange return the upstream access token byte-for-byte unmodified. The in-memory reference stores above neither
persist nor encrypt and must not be used as a durable store.
The grace body is retained for the record’s lifetime, not for the grace window. The broker record’s
EncryptedGraceRefreshResponse field holds the successor token response a rotation produced — the successor
handle plus the upstream access token that was already returned to that client — and it is the only carrier of the
successor handle, because the record has no separate successor-handle field. It serves the grace replay and
incident-visible lineage. A store must not clear the field when the grace window closes: the field expires with
the record, under the record’s own TTL (the broker handle lifetime in the policy), never at the grace deadline. The field expires with the record, under the record’s own TTL (the broker handle lifetime in the
policy), never at the grace deadline, and a durable store must encrypt it at rest for that whole lifetime like
every other Encrypted* field. Nothing extra is exposed by keeping it: it adds no material that is not already
covered by the encryption obligation (the successor handle and an access token the client already received).
Route refresh policy, family, and telemetry
The brokered refresh handle has four encoded policy values (see FacadeConfig.RouteRefreshPolicy):
HandleTTL— the local lifetime of a route refresh handle, required and bounded to[60 s, 30 d]. It is the store’s lifetime policy; a broker store that reports its own lifetime through the optionalRouteRefreshBrokerHandleTTLReportermust agree with it, so a deployment cannot declare a long ceiling while its store silently keeps a short one. A missing or zero value is a registration error, never a fallback.GraceWindow— the lost-response replay window measured from the winning rotation. Absent or zero selects 120 s; the maximum is 120 s. Inside the window the rotated (previous) handle replays the stored successor body, including handle material, because that is the lost-response recovery path. Onlyexpires_inis recomputed, to the lifetime the access token actually has left; a stored body below the five-second credential floor is not replayed at all and the head is rotated instead, so a replayed credential is always accepted for the lifetime the response states. The boundary is exclusive: a presentation at exactly the deadline is a stale predecessor.ReuseRateCeiling— retained for configuration compatibility, required and bounded to[9, 120]. It previously budgeted the removed beyond-grace access-token-only serve; no refresh path uses it now.-
RefreshBudget(refreshBudgetSeconds/refresh_budget_secondsin TypeScript and Python) — the encoded time budget of one upstream refresh call, absent or zero selecting 10 s and bounded to[1 s, 12 s]. The facade applies it as the deadline of the call (a context deadline in Go, a bounded race in TypeScript) so an adapter that ignores its own transport default still cannot outlive the budget the deployment chose; Python’s synchronous provider SPI cannot be interrupted, so its facade refuses to act on an answer that outlived the budget and treats that answer as unconfirmed, exactly like a timeout. The 12 s ceiling is the reference 15 s broker lock TTL less a 3 s commit margin: a budget above it could let the lock expire mid-rotation and admit a second concurrent upstream refresh. It is a configuration field, never an environment variable.The budget is the deadline of the call only if the transport lets it be one. An adapter that bounds its own HTTP client reports that bound through the optional companion of the provider SPI —
oauth.UpstreamFetchTimeoutReporter(UpstreamFetchTimeout() time.Duration),upstreamFetchTimeoutSeconds(): number, andupstream_fetch_timeout_seconds() -> float | None— and registration refuses a policy whose budget exceeds it:… route refresh policy refresh budget 12s exceeds the provider's upstream fetch timeout 10s, which would end the refresh call first: raise the provider's fetch timeout to at least 12s or lower the refresh budget to at most 10s. This is the honesty rule of the encoded policy: the facade will not reach into a provider’s transport (that bound is the provider’s own wiring and governs every call the adapter makes), so a budget it cannot honor is refused with both values named rather than silently cut to the stricter one. A budget at or below the reported bound is accepted and stays the binding deadline; a provider that reports no bound states nothing to check. The Autheory adapter’s bound isAutheoryProviderOptions.FetchTimeout(fetchTimeoutSeconds/http_timeout_seconds), 10 s by default, so an encoded 12 s budget requires a 12 s fetch timeout.An adapter reports only a bound it actually enforces. Two runtime facts make that a per-runtime answer rather than one number copied three ways, and both keep the same rule:
- Go and TypeScript re-time an injected transport. Go clones the supplied
HTTPClientand sets itsTimeout; TypeScript races every call againsttimeoutMsin its bounded request. So a caller-injected client orfetchis still held to the reported bound, and the report stays true — a 12 s budget over an injected 10 s transport is still refused, correctly. - Python does not. An injected
http_getis caller-owned and is not re-timed or re-plumbed with the guard, so the adapter states the bound as unknown (None) instead of naming the default transport’s 10 s, and registration skips the check exactly as for a provider that does not report at all: the caller owns the bound. The one knowable injected bound is the framework’s own bounded transport — passed directly or through afunctools.partialof it, whosetimeoutkeyword is the bound it applies — which is reported as that value.
- Go and TypeScript re-time an injected transport. Go clones the supplied
Rotation intent, post-timeout lineage verify, and the ambiguity horizon
Before it presents a record’s upstream material, the facade writes a durable rotation-intent marker
(RotationUnconfirmedAt on the broker record) under the held lock. It is the read-side twin of persist-before-ack:
the facade never presents material it has not recorded an attempt for, so a process that loses the answer leaves
evidence behind. RotateFamily clears the marker in the same transaction that resolves the attempt, and the earliest
unconfirmed instant is never moved forward, so retries cannot extend the horizon.
On the next presentation of a marked record, the facade verifies lineage before presenting anything: if the
family’s live head has already moved on, the successor exists and the stale material is never presented again — the
head is rotated for the client and the event carries the additive lineage_verified reason. If the head has not
moved, the attempt is presented through the recovery path, and an upstream invalid_grant remains transient
(temporarily_unavailable with Retry-After, recovery_pending reason) until the marker is older than the
configured grace window. Inside that ambiguity horizon a verdict cannot be told apart from a lost response, a
timeout, or the contract’s informed serve-off state (with artifact writes on but walk serve off, an in-window
rescue-marked presenter receives invalid_grant while the family survives), so it is never treated as
family-terminal evidence. Outside it, with the verdict about the live head and no unconfirmed attempt, the family is
revoked with the upstream_reauth_required attribution — the one genuinely terminal shape.
Reuse is served, never punished
A rotated-away handle presented at or after its grace deadline is a stale predecessor, and the evidence from every real client that broke is exactly that presentation: the predecessor of the live head, presented minutes to hours after a successful rotation, with the live head never presented, often at the same second on several routes of one login. Nothing distinguishes it from a stolen handle, so the facade does not treat it as theft. It rotates the family’s live head — never the predecessor, whose upstream material has already been rotated and which an upstream that detects refresh-token reuse would revoke the grant over — and hands the client fresh credentials. The presented record is re-armed with the new body and a fresh grace window, so a retry storm inside one window costs one upstream call rather than one per attempt. Every member of the family stays live.
A reuse telemetry event fires with the additive rotated_from_head outcome and the stale_predecessor reason; no
family is revoked by reuse. The family is revoked only when the upstream terminally rejects the grant
(invalid_grant on the live head, with no unconfirmed rotation attempt inside the ambiguity horizon), when an
operator revokes it through the incident surface, or when the authorization code that minted it is replayed. Each of those answers the uniform non-oracle invalid_grant an
unknown handle gets, which is the token endpoint’s re-authorize signal.
Citations: RFC 9700 (OAuth 2.0 Security Best Current Practice) on refresh-token rotation and reuse detection; OAuth 2.1 draft §4.3.1 on public-client refresh tokens; MCP authorization; and comparable providers’ reuse intervals (Auth0, Okta). RFC 9700 permits reuse detection; it does not require it, and it requires a public client to be able to recover from a lost rotation response, which is what the served path provides.
Residual risk. A stolen route handle stays exchangeable for fresh credentials for as long as the thief keeps presenting the current handle and the upstream grant remains valid. Each rotation mints a successor and stores it with a fresh full handle-TTL window, and the family state carries no absolute deadline, so a thief who presents the newest handle at least once per window keeps the chain alive until the upstream grant ends. The 30-day handle TTL therefore bounds only a handle that is never presented again. The mitigations are short access-token lifetimes; the binding checks a real client satisfies (client registration, route resource, scope, subject); revocation when the upstream terminally rejects the grant, when an operator revokes the family on the incident surface, or when the authorization code that minted it is replayed; and, for a handle that is never presented, the handle TTL itself. Detection is not attempted: the facade cannot distinguish a thief’s presentation of a stolen handle from a restart holding a stale copy, and treating the latter as theft is what broke every real client. The general treatment of refresh-token replay is in RFC 6749 §10.4 and RFC 9700’s refresh-token guidance.
What real clients actually do. The local real-client target (make local-clients) drives Codex 0.166,
Claude Code 2.1.319, Kimi Code 2.4.0 and Vibe 3.0.4 against the example app with an isolated home per
client. With a 30-second access-token lifetime, Codex issued 34 route refreshes across two separate
processes (a run and a restart), Claude Code 6 in one run, Kimi Code 1 across a restart and Vibe 1 across
a TUI login and a restarted vibe -p process: every refresh was served, no refusal was emitted, no family
was revoked, and the upstream never observed refresh-token reuse. Codex and Kimi Code kept the rotated
handle across a process restart, Claude Code persisted it within one run and Vibe persisted it across its
restart; none needed a re-login.
With the upstream grant revoked, each client made exactly one refresh, received the terminal
invalid_grant, stopped, and called no tool. Kimi Code then waited for a new login instead of looping;
Vibe stopped its turn with mcp_authorization_required and told the user the server needs
re-authorization, without starting a login on its own. A control endpoint tombstoned the family while an
access token minted with a long lifetime was still valid, and Codex presented it: the resource server
accepted it, because it accepts every credential the facade issued for the lifetime the token response
stated. No client in this suite ever presents a refusable live access token, so the MCP-401 comparison
does not arise; the refusal every client meets is the token endpoint’s 400 invalid_grant, and Vibe’s
terminal row records exactly that status (MCP [400]), not a 401.
Vibe is the one client whose login writes the operator’s real Keychain. On macOS Vibe 3.0.4’s
vibe/utils/keyring.py sends every MCP OAuth write to /usr/bin/security add-generic-password -s
ai.mistral.vibe, bypassing the Python keyring library and any PYTHON_KEYRING_BACKEND. The suite
therefore logs in under a dedicated server alias, apptheory-local-clients, whose three accounts
(mcp-oauth:apptheory-local-clients:{tokens,client_info,fingerprint}, exactly the <kind> values
vibe/core/auth/mcp_oauth.py::_kr_username writes) are the only items it may create. The suite checks
that prefix before the run, deletes every prefixed item in a finally path that also runs on failure,
timeout and Ctrl-C, and proves none remains; it never reads, modifies or deletes another keychain item,
and never reads a secret value. The login is the TUI’s /mcp login apptheory-local-clients, the only
surface that starts one; the suite drives it in a PTY, has the Rust TUI record the browser open in
VIBE_E2E_ACTION_LOG instead of launching a browser, and plays the browser against the local server until
Vibe’s own loopback callback reports success. Each prompt is then a separate vibe -p process.
One client-side limit is real and is adapted to, not worked around: MCP SDK 2.3.0 refreshes at
<origin>/token whenever the process did not cache authorization-server metadata first — which every
restart with stored tokens does — while route-issuer mode serves the token endpoint under the route. The
example therefore mounts one small compatibility route, POST /token, in its own handler: it resolves the
presented handle’s broker record, rebuilds the route’s token path, and re-dispatches through the app, so
every binding check, rotation, refusal and telemetry event remains the facade’s. Without it Vibe reports
mcp_invalid_result and calls no tool. The authoritative Autheory-path proof still runs in TMS; the
example’s own rows (examples/cdk/local-mcp-auth-facade) replay the same sequences over real HTTP in CI.
Exported refresh sweep entrypoint
A scheduled trigger keeps credentials fresh through the exported sweep entrypoint: mcpfacade.RefreshSweeper
(NewRefreshSweeper + SweepFamily) in Go, the RefreshSweeper class with sweepFamily in TypeScript,
RefreshSweeper with sweep_family in Python. It takes the same five stores, the same provider, and the same
encoded RouteRefreshPolicy the facade was registered with, and it rotates one family’s live head through the same
lock and the same RotateFamily transaction. The caller decides which families are due; the sweeper does not guess,
because the scheduler that owns the access-token expiry knows it better than the broker record.
Its concurrency contract is part of the SPI:
- Exclusive lock. A held lock, an unavailable lock, or a version that moved since the head was read resolves to
the
deferredoutcome: no upstream call, no state change, no family effect. The caller retries on its next tick. - Exactly one winner. A loser of the commit race (the request path rotated first, the lock expired, the family was revoked) gets a typed transient result and never mints a successor.
- The loser keeps working. A request-path presentation racing a committed sweep rotation is served from the stored successor body, or has the new live head rotated for it; a sweep racing a committed request-path rotation defers and reads the new head. Neither order is family-affecting.
- The sweep never revokes. Continuity maintenance is not a revocation trigger. A contract-terminal upstream
verdict observed by the sweep releases the lock and returns
terminal_verdict, leaving the family intact: revocation and its receipt stay on the request path, where the client-facing verdict is rendered and lineage is verified. - It is bounded. The upstream call carries the same encoded refresh budget, which stays below the broker lock
TTL, so a sweep can never outlive the lock it holds, and registration refuses a budget the provider’s transport
cannot honor (see
RefreshBudgetabove). - Every deferral is reported. A deferred tick emits exactly one
state_failureevent carrying theDeferredReasonthe result reports — lock contention, an unavailable family (family_state_unavailable), a rewrite failure, or an upstream rejection — including a family the sweeper could not read. A silent deferral is indistinguishable from a sweep that never ran, so an alarm or soak that counts route refresh events alone would seedeferred=1and nothing else. The event carries no handle or family hash when the tick resolved no record: the sweep does not invent identity for an answer it never had.
Family identity, tombstone, and migration
Every record carries a chain-root/family hash and a chain-generation counter, and a RotationUnconfirmedAt
(rotationUnconfirmedAt / rotation_unconfirmed_at) durable rotation-intent marker that a store must round-trip;
RotateFamily clears it as part of the rotation transaction. The shared store conformance table pins both
directions (family_rotation_intent), so a durable store that drops the marker fails its own conformance run. A handle the facade mints is the root
of its own family (generation 1, family hash = hash of its own handle); every successor records the presented
generation plus one and inherits the family hash.
The front channel requires RouteRefreshBrokerTransactionalFamilyStore: CreateFamily atomically creates an
active family-state record and its generation-1 root; RotateFamily checks the lock owner, expected version, active
family, family/generation/identity bindings, and successor uniqueness in one serialized transaction before creating
the successor and updating the predecessor; RevokeFamily writes a terminal family tombstone and revokes every
live member it handles; ListFamily remains the incident enumeration surface. Every Get, AcquireLock, and
RotateFamily of a family-marked handle honors the tombstone, so revocation covers every member, including
successors minted before the tombstone, and no root creation or rotation can undo it. Revocation is idempotent; a
family whose members have all aged out keeps its tombstone, so it cannot be recreated. Registration refuses a
base-store-only, legacy-family-only, or partially duck-typed broker before routes, roots, or successors.
Pre-policy and partially backfilled records. A family-less record (generation 0, empty family hash) predates the
family policy, including a v6.4.0-era lineage. It is migrated in code, with no manual data operation: the facade
follows the stored successor links to the lineage’s live head — the only record whose upstream material is current,
because every earlier link’s material was rotated away when its successor was minted — bounds the walk at 64 links as
a corruption guard, and mints a fresh generation-1 family root from that head’s material. The legacy head is re-armed
with the new body and a grace window, so a sibling migration lands on the family instead of minting a second one. A
missing link, a cycle, a revoked member, or the walk limit fails the migration rather than guessing; the caller then
gets the uniform invalid_grant. A family-marked record whose required family state is missing/corrupt is refused by
ListFamily and ordinary rotation fails closed, exactly as before.
Telemetry and the expiry signal
The exported sweeper reports through the same hook: lock_acquired and refreshed on a rotation, and one
state_failure per deferred tick (see the sweep contract above).
RouteRefreshEvents is an optional synchronous hook with the SPEC.md:346-352 taxonomy: issued,
validation_rejected, lock_acquired, grace_served, refreshed, reuse (the live outcome is revoked_family; access_token_only, revoked_walk,
rate_limited, and binding_rejected are retained only for telemetry compatibility), upstream_reauth_required,
and state_failure. Events carry route identifiers, status transitions, and hashes
only — never an authorization code, access token, upstream refresh token, route refresh handle, ID token, cookie, or
provider session id. The hook runs synchronously and its panic/exception is contained.
The broker store reports expiry distinctly from absence (ErrBrokerExpired / BrokerExpiredError versus
not-found). The client-facing body stays the uniform invalid_grant; the distinction exists only for telemetry
attribution.
Front-channel configuration
The framework-owned front channel — the /authorize terminator, the stage-global upstream callback, the
/token authorization-code grant, and the /register dynamic-client-registration route of DESIGN §8 — is declared by
one FacadeConfig field set. Declaring the set is what mounts the front channel: with Provider set,
registration validates the rest of the set, fails closed on an incomplete or contradictory set (including a broker
store that lacks any transactional family method), and mounts the four route shapes driven by the provider and the
five stores; with Provider absent the front channel stays unowned and no
front-channel field may be set (the /register and callback routes then mount only through the application-owned
RegisterHandler / CallbackHandler).
| Field (Go / TS / Python) | Purpose | Default | Validation | Fail-closed rule | Demanded by |
|---|---|---|---|---|---|
Provider / provider / provider |
Anchors the framework-owned front channel: with it set AppTheory owns /authorize, the stage-global callback, and the /token authorization-code grant |
absent — the front channel stays unowned, and the app either supplies its own handler factories or registers no OAuth surface | none (an interface value) | All-or-none set: setting any other front-channel field while Provider is absent is a registration error naming that field |
DESIGN §8; DESIGN §8.1 |
Stores / stores / stores |
The five store SPIs the front channel persists through: transaction, authorization code, client, route-refresh broker, rate limit | absent | all five must be non-nil; a missing store fails closed rather than degrading | Registration error naming every missing store (… requires all five stores; missing Transaction, RateLimit) |
DESIGN §7 |
UpstreamClientID / upstreamClientID / upstream_client_id |
The facade’s own upstream client registration: sent on the upstream authorize request and presented on the server-side code exchange, and the expected azp/client_id of a validated upstream access token |
empty | non-blank, well-formed Unicode, no NUL | Registration error (… upstream client id is required and must be well-formed) |
DESIGN §8.1; DESIGN §5.2, §6 |
UpstreamIssuer / upstreamIssuer / upstream_issuer |
The expected upstream issuer: the RFC 9207 iss the callback pins before consuming the transaction or exchanging the code, and the issuer Discovery must verify before any published endpoint is trusted |
empty | absolute HTTPS URL, no query, no fragment, normalized like IssuerURL |
Registration error (… upstream issuer must be an absolute HTTPS URL without query or fragment) |
DESIGN §8.2; DESIGN §5.2, §6 |
LifecycleScopes / lifecycleScopes / lifecycle_scopes |
Scope values added to every upstream authorize request but never required from the MCP client (for example offline_access) |
absent — adds none | each value trimmed, non-empty, and well-formed Unicode; duplicates collapse | Registration error (lifecycle scope values cannot be empty / … must be well-formed Unicode) |
FRAMEWORK_VS_POLICY row 7 |
ProviderHints / providerHints / provider_hints |
The opaque per-request hint seam for one authorize request (for example account_id); a hint carries no authority |
absent — contributes no hints | none at registration (the function is opaque); a hint whose trimmed, lower-cased name collides with a required or reserved authorize parameter (response_type, client_id, redirect_uri, code_challenge, code_challenge_method, state, resource, scope) is refused by the adapter as invalid_request before the upstream is contacted, and a hint whose name carries leading or trailing whitespace is refused the same way rather than forwarded under its untrimmed or trimmed spelling, so a returned error is a provider-call failure in the gateway class (502 upstream_error), never a redirect |
Registration error when set without Provider |
DESIGN §6 |
RouteRefreshPolicy / routeRefreshPolicy / route_refresh_policy |
The static policy of the brokered route refresh handle: HandleTTL (required), GraceWindow (optional, default 120 s), ReuseRateCeiling (required), and RefreshBudget / refreshBudgetSeconds / refresh_budget_seconds (optional, default 10 s) — the encoded upstream refresh-call budget |
none | required whenever Provider is set. HandleTTL ∈ [60 s, 30 d]; GraceWindow ∈ (0, 120 s]; ReuseRateCeiling ∈ [9, 120] per family per hour; RefreshBudget ∈ [1 s, 12 s], the ceiling being the reference 15 s broker lock TTL less a 3 s commit margin, and no budget above the provider’s reported transport bound (UpstreamFetchTimeoutReporter). A broker store that reports its own lifetime through the optional reporter must equal HandleTTL |
Registration error on absent/zero/invalid values (… route refresh policy handle TTL is required and must be positive, … must be within [1m0s, 720h0m0s], … refresh budget must be within [1s, 12s], … refresh budget 12s exceeds the provider's upstream fetch timeout 10s …); registration error when set without Provider |
DESIGN §7 TTL min-of; docs/115; refresh-rotation-recovery R7 |
RouteRefreshEvents / routeRefreshEvents / route_refresh_events |
Optional schema-redacted route refresh broker telemetry hook | absent — emits nothing | hook is opaque; called synchronously and its panic/exception is contained | Registration error when set without Provider |
SPEC.md:346-352 |
Every rejection uses the runtime’s existing configuration-error prefix and the same message body (mcpfacade: …
in Go, AppTheoryMcpFacade: … in TypeScript and Python).
The reasoning behind the shape, because each of these was a reviewer question:
Provideris the anchor. The front-channel field set is all-or-none: aProviderwithout the rest is incomplete (fail closed), and the rest without aProvideris dead configuration (fail closed). There is no “partially owned” front channel that half-registers.- The stores carry no TTL here except the broker handle lifetime. Each store owns its own TTL — ≤10 min for a transaction, ≤600 s for an authorization code, age-out (not TTL) for a client, and a window for the rate limiter — so the facade configures none of those (DESIGN §7 TTL column). The broker handle lifetime is the exception: the route refresh policy declares it and the broker store applies it, because the value is the min-of policy the facade must validate at startup rather than leave to a store default. The injected clock that makes every TTL deterministic is the store’s own concern.
UpstreamClientIDis both identities on purpose. It is the client the facade presents upstream and the expectedazp/client_idof an upstream access token the facade validates (DESIGN §5.2, §6), so there is no separate audience/azpfield: a token minted for another client is refused against the same value.UpstreamIssueris the upstream issuer, not the client-facing one. It is the RFC 9207issthe callback pins and the issuerDiscoveryverifies (DESIGN §5.2, §8.2). The client-facing issuer is a different value —IssuerURLin family mode, the route URL in route mode — and the two are deliberately distinct.- There is no upstream callback-URL field. The callback URL is derived from
URLMode/PublicBaseURLplusUpstreamCallbackPath(DESIGN §3.2), so an absolute callback URL is never configured and the derived URL cannot drift from the mounted stage-global callback route. LifecycleScopesis the injectable lifecycle scope of FRAMEWORK_VS_POLICY row 7 (theoffline_accessinjection): the framework exposes it as configuration rather than hard-coding the literal, so the scope vocabulary stays application policy.ProviderHintsis the DESIGN §6 opaque hint seam (theaccount_idhint). It carries no authority: the provider derives authentication account context from its own validated binding, never from the hint.- The application-owned factories are mutually exclusive with a
Provider.Providerowns the authorize, token, and callback routes, so configuringAuthorizeHandler/TokenHandlerorCallbackHandleralongside it is a registration error rather than a silently dropped or double-mounted route. (A lone one of the authorize/token pair is already rejected by the pre-existing all-or-none factory rule.)
The framework issues no facade token and needs no signing key. The access token a client receives is the upstream token returned byte-for-byte unmodified, and the facade’s own authorization code is an opaque value — not a signed or self-describing artifact (DESIGN §8.4, §10). So there is no signing-key configuration anywhere in this field set: there is nothing for the framework to mint or verify with a key of its own.
What the front channel does
When the front-channel field set is declared, the registrars mount three route shapes, and the mechanics behind them belong to the framework rather than the application.
GET …/authorize(per endpoint kind) — front-channel termination. Validation order is client, redirect URI,response_type, S256 PKCE,state,resource, scope. A failure before the redirect URI is validated — an unknownclient_id(400 invalid_client) or aredirect_urithat does not exactly match a registered value (400 invalid_request) — renders a JSON error page and never sends aLocation. Once the redirect URI is validated, a later failure (response_typeother thancode, absent/plain/non-S256 PKCE, aresourcethat is not the route resource →invalid_target, or a scope request that clamps to nothing) redirects the browser back to that validated redirect URI as302carrying the fixederror,error_description, the client’s ownstate, and the client-facing RFC 9207iss. On success it records a single-use transaction keyed byhash(upstream state)and sends the browser upstream with the facade’s own client, callback URL, S256 challenge, fresh upstream state,resource, hints, and clamped scope set.GET /_oauth/mcp/callback(one stage-global route). The callback pins the upstream RFC 9207issagainst the configuredUpstreamIssuerbefore consuming the transaction or exchanging the code; an absent or mismatchedissis400 invalid_requestwith noLocation. It then consumes the upstreamstatesingle-use, exchanges the code server-side with the facade’s own client and PKCE verifier, validates the upstream access token, seeds the route-refresh broker with the framework-minted opaque handle and the encrypted upstream refresh material, mints a single-use facade code (durable in the code record with the encrypted token response), and redirects the client to its registered redirect URI withcode, the client’s ownstate, andiss(the route URL in route issuer mode, else the configured family issuer). Upstream codes, refresh tokens, andid_tokennever reach the client.POST …/token— theauthorization_codegrant. The grant requiresclient_id,code,redirect_uri, andcode_verifier; only a registered public client (token_endpoint_auth_methodempty ornone) may redeem. The code is single-use and bound to that client, that redirect URI, the route kind, and the S256 challenge; a mismatch is400 invalid_grant. A replay returns400 invalid_grantand revokes the broker record the code minted, so the refresh handle from that authorization dies with the replay. An expired code burns on its first consume (400 invalid_grant) and the following attempt is then a replay that revokes the broker record. Aresourcethat is not the code’s resource is400 invalid_target. On success the response is200carrying the upstream access token byte-for-byte unmodified, the upstreamtoken_type/expires_in/scope, and the framework-minted opaque refresh handle asrefresh_token; it never carries anid_tokenor upstream refresh material.POST …/token— therefresh_tokengrant. The client presents the opaque handle the code exchange returned and the sameclient_id. A handle that is unknown, locally expired, revoked, bound to another client, or presented at another route’s token endpoint is one and the same400 invalid_grant(no oracle). A successful refresh rotates the handle to a fresh opaque handle and answers200with the upstream access token byte-for-byte plus the successor handle; anid_tokenand upstream refresh material never appear in the response, a header, a redirect, or an error body. A presentresourcemust equal the bound resource (400 invalid_targetotherwise) and a presentscopemust be exactly the granted scope set — a wider set and a subset, including a present-but-emptyscope, are400 invalid_scope, because the upstream access token is returned unmodified and cannot be narrowed. A missing or over-512-byte handle is400 invalid_request. Refresh is single-flighted under the broker store’s lock, so concurrent callers of one handle cause exactly one upstream refresh call: a caller that loses that race waits up to 3 seconds, then receives the winner’s successor tokens or503 temporarily_unavailablewithRetry-After. For the configured grace window (default 120 seconds, bounded at 120 s) the previous handle replays the same successor tokens byte-for-byte (an idempotent lost-response path, including its handle material). Beyond that window the previous handle is classified by chain depth: the immediate predecessor of a live head is answered with the access token only — never handle material — at most once per handle, behind a per-family hourly budget; a second serve of the same handle, or a replay two or more generations behind the head, is theft class and revokes the whole refresh family with the sameinvalid_grant. A terminal upstream rejection is400 invalid_grant(the record is revoked), an upstream gateway failure is502 upstream_error, and a transient upstream, store, lock, or contention failure is503 temporarily_unavailablewithRetry-After. The grace window, the 3-second coalesce wait cap, the 512-byte handle bound, and the broker store’s 15-second lock TTL are framework constants; the handle lifetime, grace window, and reuse budget are the encodedRouteRefreshPolicy— no environment variable. The endpoint still answers400 unsupported_grant_typefor every other grant and400 invalid_requestfor an absent grant type. The refresh503’sRetry-Afteris a fixed framework constant (1 second) and is never computed from the injected framework clock, so a test that advances that clock can observe aRetry-Afterthat disagrees with the harness’s own real elapsed time — a harness artifact of the two clocks, not a framework defect (ADV-1145-5).POST …/register— RFC 7591 dynamic client registration. The framework-owned handler bounds and validates the client metadata, mints a server-assigned opaqueclient_id(≥128 bits), and stores the record through theClientStore, hash-keyed and bound to the advertising route. Only public clients are accepted (token_endpoint_auth_methodabsent ornone);grant_types(if present) must includeauthorization_codeandresponse_types(if present) must includecode; everyredirect_urimust be an absolute URL with no fragment that is eitherhttpsor loopbackhttp; unknown JSON members are ignored. Both the raw body and the metadata are bounded, and the route is per-route rate limited through theRateLimitStore, keyed by the advertising route kind plus the provider-derived source identity (a shared per-route bucket when no source identity is available, so it fails closed to the stricter bucket), with a store or bucket error failing closed too. A refusal is400with a fixed RFC 7591 error code (invalid_client_metadataorinvalid_redirect_uri); a rate-limited or store-failed request is429with the fixed codetemporarily_unavailableand aRetry-Afterheader. The201response carriesclient_id,client_id_issued_at, the normalized metadata, and noclient_secret(a public client has none), withcache-control: no-store.
Provider failures are their own class. A provider AuthorizationURL / ExchangeCode / ValidateAccessToken
failure is never returned in the facade’s 400 vocabulary: it is a distinct 502 carrying the fixed error code
upstream_error (error page, no client redirect), so the facade’s own request-class rejections and a gateway-class
upstream failure stay distinguishable. The rule is the same on both legs. On /authorize, a failure of the provider’s
AuthorizationURL builder or of the app-supplied ProviderHints is that gateway-class 502, while the 400
vocabulary stays the facade’s own client-caused rejections (invalid_client, invalid_request, invalid_target); on
/callback, any exchange or token-validation failure is the 502, which is what keeps the iss and state pins
non-vacuous. The client-facing error vocabulary is closed and fixed — every rejection of one error code carries the
same error_description — so the response never distinguishes an unknown key from a used one.
Encryption is still a store obligation. The front channel hands each store the upstream material it must protect
and relies on the store to seal it: a durable store must encrypt every Encrypted* field at rest, and the
framework never writes upstream material to a log, a redirect, a response, or an error body.
The JSON bodies are semantically identical across runtimes, not byte-identical. The token and error bodies are
JSON encoded by each runtime’s own encoder: Go’s encoding/json HTML-escapes &, <, and > as \u0026,
\u003c, and \u003e, while the TypeScript (JSON.stringify) and Python (json.dumps(..., ensure_ascii=False))
runtimes emit those characters raw. Every form decodes to the same values, and the grace replay is byte-identical
within one runtime (which is what the configured grace replay requires); no cross-runtime byte equality is promised, so
a cross-language golden comparison must normalize or compare decoded values, never raw bodies.
Conformance suites and the fake provider
Three shared conformance tables drive all three runtimes from one source (contract-tests/fixtures/routing/mcp-auth-facade/):
facade-provider-conformance.v1.json— discovery, authorize-URL construction, code exchange, refresh and token validation rows, run against the Autheory adapter and a tiny second adapter (provider-neutrality) over a real local HTTP fake upstream with real RSA keys.facade-store-conformance.v1.json— the atomicity rows (single-use consume, replay vs unknown, rotation/CAS, lock with expiry, idempotent revoke, rate-limit window) including concurrent-consume/rotate/revoke rows, the broker expiry-versus-absence signal, and the optional family capability rows (list_family,revoke_family, and an unknown-family empty result), run against the in-memory reference stores.facade-conformance.v1.json— the front-channel behavior rows executed through the real mounted handlers: the RFC 9207isspin, the loopback redirect match, the bounded strict/tokenform parse, the method-mismatch rule, the RFC 7591 DCR (dcr) rows, the DCR route binding (bound_route) rows, and the brokered refresh (refresh) rows (rotation, the grace replay, the beyond-grace depth-1 access-token-only serve, the second-serve/theft revocation, the byte-identical refusal set, the scope/resource rule, the handle bound, replayed-code revocation, and the upstream terminal/transient failures).facade-middleware-order.v1.json— the runtime-bearer ordering rows executed through a really-mounted plainAppandSecureApp: the bearer guard runs before application middleware onPOST/GET/DELETE, a short-circuiting cache middleware cannot serve a credential-free request or perform a cache lookup, a pass-through writer cannot run before denial, valid credentials order as guard → middleware → handler, and the pre-authorizationPolicyHookstill runs before the guard.
Any store — the in-memory ones now, an application’s durable store later — must pass the store conformance suite. A
fake provider (real RSA keys, real local HTTP, configurable success/error/slow/oversized-filler/oversized-valid-json/
rotated-refresh/missing-iss/bad-signature behaviours) ships in the test-support area for the executed journey tests.
The oversized-valid-json mode serves a well-formed token document whose access_token is itself past the cap, so the
response-size bound is observable rather than indistinguishable from a JSON parse failure.
Where the code lives
| Surface | Go | TypeScript | Python |
|---|---|---|---|
| Provider SPI + Autheory adapter | runtime/oauth/provider.go, runtime/oauth/provider_autheory.go |
ts/src/oauth/provider.ts |
apptheory.oauth.provider, apptheory.oauth.autheory |
| Store SPI + reference stores | runtime/oauth/store |
ts/src/oauth/store.ts |
apptheory.oauth.store |
| Framework-owned front channel | runtime/mcpfacade/front_channel.go, runtime/mcpfacade/front_channel_config.go, runtime/mcpfacade/dcr.go |
ts/src/mcpfacade.ts (front-channel section) |
apptheory.mcpfacade (front-channel section) |
| Store key derivation | oauthstore.HashKey |
hashKey |
hash_key |
| Fake provider (test support) | testkit/oauthprovider |
ts/src/testkit/oauthprovider.ts |
apptheory.oauth.fake_provider |
The Store SPI is a separate Go package because the package oauth already declares the older, narrower
AuthorizationCodeStore/RefreshTokenStore types. The TypeScript rate-limit key type is exported as
RateLimitBucketKey because the TypeScript SDK already exports limited.RateLimitKey.
The store-key helper is intended public API. oauthstore.HashKey / hashKey / hash_key — the unpadded
base64url SHA-256 of the protected value — is ratified as supported public surface, not an internal detail. Every
store SPI is keyed by the hash of the value it protects and never by the value itself, so this helper is the seam
an application uses to pre-register a client while DCR is unmounted (and, once DCR lands, to reconcile a client
it already knows through another path). It is a pure, authority-free derivation: it only reproduces the key the
facade itself derives when it looks a record up, and it grants no access of its own.
Non-goals today
Still absent, by milestone:
- CDK wiring: the
AppTheoryMcpServerconstruct wires the stage-global callback path override throughupstreamCallbackPath, resolved by the sameAppTheoryMcpRouteAlgebra.callbackPathForConfiguredPaththe runtime applies toUpstreamCallbackPath, so the mounted and registered callback routes cannot diverge. The construct’sfacadeattach prop is presence-only by design and deliberately does not wire the provider and the stores: its presence selects theruntime-bearerposture and enables the route derivation and the defense-in-depth floor checks, while the provider and the five store SPIs are runtimeFacadeConfigconfiguration (FRAMEWORK_VS_POLICY.md). - A subset-accepting refresh scope: not built and not planned. A present
scopeon a refresh must be exactly the granted set (ruling R4); the facade cannot narrow an upstream access token it returns byte-for-byte. - A durable store: the framework still ships none. The in-memory reference stores are non-durable and do not encrypt; a deployment supplies a durable store that discharges the encryption obligation above.
- Transport-route bearer enforcement is unchanged (M1/M2).