Skip to main content

ADR-0021: Registry & Gateway Architecture (MCP + LLM)

  • Status: Accepted (founder approval 2026-07-06, upsquad-ai/upsquad-core#1682)
  • Date: 2026-07-06
  • Decision owners: Founder (sign-off), Principal Architect (author), Backend SME (Context Engine / gateway), DevOps (GKE LOE), Product Manager (PRD #1674)
  • Related:
    • PRD upsquad-ai/upsquad-core#1674
    • ADR-0020 — dual-runtime worker types (#1627)
    • upsquad-ai/upsquad-core#1647 (+ its W2 dependency for grants reaching agents)
    • upsquad-ai/upsquad-core#1642 / #1643 — Org v2.4
    • LiteLLM dev facade PR #1632
    • upsquad-ai/upsquad-core#3679 — Amendment 1 (decision 4 carve-out; terms position and founder decision 2026-10-02)

Status​

Accepted — founder approval 2026-07-06 (via GitHub comment on #1682).

Context​

Founder requirements driving this ADR:

  • MCPs must be registry-mandatory (no ad-hoc upstreams).
  • Each MCP gets a stable per-MCP proxy URL.
  • Team binding with team-owner/Manager approval; cascade via Org v2.4 resolver + the core#1647 snapshot work.
  • User-composable group proxies that aggregate multiple MCPs without tool-name conflicts.
  • Per-tool deterministic guardrails set at team level (e.g. args.amount <= N, response filters).
  • The same architecture pattern applied to LLM models (model registry + gateway), not just MCP tools.

This ADR captures ONE architecture pattern with TWO instances: MCP (tools) registry+gateway and LLM (models) registry+gateway.

Basis: adversarially verified research (deep-research workflow, 9 findings, 0 refuted), code-grounded architect passes over the current ContextForge-based mcp-proxy + Go registry, and DevOps/LOE assessments.

Decisions​

1. Registry unification. proxy_upstreams becomes a projection of mcp_servers + mcp_server_units — a single source of truth. The registry gains probe-time tool-schema capture, versioning, and status = pending | approved | disabled. Schema modelled on the official MCP registry (namespaced names, ownership verification, designed for private-subregistry federation — verified 6-0).

2. Proxy technology. KEEP the ContextForge-based mcp-proxy + Go registry (ContextForge's two-tier auth verified 9-0 as the reference multi-tenant pattern). Envoy stays edge-only. NO rebuild. Envoy AI Gateway verified 12-0 as the strongest k8s-native alternative (MCPRoute aggregation, session multiplexing, OAuth termination, native per-tool CEL) — a formal RE-EVALUATION GATE at GKE migration.

3. URL scheme. App-layer path routing: /mcp/{registry-id} and /mcp/group/{id}; the edge keeps ONE coarse route. Each URL serves per-path RFC 9728 protected-resource metadata (spec-mandated, verified 6-0).

4. Auth. Gateway terminates OAuth; token passthrough is NORMATIVELY BANNED (verified 9-0, spec verbatim). Per-upstream tokens via RFC 8693 token exchange; RFC 8707 audience binding mandatory; confused-deputy prevention (per-client consent + client registry) required for dynamic client registration (verified 6-0).

Amendment 1, 2026-10-02 — ACCEPTED (founder approval 2026-10-02, PR #3689 comment 5946673789; record on core#3679). One narrow carve-out from the passthrough ban on the LLM instance only: a developer's own Claude Code subscription bearer, forwarded transiently and unchanged to api.anthropic.com, only when the same request carries a verified UpsQuad subscriber identity. Everything else in this decision is unchanged. The carve-out is stated as an enforceable predicate, with its handling obligations, ledger treatment and gate rulings, in Amendment 1 below.

5. Groups. Register-time conflict rejection for authored groups + automatic {server}__{tool} prefixing as safety net (industry consensus verified 15-0). Group session-map = one client session → N upstream sessions. v1: streamable-HTTP upstreams only (SSE federation unsupported industry-wide); reject callback-requiring upstreams.

6. Per-tool guardrails. Policy store in Postgres keyed (team, server, tool); ARGUMENT rules as CEL expressions + RESPONSE filters (DLP/regex/redaction); evaluated in our proxy plugin chain; policies EMIT portable CEL so they can compile onto Envoy AI Gateway post-GKE. Team-level semantics ride the Org v2.4 guardrail axis (unconditional push down home chain).

7. State discipline. Group session-map + snapshot caches in REDIS, never in-process (multi-replica GKE requirement).

8. Approval. MCP↔team attach requires team Manager approval (org_units.manager_member_id, Org v2.4 authority); binding is inert until approved.

9. LLM instance of the pattern. Model catalog + BYOK vault + team_model_allowlists (exists) + internal/aigateway + Anthropic-format facade (replaces dev LiteLLM; ties to PRD #1674); same team binding / approval / guardrail semantics.

Amendment, 2026-09-25 (core#3601; founder direction, architect's ruling #3601 issuecomment-5828940160 §1/§3). The LLM instance's approval axis is the ENDPOINT BINDING; the model set is a narrowing ATTRIBUTE of it.

Decision 9 gave the LLM instance a model-level approval axis mirroring the MCP one: team_model_allowlists with its own pending/approved/denied lifecycle and its own Manager inbox. That mirror is withdrawn. The two grains were not analogous — an MCP server is a resource a team is granted, while a model is something an already-granted endpoint either serves or does not — and keeping a separate approval axis for the second produced a control that could name models the team could not reach and exclude the ones it could. Measured on beta-dev: the Engineering team held two PENDING entries (gpt-4o, Claude Sonnet 4), neither served by any endpoint it was bound to, and approving either would have made gate 7c deny the only model its endpoint served (core#3146 5813201959).

What replaces it: llm_endpoint_units.enabled_models (migration 262), a narrow-only JSONB attribute of the binding row. Binding approval (L4 and the unit's Manager) approves the ceiling — every model that endpoint serves — and the narrowing can only remove from it, so it needs no second approver. NULL and [] both mean no narrowing; a list equal to the endpoint's full served set canonicalises to NULL. Gate 7c reads it off the binding row it already holds, so the model axis costs zero extra reads and cannot disagree with the endpoint axis by construction.

Decision 8 is UNCHANGED and is the part that still holds: attachment requires team-Manager approval, and a binding is inert until approved. What changed is that the LLM instance now has ONE approval axis instead of two, which is what decision 8 describes for MCP. team_model_allowlists is retired as a policy source and is dropped in a later migration.

10. No service mesh now. Ambient mesh + sidecar + SPIFFE re-evaluated at GKE (verified: zero industry evidence of established practice on mesh L7 MCP awareness / per-agent sidecars / SPIFFE propagation — nothing to adopt yet).

GKE Transition​

Sequencing decision = COMPOSE-FIRST. Rework analysis: throwaway is 3-5% (~half a day) — a few Envoy routes / compose defs. GKE-first would block the entire build 3-4 weeks and collide with the live Org v2.4 migrations on the same tables.

GKE migration facts (DevOps LOE): foundation ~80% exists (VPC / WIF / Artifact Registry / tunnel live; CloudSQL stopped with data; some kustomize manifests + 1 ArgoCD app). GkeStack is an EMPTY STUB.

Work items: fill GkeStack (M), missing manifests — ai-gateway / client / spa / pgbouncer / migrate-jobs (M), ArgoCD app-of-apps (M), CloudSQL reactivate (S), Memorystore recreate (S), Secrets → Secret Manager + ESO (M), Gateway API ingress + Cloudflare cutover (M), Managed Prometheus (M), CI rewire (M), cutover + rollback (M).

Total: 6-9 person-weeks, 3-4 weeks calendar, +$450-600/mo.

Autopilot constraints: no privileged daemonsets, no host networking, resource minimums, ollama impractical (prod = BYOK, drop).

What changes at GKE for THIS architecture: host Envoy → Gateway API; Envoy-AI-Gateway re-eval (decision 2 gate); ambient mesh for mTLS/identity; per-tenant worker pods make sidecars meaningful; SPIFFE identity revisit.

What stays identical: all app-layer routing, registries, policy store, session state (already Redis), plugins.

Alternatives Considered​

  • Adopt Envoy AI Gateway now — rejected: k8s-CRD-native, no compose deployment.
  • Adopt agentgateway / MetaMCP — rejected: replaces the working governed proxy, loses our audit/idempotency plugins.
  • GKE-first sequencing — rejected: blocks build 3-4 weeks, collides with Org v2.4 migrations.
  • Build-nothing / static config — rejected: registry mandate + team cascade impossible.

Consequences​

Positive

  • Single source of truth (registry) removes proxy_upstreams drift; versioned, probe-captured schemas.
  • One pattern reused for MCP and LLM → shared binding/approval/guardrail machinery.
  • Portable CEL policies keep an exit path onto Envoy AI Gateway at GKE.
  • Compose-first keeps the entire build unblocked; ~half a day of throwaway.
  • Redis-first state is GKE-multi-replica-ready from day one.

Negative

  • Continued dependency on the ContextForge upstream project (roadmap / maintenance risk).
  • Group session-map complexity (1→N session fan-out, lifecycle, cleanup).
  • Two proxy technologies coexist (our plugin proxy + edge Envoy) until the GKE re-eval gate.

Risks

  • MCP auth spec churn (RFC 9728 / 8693 / 8707 / confused-deputy guidance still evolving) — may force follow-up work.
  • SSE / callback upstreams unsupported in v1 → some real-world MCPs excluded until federation matures.
  • Envoy AI Gateway re-eval could reverse decision 2, incurring migration cost of the plugin chain.

Amendment 1 — 2026-10-02 — verified-identity subscription passthrough (core#3679)​

  • Status: Accepted (founder approval 2026-10-02, PR #3689 comment 5946673789 — user.type == "User", body approved, 2026-10-02T06:22:52Z; the PR merged as a89452cc2). The condition the previous status line attached — decision 4 and internal/modelgateway/transport/headers.go unchanged until a founder comment on the PR — is discharged by that comment. Implementation LLD: #3698 (architect-approved under the 2026-07-26 artefact split; HLD #3692). Canonical implementation names that differ from this amendment's working names are recorded inline at A1.2 account(R) and A1.3 S-REG.
  • Scope: the LLM instance of the pattern only (decision 9, the Model Gateway). The MCP instance's passthrough ban is untouched.
  • Record: the founder decision, the verbatim Anthropic terms (S1, S2), the measured wire shape (S3), the element-by-element interpretation, the commitments and the accepted residual risk are all on core#3679 (issuecomment-5946231754). This amendment refers to that record and does not restate it. The product record is the PRD #2644 delta being drafted by the Product Manager in parallel; this amendment is the engineering rule, and the two cite each other.
  • Supersedes: the 2026-09-30 disposition in core#3679's body ("not buildable securely and not permitted") on its terms leg. Its engineering findings — no verifiable per-request identity from Anthropic, no per-member key registry, a ledger that cannot express flat-rate usage, a fifth sourcing mode — were correct and are what this amendment supplies controls for.

A1.1 Context — why the ban exists, and why this case is different​

Decision 4 banned token passthrough because of what passthrough means in the MCP authorization spec: a gateway accepting a token issued to it (or to some other audience) and replaying it to an upstream, so that the upstream sees a credential whose audience, consent and lifetime were decided elsewhere. The spec calls this out as the confused-deputy opening; the ban is paired with RFC 8707 audience binding and RFC 8693 exchange precisely because the cure is "mint a token for this upstream, for this caller, for this call". headers.go:20-34 enforces the LLM analogue by construction: the caller's Authorization/X-Api-Key/Api-Key/Cookie are dropped before the tenant credential is substituted, so there is no fall-through to a caller header even under AuthNone.

The case carved out here has three properties the banned shape lacks, and together they are why "passthrough" is a misnomer for it:

  1. The credential belongs to the caller. It was issued by Anthropic to the developer, in Anthropic's own sign-in flow, on the developer's machine. UpsQuad did not mint it, does not hold it, and is not its audience.
  2. It is used only for the caller's own request. The request that carries the bearer is the request the developer's own, unmodified Claude Code made. The gateway forwards that request; it never makes a request of its own with the bearer, never attaches it to a different request, and never holds it past the response.
  3. It is billed to the caller. The usage lands on the developer's own subscription and its limits (S2). The organisation pays nothing, meters no dollars, and resells nothing.

A deputy that is confused has used someone's credential for a purpose or audience they did not intend. Here the audience (api.anthropic.com), the purpose (this request) and the payer (this developer) are all the ones the credential's owner chose. What the gateway adds is the organisation's governance over traffic its members chose to route through it — identity, audit, content guardrails, token visibility — not a change of who is calling whom.

What makes this a decision rather than a reading is that Anthropic's own S1 text is strong on every element but one (the word intermediate, read as "handle in transit"), and S1 reserves enforcement without notice. The founder has weighed that and decided to proceed (#3679). This amendment therefore does not argue the terms; it fixes the engineering rule so that what we build is exactly, and only, the thing the position on #3679 describes.

A1.2 The carve-out, as a predicate​

Let R be an inbound HTTP request to the Model Gateway. Define:

TermHolds iff
route(R)X-UpsQuad-Subscriber is present on R. Its presence selects the subscription admission exclusively: R is decided by this predicate and by nothing else. Its absence means R is decided by the existing admissions (member API key, agent token, capability token), under which a subscription-shaped bearer fails JWKS as it does today (agentauth/middleware.go:223-230).
shape(R)R carries exactly one Authorization value, of the form Bearer sk-ant-oat01 followed by the opaque suffix of the length measured on S3 (the LLD pins the exact pattern); anthropic-beta is present and contains the token oauth-2025-04-20; none of X-Api-Key, Api-Key, Cookie, Proxy-Authorization is present.
subscriber(R)the X-UpsQuad-Subscriber value is present exactly once and verifies, by constant-time comparison of its hash, against one row of the subscriber registry (A1.3, control S-REG) that is not revoked, not expired, whose member is active in its organisation, and whose org unit is active and holds an approved binding to the subscription endpoint (decision 8 — Manager approval, binding inert until approved).
ours(R) = ∅no gateway-owned credential is resolved for R or attached to the outbound request: the route's credential scheme is caller_subscription (A1.3, control S-SCHEME); the vault is not consulted; the outbound header set contains exactly one Authorization, byte-equal to the inbound one.
account(R)the account_… segment of R's body metadata.user_id (shape per S3 and the August PoC's identity.go carrier-(d) parser — account/device/session; the LLD fixes the parser) is present and parses. If the subscriber row's account_ref is NULL, it is bound now (written, audited, visible to the member and the Manager). Otherwise it equals the bound value. Naming (LLD #3698 §0): the canonical column is observed_account_uuid; account_ref is this amendment's working name, kept where it appears so the history reads. The name says what the value is — client-supplied and unsigned (A1.8), an observation and not a verified fact.
surface(R)(method, path) is in a closed allowlist of Claude Code request shapes, each entry justified by a request the unmodified binary was measured to send (the spike on #3679 item 3; POST /v1/messages at minimum).
gates(R)HLD #2649 §5.1 steps 4, 5, 6, 7a, 7c, 7d, 7e all admit R, as ruled in A1.6.

forward(R) ⟺ route(R) ∧ shape(R) ∧ subscriber(R) ∧ ours(R) = ∅ ∧ account(R) ∧ surface(R) ∧ gates(R).

When forward(R) holds, the gateway forwards R to https://api.anthropic.com with its own bearer, modified only as A1.4 states, and relays the response — including a 401 — unchanged.

When it does not hold, the gateway refuses R with a complete response on the wire and a ledger row (governance_outcome = 'deny', deciding_gate naming the failed term). There is no fall-through to any other admission. In particular:

  • route(R) ∧ shape(R) ∧ ¬subscriber(R) — a subscription bearer whose identity header is missing, unknown, revoked, expired, or on a team with no approved binding — is refused. It is not admitted on an API key, because there is no API-key arm here to fall to: the API-key admission is keyed on a uq_key_* credential, which this request does not carry. The 2026-09-30 proposal's "unregistered → fall back to API-key admission" arm does not exist in this design.
  • route(R) ∧ ¬shape(R) — the identity header beside anything other than a subscription bearer (an agent token, a uq_key_*, an sk-ant-api… API key, two Authorization values, an X-Api-Key) — is refused, not routed to the admission the bearer would otherwise have matched. A stray identity header is a misconfiguration, and a request that is ambiguous about which admission it wants gets neither.
  • ¬account(R) on a bound row is refused and audited as a mismatch: the identity header is being used from a Claude account other than the one it was first used with. OQ-20 ruling: this answer governs — refuse on mismatch, with self-serve re-bind by the subscriber in the portal (LLD #3698 §7.3) — taken under the founder's standing single-recommendation rule on HLD #3692 (#3692#issuecomment-5947594855); PRD #2644 MG-SUB.9/.10 are amended to match in v1.8.

The predicate is also the negative space of the ban: a request that is not R-shaped meets headers.go exactly as it does today. Decision 4 is unchanged for every other request.

A1.3 Handling obligations, and the control that enforces each​

The bearer is a credential we did not issue, held for a caller we did not authenticate to Anthropic, forwarded to an upstream we do not own. Each obligation below names its control, says whether that control exists today (for the tenant's BYOK upstream secret) or is new, and for every new control names the mutant its test must kill. "Remember not to log it" is not a control (endpointcredential/secret.go says this about the vault write and it applies with more force here).

#ObligationControlStatusMutant the test must kill
S-RENDERNever rendered — not by %v, %d, %#v, JSON, text, or slogThe in-flight bearer is carried as transport.Credential{Scheme: AuthCallerSubscription, Secret: …}; transport.Credential already redacts every rendering path (transport/types.go:95-107, credential_redaction_test.go). The at-rest analogue for the vault write is endpointcredential/secret.go's fmt.Formatter type.Existing— (already pinned; the verb sweep is the oracle)
S-LOGNever logged, including on refusal paths and in error stringsToday's admissions log "a check, not a value" (agentauth/middleware.go:226-229). New: the shape check, the subscriber lookup and the account comparison each have refusal branches that see the bearer and the header, and each must produce an error text with neither in it.NewInterpolate the bearer (or the X-UpsQuad-Subscriber value) into any refusal message or slog attribute on the subscription path ⇒ a test that drives every refusal arm and asserts no emitted line contains sk-ant- or the header value reds.
S-TRACENever a span attributepassthrough/tracing.go's oracle asserts the span key set is a subset of a declared allowlist, by design, because a substring check passes the moment a secret is base64'd (#3583 §3, landed in #3633).Existing mechanism; new coverageAdd an attribute key carrying the inbound Authorization or the subscriber header on the new path ⇒ the key-set test reds. The allowlist gains no key for either.
S-PERSISTNever persisted — nor any derivative of it (no hash, prefix or length; the August PoC's sha256(bearer)[:12] fingerprint is the practice this forbids) — no ledger column, no audit detail, no cache, no captureThe ledger schema has no column for a credential value and the recorder takes callFacts, not the request (gates.go gateInput doc). New: the subscriber header is stored hashed only (S-REG) — that is our credential, and hashing it is how it is verified; the bearer is Anthropic's and gets no hash. The thing that is persisted from the body — account_ref — is an account identifier, not a secret, and that is the only body field this path records.Existing for the ledger; new for the registryStore the plaintext identity header, or write any Authorization value or digest of one to any table/detail bag ⇒ a test that inserts a registration and scans the row for the plaintext, and a test that scans every audit detail and ledger column emitted on the path for the bearer and its SHA-256, red.
S-REUSENever reused — derived from this request, forwarded with this request, never attached to anotherpassthrough.Route.Credential is "resolved per request and never cached in this package" (handler.go:44-46); the resolution cache (cache.go) caches endpoint rows, not credentials. New: that property becomes load-bearing for a value the caller owns, so it gets a test.Existing behaviour; new pinCache the Route (or its Credential) across requests, or build the outbound credential from anything other than the inbound header of the same *http.Request ⇒ a two-request test with two distinct bearers asserting each outbound carries its own, reds.
S-DISCARDDiscarded at response — nothing retains the bearer past the relayThe relay holds one frame at a time (passthrough/concurrency_footprint_test.go); the outbound *http.Request is dropped with the handler. New: no retry layer may re-send with the bearer after the response has begun, and no error-path capture (the "debug dump the request" pattern) may exist on this route.New pinAdd a post-response re-dial, or a request dump on the upstream-error path ⇒ a test counting upstream requests per inbound request (exactly one) and asserting no retained reference, reds.
S-HOSTNever forwarded to any host but api.anthropic.comNew. The caller_subscription scheme may exist only on a platform-managed llm_endpoints row whose base_url host is exactly api.anthropic.com: a DB CHECK ties the scheme to the host; dialguard/hostallow refuse the dial otherwise; a tenant cannot create, edit or re-point such a row. This is the control that turns "passthrough" back into "harvesting" if it is missing — a tenant-controlled upstream receiving members' subscription bearers.New(i) Insert a caller_subscription row with another host ⇒ CHECK violation, test reds. (ii) Bypass the CHECK in the fixture and dial ⇒ dialguard refusal, test reds. (iii) Attempt the tenant-side RPC to set the scheme ⇒ refused, test reds. All three; one layer is not a control.
S-SCHEMEThe forwarding happens in one place, the place the ban is enforcedNew. SanitizeRequestHeaders (headers.go:161) gains a scheme arm AuthCallerSubscription that preserves the inbound Authorization iff shape(R) and sets nothing of ours; every other arm keeps stripping unconditionally (headers.go:176-178). The carve-out and the ban live on the same switch, so a reader of the ban sees the exception and a reader of the exception sees the ban.New(i) Make the strip conditional on the scheme for AuthBearer/AuthXAPIKey/AuthNone ⇒ the existing "caller Authorization never reaches upstream" tests red. (ii) Under AuthCallerSubscription, also set an X-Api-Key from the vault ⇒ the "exactly one Authorization, no X-Api-Key" test reds. (iii) Under AuthCallerSubscription, forward a non-sk-ant-oat01 bearer ⇒ the shape test reds.
S-REGThe identity header is a platform credential: minted by us, hashed at rest, prefix-distinguishable, scoped to (org, member, unit), rotatable, revocableNew. A llm_model_subscribers table — canonical name per LLD #3698 §0 (PRD #2644 §5 prefix symmetry: every Model Gateway table carries the llm_ prefix that hack/rls-check.sh and the classregistry mirror key on; companions llm_model_subscriber_grants, llm_subscriber_settings); gateway_subscribers is this amendment's working name — (RLS, app_rw cannot sweep cross-org — dbguard), one active credential per (org, member), revoked_at/expires_at, observed_account_uuid (working name account_ref; A1.2 account(R)), and an audit event on mint, bind, rotate, revoke and mismatch. It is not a member_api_keys row: a uq_key_* admits the org-billed API-key path, and a credential that can admit two paths is the fall-through A1.2 forbids.NewMint with no expiry, or verify a revoked row, or verify across orgs under app_rw ⇒ the respective tests red.

A1.3 is the list a reviewer checks the implementation PR against. Every "New" row needs its mutant-killing test in the PR that adds the control; a row shipped without its test is the SHELFWARE-check failure in its security form.

A1.4 What is forwarded unchanged, and what is added​

Body: forwarded byte-for-byte. ModeTranslate is refused on the subscription endpoint (A1.6, step 6): the request must reach Anthropic as the developer's client composed it.

Preserved byte-for-byte (these already survive SanitizeRequestHeaders by construction, because the strip set is an explicit list and everything else is forwarded — headers.go:139-142): anthropic-beta (S2 requires the OAuth capability be forwarded; it is also the thing that makes the request readable as what it is), anthropic-version, User-Agent, x-app, X-Claude-Code-Session-Id, and every other provider-native header. Byte-transparency on User-Agent and anthropic-beta is also the enforcement-fingerprint mitigation #3679 records: the request on the wire is the developer's request.

Stripped before upstream: our own X-UpsQuad-Subscriber — covered today by the x-upsquad- prefix rule (headers.go:47, IsInternalHeader), which is why the header is spelled with that prefix and must keep it; RFC 7230 hop-by-hop; edge metadata (X-Forwarded-*, Cf-*, …); the caller's W3C trace context (the gateway's own is injected, #3583 §3).

Added: Accept-Encoding: gzip (the one permitted mutation, LLD §4.1 — metering cannot read a Brotli body) and the gateway's traceparent. Nothing else. No X-Api-Key, no gateway Authorization, no metadata rewrite, no model substitution.

A1.5 Ledger​

Three changes, the first two of which are new vocabulary and the third a new column.

(1) credential_class = 'subscription'. A new member of identity.CredentialClass (internal/auth/identity/identity.go:111-142; the Go domain is closed, migration 225 deliberately puts no vocabulary CHECK on the column). It reaches the ledger through callFacts like the other three and is not readable by any gate (gateCaller, gates.go:446-451 — the interface has no CredentialClass method, and TestGateChain_CannotAskWhoAuthenticated scans the two ways round it; a fourth class is scanned the day it is declared).

(2) credential_runtime stays NULL, and migration 225's CHECK is untouched. 225 defines the column as the token's runtime claim, carried verbatim, and adds it only because two agent_token mints share a class so the mechanism is not derivable from the class — "the test is derivability" (225 … .up.sql, "WHY THE LEDGER NEEDS THIS"). A subscription row has no UpsQuad-minted token and exactly one mechanism, so the mechanism is derivable from the class, and 225's own test says: no second column value. credential_runtime_requires_token_class (CHECK (credential_runtime IS NULL OR credential_class IS NOT DISTINCT FROM 'agent_token')) is satisfied by NULL and needs no change. The client version (claude-cli/<ver>) is a User-Agent fact; if the PRD wants it, it is a new column named for what it is, not a value smuggled into credential_runtime.

(3) A new cost basis, subscription_billed, as a column. Today the ledger expresses cost two ways: cost_usd a number (org-metered, priced), or cost_usd IS NULL with llm_usage_costs.unknown_reason naming one of five closed reasons (pricing/price.go:91-118; llm_usage_costs_unknown_reason_check, migrations 203/238). Neither expresses "there is no organisation dollar figure for this call, and that is not a gap". Both existing encodings are rejected for this row:

  • cost_usd = 0 reads as genuinely free (203 … .up.sql:478). A subscription call is not free; it is paid by someone else. Rolling it into the org's $0.00 rows hides exactly the fact the founder ruled must be visible (#3661 rule 3 / #3673: a cost change is shown to the user, never silently zero).
  • cost_usd IS NULL + a sixth unknown_reason reads as unknown. It would increment cost_unknown_events (203 … .up.sql:565), degrade budgetburndown's projection status (its UnknownCostEvents > 0 arm), and send an operator to chase a rate card that does not apply.

So the basis is a column: llm_usage_events.cost_basis TEXT NOT NULL DEFAULT 'org_metered' CHECK (cost_basis IN ('org_metered', 'subscription_billed')), with a derivation guard in 225's style so the two provenance facts cannot disagree: CHECK ((credential_class IS NOT DISTINCT FROM 'subscription') = (cost_basis = 'subscription_billed')). Under subscription_billed: cost_usd IS NULL, no llm_usage_costs row is written (the pricing job skips the event by basis), and every token count is recorded exactly as for an org-metered call.

cost_basis is derivable from credential_class today, and that is acknowledged rather than hidden. It is a column anyway because its consumers — the llm_usage_effective_cost view (migrations 227/250), cost_unknown_events, budgetburndown, the cost UI — must each tell "not org-metered" from "unknown" without hard-coding which credential classes are org-metered. That mapping is the policy the founder's rule makes visible, and an N-place enumeration of it across SQL views and Go is the EDGE/MEMBER-SET defect by construction. Named consumer changes, each in the implementation LLD: the view exposes cost_basis and computes cost_unknown := cost_usd IS NULL AND cost_basis = 'org_metered'; cost_unknown_events counts only org_metered; budgetburndown excludes subscription_billed rows from both priced and unknown counts and reports them as a third figure; the UI renders the row as "subscription-billed — not metered to this organisation", with tokens, never as $0.00 and never as "unknown".

Failure direction of a consumer that has not yet learned cost_basis: it sees cost_usd IS NULL and renders unknown. That is the conservative error — it prompts a question rather than silently reporting a cost that is not there — and it is the direction #3661 rule 3 asks for.

A1.6 Which gates apply (HLD #2649 §5.1 numbering; gates.go:114-176)​

StepRulingWhy
3 identityNew admission (A1.2 route ∧ shape ∧ subscriber ∧ account) produces a CallerIdentity with ClassSubscription, MemberID = the subscriber, TeamID = the registration's unit, AgentID = empty. Refusals cite 3/identity with a reason naming the failed term.The closed identity domain (identity.go:147-152) gains a constructor reachable only from this middleware.
4 rate limitApplies, unchanged. Per-identity buckets (ratelimit.go), keyed off gateCaller, which cannot see the class.The limit protects the gateway, not Anthropic's quota; a subscriber is one identity and gets one identity's buckets. Anthropic's own anthropic-ratelimit-* / 429 are relayed unchanged (A1.4).
5 routing + bindingApplies. The subscription endpoint is a platform-managed llm_endpoints row (api.anthropic.com, dialect anthropic, scheme caller_subscription — A1.3 S-HOST/S-SCHEME). A team reaches it through an llm_endpoint_units binding under decision 8: Manager approval, inert until approved. No binding ⇒ 5/binding refusal.The Manager's approval is the organisation's consent that its members' subscription traffic may flow through the gateway at all. Reusing the binding is what keeps this "one pattern, two instances" (decision 9) rather than a side door.
6 modePassthrough only. ModeTranslate is refused on this endpoint regardless of the binding's allow_translation and the caller's opt-in.A1.4: the body reaches Anthropic as composed. The dialect is anthropic on both sides, so there is nothing to translate anyway; the refusal exists so a future binding knob cannot re-open it.
6 metering (unmetered gate)Applies. Anthropic's usage frames are readable; the endpoint is meterable.Token counting is the whole of the organisation's visibility here.
7a clearance floorApplies. The subscriber's clearance against the endpoint's min_clearance.A member below the floor is refused the way they would be on any endpoint.
7b agent enablementNot applicable, by the existing rule for non-agent callers: AgentID is empty, and LoadEnablement returns no narrowing for an empty id (enablement.go:235-237). No change.There is no agent.
7c model refusalApplies. The model is in the body; the binding row's enabled_models (decision 9 amendment, migration 262) narrows what the team may call.The organisation can say "no Opus through here" and have it hold.
7d budget — token capsApplies, unchanged in kind, with one addition. Gate 7d is a token budget over org/team/agent grains composed min-of (budget.go). Subscription tokens count against the org and team grains like every other token: the grains are a governance quantity ("tokens through this gateway"), not a dollar quantity, and a gate that excluded them would have to ask which mechanism authenticated the caller, which gateCaller forbids (LLD #2901 §3.1). Added: a per-subscriber token cap, set by the Manager or org admin on the registration, composing min-of with the others (adding a grain can only lower the minimum — budget.go, "DEGRADES CORRECTLY"). The LLD decides the key plumbing under the constraint that gateCaller learns a budget subject, never a mechanism.Per-subscriber caps are the organisation's lever on a member routing a lot of traffic.
dollar budgets, burndown, projectionsDo not apply, by construction. There is no org dollar for this row (A1.5). budgetburndown excludes subscription_billed events from USD and from unknown_cost_events, and reports them as their own figure.A dollar control over a zero-dollar quantity is not a control; pretending otherwise would make the projection lie in whichever direction the rows were counted. This is a bypass of dollar budgets by construction and is recorded as such in A1.8.
7e guardrails / PIIApplies. The body is scanned exactly as for any call.Content policy is the organisation's; the payer is irrelevant to it.
8 credentialThe carve-out. Under caller_subscription, step 8 resolves nothing from the vault and SanitizeRequestHeaders preserves the inbound bearer (A1.3 S-SCHEME).The one place the ban is relaxed, and the one place it is enforced.
audit chain + ledgerApply, unchanged. governance_outcome, deciding_gate, the hash-chained audit hop, tokens, latency, credential_class, cost_basis.Every action is auditable (Core Tenet 2).

A1.7 What this is NOT​

  • Not a fifth gateway credential for agents. No agent — platform or external — can hold an X-UpsQuad-Subscriber credential; registrations are minted only to human members, and the admission constructs an identity with no AgentID.
  • Not a path for API keys. sk-ant-api…, uq_key_* and any bearer that is not sk-ant-oat01… fail shape(R) and are refused on this route; the existing API-key admission is reached only without the identity header and still forwards nothing of the caller's.
  • Not pooling. One subscriber, one bearer, one request, one upstream call; no shared account, no shared bearer, no org-side credential of any kind on the wire.
  • Not a change to the MCP instance. Decision 4's ban is intact for every MCP upstream and for every LLM upstream other than the one platform-managed row described in A1.6 step 5.
  • Not a Claude.ai login. Sign-in happens in the unmodified Claude Code binary on the developer's machine; UpsQuad never sees the flow, never sees a refresh token, and never mints or exchanges anything with Anthropic on the developer's behalf.

A1.8 Consequences and risks​

Positive

  • Governed Claude Code traffic (identity, audit, content guardrails, model allowlist, token caps, per-member visibility) with no key entry by the developer and no org-side provider cost — the founder's stated goal.
  • The carve-out and the ban share one switch (A1.3 S-SCHEME), one header-strip list, one gate chain and one ledger. Nothing is duplicated to make the exception possible.

Risks, each with its owner

  • Enforcement by fingerprint, without notice (S1; precedent 2026-04-04). Many subscriptions from one egress can resemble pooling on the wire regardless of intent. Mitigations are A1.4 (byte-transparency), A1.7 (no pooling) and the prepared position on #3679. Founder-accepted residual risk; the failure mode is Anthropic returning 401/403 to our members, which A1.2 relays unchanged — the gateway must never mask it.
  • The identity header is a new platform credential surface. It is a secret, not a username: whoever holds it can route their own subscription traffic as the member, which misattributes audit and content-policy decisions (not cost — the holder pays with their own subscription). Named obligations: rotation (one active credential per member; rotate = mint-then-revoke, both audited), revocation (immediate; subscriber(R) reads the row per request, not a cached verdict), scope (org + unit; no cross-org verify under RLS; no scope to any other admission), expiry (mandatory), and the TOFU window on account_ref — the first request binds the Claude account, so a stolen credential used before its owner's first request binds the thief's account; mitigation is the bind audit event delivered to the member, and a Manager-visible "bound to account … on …" line.
  • Dollar budgets are bypassed by construction (A1.6). A team whose org-metered spend is capped can still generate subscription traffic through the gateway, bounded by token caps (7d, including the new per-subscriber grain) and by Anthropic's own subscription limits, not by any org dollar figure. The PRD delta must say this to tenants in terms.
  • A new admission is a new attack surface at step 3. It is reached by a header, so every refusal arm is reachable by an unauthenticated caller; S-LOG and the rate limit at step 4 are what bound it.
  • metadata.user_id is client-supplied and unsigned (S3). account(R) binds and compares it to detect a changed account, not to prove one — a client can lie consistently. The verified identity is X-UpsQuad-Subscriber; the account segment is a consistency check and an audit fact, and the design must not describe it as more.

A1.9 Status and process​

  • Accepted. The gate this bullet set — a founder approved comment on the PR that adds this amendment (new authentication primitive — CLAUDE.md "Wait for human approval") — was passed on PR #3689, comment 5946673789, 2026-10-02T06:22:52Z (user.type == "User", performed_via_github_app == null, unedited). A1.2–A1.6 are now implemented through LLD #3698's tasks (tracker #3690, milestone 39).
  • Product record: the PRD #2644 delta (Product Manager, in parallel) — the fifth sourcing mode, per-person grain, tenant-facing wording of A1.5 and A1.8. The two documents cite each other by PR number; a conflict between them is resolved in favour of whichever is narrower, and the other is amended.
  • Still required before build, carried from #3679 item 3 and narrowed by prior evidence: the August inspection-gateway PoC (docs/architecture/gwpoc-inspection-gateway.md) already ran an unmodified Claude Code through a pass-through proxy on a subscription login (its graduation gate 3 is this very ToS question), carried identity on ANTHROPIC_CUSTOM_HEADERS (§3 step 1), and parsed metadata.user_id into account/device/session (§7, identity.go). So the end-to-end is demonstrated, not hypothetical. What the spike still owes is (i) the same on the current CLI build with the header spelled X-UpsQuad-Subscriber, and (ii) the measured (method, path) list surface(R) needs — the PoC's ledger already shows shapes beyond POST /v1/messages (a HEAD /api/hello probe and a hidden title-generation call, §4 step 2), and each must be either allowlisted with its justification or shown to be refusable without breaking the client.
  • One PoC practice is explicitly NOT carried forward: the PoC persisted sha256(bearer)[:12] as a key fingerprint (§7). A1.3 S-PERSIST forbids any derivative of the bearer at rest — hash, prefix or length — for the reason endpointcredential/secret.go gives for its redaction marker: a derivative leaks the one fact an attacker with a candidate wants. Attribution comes from X-UpsQuad-Subscriber, never from the bearer.
  • Implementation: one LLD under HLD #2649, tasked per A1.3's rows (each New row is a task with its mutant named in the acceptance criteria) plus the A1.5 migrations and consumer changes, reviewed under the WR2 failure-class checks with S-HOST and S-SCHEME treated as security-critical.