Skip to main content

KT — Governed MCP & the Team Gateway

Audience: a new engineer joining the MCP / gateway effort, and anyone who has to hand a customer the steps to register an MCP server or connect an agent. Goal: understand the whole system end‑to‑end, know what is real vs stubbed vs parked, be able to onboard an MCP server under each auth mode we support, and be able to hand external‑agent operators the exact steps to connect and authenticate.

Status legend used throughout: 🟢 LIVE (merged, in the prod code path) · 🟡 STUBBED (placeholder, works but not final) · 🔵 DEV‑ONLY (only wired for beta‑dev/docker) · 🟠 PENDING/PARKED (designed and/or coded but gated off / blocked) · ⛔ NOT SUPPORTED (no code; listed so nobody goes looking).

Changelog since f868237bd (2026‑10‑30)​

Re‑verified against main @ 7ba02dcd3 (2026‑11‑14) and GitHub for milestone #41 (tracker #4206). Every file:line below is read from that tree. Section 7 is unchanged. Docs‑only pass: nothing was re‑run on beta‑dev, so the 15/15 proof below is still the f868237bd run.

  • Authenticated discovery (§1 step 5, §4.5; #4507, 2026‑11‑21). The design ruling is #4507 comment 7060237384. Line references are at the PR head, and nothing was re‑run on beta‑dev.
    • Session initialize. Each member's initialize now carries the Hop‑B credential tools/call would send. The gateway mints it with AuthorizeAggregatedWithClaims on the request's own proof, against the aggregate's unit (aggregated.go:456‑470). The order per request is: the edge's list filter (visibleMembers, aggregated.go:477‑494), then the mint, then the initialize. A member the edge hides is left out silently, with no vault read and no audit row (#4310). If every member is hidden, the session is still issued, with no members (aggregated.go:243). The initialize dials the grant's effective endpoint and never reads the client's request, so the passthrough ban holds by construction (group_session.go:217‑252). type=none still sends no Authorization. If a configured credential cannot be minted, the member is left out with the new reason upstream_credential_unavailable (group_session.go:66), and that member is never dialled.
    • Registration capture. The registration probe, the URL‑change re‑probe and the post‑approval re‑probe now send the credential when the registry can derive one without an agent. tokenexchange.MintForDiscovery decides, and the table is in its file comment (discovery.go:74‑99): bearer reads the probing unit's slot, then org _default; oauth2 client_credentials makes one token POST. Two cases are not_derivable and send no header. token_exchange is refused before any POST (discovery.go:82). A binding with require_per_agent is refused before any vault read (discovery.go:91). A configured credential whose mint fails means the probe is not attempted: health_status=unreachable, and last_error carries only the class, never the mint error text (discovery_credential.go:183‑228). When a probe that sent no header gets a 401 or 403, last_error says why no credential was sent. The mint shares the probe's 8 s deadline (service.go:424‑445). It runs through the gateway's own Exchanger and egress client (main.go:2319,3308). The post‑approval re‑probe resolves at the approved binding's unit (service.go:1561). The URL‑change re‑probe resolves at the server's owning unit (service.go:1405).
    • Vault refs bound to the server (review of PR #4650). RegisterMCPServer refuses any bag that carries a token_vault_ref or client_secret_vault_ref, in any key case. The refusal decodes the bag the way the reader does (encoding/json struct matching is case‑insensitive), and also scans every key with strings.EqualFold, so it is never narrower than the reader: a legitimate ref names the server id, which does not exist until the insert, and the capture mints from that bag. Every capture dereferences a ref only when its provider is credentialscope.MCPCredentialProvider(<type>, <this server id>), the spelling SetMCPServerCredential writes. Any other ref is never read and the probe goes out with no header. #4700 tracks the same binding on UpdateMCPServer for the stored‑bag tools/call path, a gap that predates this change.
    • Redirects. The prober and the initializer now refuse redirects whatever client they are given (probe.go:99, group_session.go:171). The re‑prober also invalidates the exchanger's allow‑list cache (mcp_reprobe.go:99).
    • Cost and follow‑ups. The Exchanger has no token cache, so a session open costs one token POST per visible oauth2 member. On the oauth2 fixtures, a team of four oauth2 members took 4 POSTs per session open and 5 with one tools/call. The agent runtime opens a session before every tool call, so this multiplies; #4649 tracks fixing it. #4648 tracks re‑probing when a credential or auth mode changes after approval. cmd/tools/first-party-seed still probes with no headers: first‑party servers serve open discovery.
  • The handout is a user manual now (§4.5; #4521). Sections 1–8 of the MCP server owner handout moved to docs/manuals/mcp-server-owner-integration.md, the first page of the new docs/manuals/ section (pages handed to platform users as-is, rendered under the site's /manuals/ route, and checked by the docs-site build for self-containment). The evidence appendix stays in docs/runbooks/mcp-server-owner-integration.md, now its internal companion, so there is nothing to cut before sending. The handout text moved unchanged except its opening: the "Not for:" line no longer links into this doc, and the sentence about the same-page appendix is gone. Docs-only; nothing in this doc was re-verified.
  • Handout for the MCP server owner (§4.5, §9; #4503). New runbook docs/runbooks/mcp-server-owner-integration.md, whose sections 1–8 are sent to a vendor (the evidence appendix stays internal): the wire traffic their server receives, what to hand over per mode, network, error contract, worked examples from the beta‑dev fixtures, and a two‑sided checklist. Its evidence appendix is read from main @ 0d3cf9fad (2026‑11‑15); the rest of this doc was not re‑verified. A code fact it records that this doc does not state: the gateway's session path never sends the upstream a notifications/initialized (only the registration probe does) or a DELETE. It also recorded that the upstream credential rode on tools/call only, so the probe and the session initialize carried no Authorization. That stopped being true with #4507; see the entry above.
  • Both aggregated routes authenticate first, on every verb, and each tools/call runs the gate once (§1, §3, §5, §8). PR #4475 merged 2026‑11‑14 19:46Z as 7ba02dcd3 and closed #4289. It implements the architect's LLD (#4289, comment 6422172881):
    • Auth‑first. /mcp/team/{unit} and /mcp/group/{id} now share one request order, aggregatedEndpoint.serve (aggregated.go:135‑161): path id → gate → DELETE → resolve (502/404/403/409) → POST → 405 + Allow: POST, DELETE. An anonymous caller gets the same 401 challenge for an unknown, an approved and an empty unit, with no database read. Before, a GET on the group route resolved the group first, and a valid token on GET got a 401 instead of 405.
    • One gate per call. Terminator.AuthenticateAggregate returns an oauth.GatedClaims proof (terminator.go:179‑217). The mint, AuthorizeAggregatedWithClaims, runs on that proof, re‑verifies nothing, and refuses a zero‑value proof (terminator.go:236‑244; called at dispatch.go:361). AuthorizeAggregated and AuthenticateAggregateClaims are removed; git grep finds no production caller of either.
    • Edge probe. scripts/edge/probe-edge-vhosts.py now declares the anonymous team answer as 401 with a WWW-Authenticate pin, not 404. infra/edge/envoy.yaml is unchanged; its mcp_team comment is stale on purpose (infra/edge/README.md says why).
    • #4288 was already closed by PR #4361. Three review follow‑ups are open, none prod-enablement: #4476 (the team source catalog still re‑validates the bearer), #4477 (JWKS validator accepts a token with no exp) and #4478 (EndSession deletes by session id alone).
  • The gateway serves a team without its dead members (§1, §5, §6, §8). Before, the initialize fan‑out was all‑or‑nothing: one unreachable member made every session a 502. Now a member that cannot be opened is left out of the session. A WARN line gives a bounded reason and one mcp_member_initialize_failed row records it. The row type is new in migration 286, and cmd/context-engine/main.go:2151 wires the gateway's Config.Audit to the durable audit writer. Only "no member reachable" is a 502. tools/list on that session omits the left‑out member's tools (group_session.go:230, aggregated.go:257,277; #4308, PR #4361 00e1ebc35). Two follow‑ups are open: the portal matrix still shows the member allowed (#4349), and the fan‑out is still sequential.
  • Edge gates decide before the mint (§1, §2, §8). The clearance floor, the allowlist and the CEL policies now run on the gated caller before the mint resolves the upstream credential (dispatch.go:292,312,331 before :361; #4310). The mint was AuthorizeAggregated then; since #4289 it is AuthorizeAggregatedWithClaims. A refused call no longer reads the vault and no longer writes oauth_upstream_token_issued. The step numbers change: the mint is now step 3.6, after 3.3–3.5, where it used to be 3.2. One #4310 ask is still open: tools/list filtered by the caller's verdict (#4348).
  • Truthful bearer audit reason (§1, §3, §6). A bearer server with nothing stored for the calling grain now audits oauth_upstream_token_denied with reason no_stored_credential instead of token_exchange_failed. The 403 is unchanged (terminator.go:52,400‑402, tokenexchange/exchanger.go:215‑239, config.go:104; #4311). The #4287 review survivors are pinned by tests (#4288).
  • The team route authenticates before it resolves the unit (§1, §3, §5, §8). PR #4405 (2026‑11‑06, a repository‑source PR) gated every team request before ResolveGroup, and reads membership under the authenticated org (pg_team_resolver.go:63‑66). That removed the old #4289 residual, an anonymous 404 for an unknown unit, on /mcp/team. The rest of #4289 (the group route, 405 for other verbs, one gate per tools/call) landed with PR #4475; see the first entry.
  • oauth2 bag writes validated (§3, §4.3, §8). Every write goes through one gate, ValidateOAuthBag (internal/mcpserver/oauth2_settings.go:143): structured settings, a raw oauth_config_json, or a mode switch. A mode‑only switch to oauth2 is refused unless the resulting bag is complete (PR #4356 cb6c7792, 2026‑11‑12). The founder deleted beta‑dev's never‑mintable test auth row the same day, and #4217 is closed.
  • mcp-credential-helper -check (§5, §8). A one‑shot self‑test: one mint, one tools/list, exit 0/1/2. The token is never printed (cmd/mcp-credential-helper/check.go, README "Self‑test: -check"; #4215, PR #4351). The same PR pinned the egress‑observer wiring (#4240) and the standup strays rule (#4292).
  • External‑agent credential UX (§2, §8). GetExternalAgentCredential returns credential metadata and never the secret material (PR #4360). The client panel reads it for status, last use, and rotate/revoke (client#962), and the config block shows the real issuer origin (client#961). #1958 is closed. Two gaps found along the way are open: #4338 (no audit row on DeregisterMCPServer / RevokeExternalAgentCredential) and #4350 (DeleteAgent leaves an external agent's credentials active).
  • Smoke and fixtures (§9). Smoke‑harness hardening is done (#4321, PR #4367): a whitespace roster is refused, the battery has a timeout budget, and key custody is measured by the signer. test/harness/betadev-fake-as/register-fixtures.sh registers the oauth2 fixtures through the product's RPCs; it is a dry run by default (PR #4352). The 15‑case roster and its exit codes are unchanged.
  • Adjacent, not part of this gateway: the external /mcp/platform contract (golden tools/list, plus the dev fixture cmd/platform-mcp-fixture) is pinned but not served (PR #4433, #4425 open, milestone #42). Repository‑source tools can join the team gateway's catalog behind REPO_MAP_SOURCE_TOOLS_ENABLED, which is off when unset (source_catalog.go, internal/auth/mcpboot/config.go:20,41‑43; PR #4405).
  • No status downgrades. Every change in this pass is an upgrade (open → closed) or a new open follow‑up (#4348, #4349, #4338, #4350).

Changelog since bdcae576c (2026‑10‑19)​

Re‑verified against main @ f868237bd (2026‑10‑30) and GitHub for milestone #41, Governed MCP — beta‑dev end‑to‑end (OAuth proof) (tracker #4206). Section 7 is unchanged. Every other section carries one or more of the edits below.

  • Public issuer live on beta‑dev (§2, §3, §5, §8). https://auth-beta.upsquad.ai resolves and is the issuer: the RFC 8414 metadata names it as issuer, token_endpoint and jwks_uri (#4210, closed 2026‑10‑22). In compose, MCP_GATEWAY_PUBLIC_BASE_URL derives from PLATFORM_ISSUER (PR #4236). So every beta‑dev token now carries iss=https://auth-beta.upsquad.ai and aud=https://auth-beta.upsquad.ai/mcp/team/{unit}. Previously 🟠 "DNS does not resolve".

  • Team gateway public on the same hostname (§1, §2, §3, §5). The platform-issuer edge vhost routes /mcp/team/* and its RFC 9728 metadata /.well-known/oauth-protected-resource/mcp/team/*, with their own rate bucket. Every other path is sealed with a 404 (#4273 decision; PR #4290 merged as c6b29f5c; the founder applied it 2026‑10‑26). refund-mcp.app.upsquad.ai is sealed at the edge (PR #4254; #4241 closed 2026‑10‑23).

  • Bearer on every method, spec initialize (§1, §3, §5). The team, group and platform routes now authenticate before reading the body. That covers initialize, tools/list, tools/call, notifications and DELETE (#4270). initialize answers a JSON‑RPC result plus Mcp-Session-Id, a notification gets 202, and only initialize fans out (#4271). Both fixes are PR #4287 (76da9d6c). Residual at f868237bd: an unknown unit still answered 404 before authentication (#4289). That is gone on the team route since PR #4405, and on both routes for every verb since PR #4475; see the newer entries.

  • Signing key rotated, custody fixed (§3, §9). The key is 0600, owned by uid 65532, in a 2700 65532:65532 directory. The kid is dev-platform-20261023-094112 (#4237, closed 2026‑10‑23). The generator refuses a key that is not private (PR #4244). The smokes now sign as the service uid inside a throwaway docker run (PR #4318, 3a943243). PR #4331 (merged 2026‑10‑30 as f868237bd; #4283 closed) does the same for the trust‑root [2b] stage: a static go test -c binary runs in context‑engine's own image and network namespace, as uid 65532, with the key directory mounted read‑only.

  • Edge deny audit rows land once (§1, §6, §8). An edge deny row used to write the Mcp-Session-Id into agent_audit_log.session_id, which is an FK to agent_sessions. The row was dropped with 23503, and a whole‑batch retry stored its siblings 4× (#4307). PR #4328 (cb215be9) fixes both. EdgeToolCall.MCPSessionID goes into the row's detail as mcp_session_id, session_id stays NULL, and the writer retries only the entries that did not commit. Follow‑ups #4329 and #4330 are open.

  • oauth2 configurable without hand‑written JSON (§3, §4.3, §8). RegisterMCPServer / UpdateMCPServer accept structured oauth2_settings (PR #4216, FR‑CR.9), and the client SPA exposes those fields (client#945). This closes the old §8 blocker "portal cannot configure oauth2". Residual then: #4217, closed since by PR #4356.

  • First‑party dev stack fixed (§2, §4.4, §8). Compose derives the memory/knowledge TOKEN_AUDIENCE from the public base URL. scripts/dev-seed-first-party-mcp.sh seeds mcp_builtin_registrations (#4204 closed; PRs #4236 and #4242). Both §8 dev defects are closed.

  • Beta‑dev proof (§2, §4, §8, §9). scripts/smoke-mcp-oauth-betadev.sh is the 15‑case exit gate (PR #4280, fixed by PR #4318). Its fixtures:

    • betadev-refund-mcp, bearer (#4207).
    • betadev-fake-as plus betadev-refund-oauth2-mcp, with servers betadev-refund-oauth2-cc / -tx (#4209, PR #4312).
    • betadev-smoke-mcp, with betadev-smoke-none / betadev-smoke-rpa, an escalate policy and a low‑clearance agent (#4272, PR #4305).

    Exit criterion met: the full run on main f868237bd (2026‑10‑30 20:53Z) exited 0 with 15/15 VERIFIED, 0 FAILED, 0 COULD‑NOT‑CHECK. Issuer https://auth-beta.upsquad.ai, kid dev-platform-20261023-094112. All five Hop‑B modes (none, bearer, oauth2 client_credentials, oauth2 token_exchange, first‑party) and all seven negatives passed (#4214 closed). The last two red cases went green with #4328 (neg-32602) and #4331 (hop-b-bearer). context‑engine ran image cb215be9; no service code changed between it and f868237bd.

  • mcp-credential-helper proven live (§2, §5). Claude Code with the helper ran tools/call through https://auth-beta.upsquad.ai. Both client‑auth methods passed in‑network and through the public edge (#4211, closed 2026‑10‑26). Codex was not exercised.

  • Portal E2E (§8). Both legs passed through the client SPA and the public team gateway: bearer on 2026‑10‑26, none on 2026‑10‑29 against betadev-smoke-none (#4213 closed). The negative case's mcp_clearance_floor_denied row now lands exactly once. The runs filed #4307–#4311: four gateway/audit bugs and one client‑portal bug. #4309 (the client‑portal bug) is fixed by client#960. #4308, #4310 and #4311 were open at f868237bd; all three landed in PR #4361 (see the newer entry).

  • Dev deploy is a reconciler (§9). The Deploy Dev Stack workflow replaces the hand‑run docker compose … --force-recreate line.

  • No status downgrades against the previous version's claims about the present. One retroactive correction: the edge deny audit rows that §1 step 3.3 described were being dropped for every caller until PR #4328 (2026‑10‑28). Prod gaps stay on milestone #40, and #1864 is not on #41.

Changelog since the 2026‑07 version (#2028/#2029 era)​

Re‑verified against main @ bdcae576c (2026‑10‑19). Sections 1, 6 and 7 are unchanged apart from the additions listed here.

  • Hop‑B oauth2 now has two grants (§3): token_exchange (RFC 8693, the default, unchanged) and client_credentials (RFC 6749 §4.4) selected by grant_type in the server's oauth config (#1737, internal/auth/tokenexchange/config.go). The previous version listed exchange only.
  • Explicit "not supported" list for Hop‑B (§3): authorization‑code / refresh, API‑key header, HTTP basic, mTLS, XAA / ID‑JAG. Previously implied by omission.
  • Per‑mode onboarding steps (§4): the single checklist is now "common steps" plus one subsection each for none, bearer, oauth2, and first‑party servers.
  • mcp-credential-helper (§5, #2994, 2026‑09‑05): the supported way for Claude Code / Codex to reach /mcp/team/{unit}. The hand‑minted POST /oauth/token flow is kept as the wire contract the helper implements.
  • First‑party MCP servers (§3, §4.4, §8): upsquad-memory-mcp / upsquad-knowledge-mcp reached through the gateway with a platform‑minted delegation bearer (FirstPartyMinter, #4172, merged 2026‑10‑17). Two dev‑stack defects recorded in §8.
  • Public issuer hostname (§3, §5): founder ruling 2026‑10‑02 = https://auth-beta.upsquad.ai (Access‑free, three paths only). DNS does not resolve as of 2026‑10‑19; the internal issuer remains http://context-engine:8080.
  • Status corrections (§2, §8): #1764 (CEL at the edge for BYO callers) is closed and live; the "identity rung" badge is documented as a Hop‑B descriptor (gateway_identity / shared_token / anonymous), not an inbound‑identity rung.
  • Operational caveats added (§3): no Hop‑B token cache (an oauth2 mint happens per call); no upstream authorization‑server discovery (token_endpoint is hand‑entered and must be https).
  • Corrections from the architect pass (2026‑10‑19): the egress enforcement_phase column is read by no code (the guard always enforces); the portal cannot configure oauth2 beyond the mode; gateway egress denials emit no audit. All three in §8.
  • Still true, re‑checked: #1864 OPEN (prod-enablement), MCP_GATEWAY_ENABLED default false, beta‑dev JWKS live (kid dev-platform-20260719), /oauth/token advertises client_credentials only.

0. TL;DR — the mental model​

  • An agent never talks to a customer's MCP server directly. It talks to our team gateway at /mcp/team/{unit}, which is the single Policy Enforcement Point (PEP) for every MCP tool call.
  • There are two authentication hops, and keeping them straight is the whole game:
    • Hop‑A — agent → our gateway ("prove who you are to us"). A short‑lived RS256 JWT, either platform‑minted (agents running inside our platform) or obtained via POST /oauth/token (agents running outside our platform, pre‑registered as external agents). A developer's Claude Code or Codex is an external agent; mcp-credential-helper does the token loop for it.
    • Hop‑B — our gateway → the upstream MCP server ("we authenticate to the tool on your behalf"). One of none / bearer / oauth2 (grant token_exchange or client_credentials), using credentials we hold in a vault — or, for our own first‑party servers, a platform‑minted delegation bearer. The agent's inbound token is never forwarded upstream (passthrough ban).
  • Between the PEP and the upstream there is a network egress guard (SSRF defence): private IPs are denied by default and only reachable through an explicit, approval‑scoped allowlist row.
  • Governance (clearance floor, per‑agent allowlist, HITL approval, tiered guardrails, manager subtree‑withhold) is enforced at the edge, in order, before anything leaves our process. This is ADR‑0024.
  • Where it runs today: beta‑dev only. There the whole chain is proven by scripts/smoke-mcp-oauth-betadev.sh: the public issuer and team gateway at https://auth-beta.upsquad.ai, every Hop‑B mode, and the governance negatives. It exited 0 with 15/15 cases VERIFIED on main f868237bd (2026‑10‑30). No later run is recorded on #4206. Since then the gateway tolerates a dead team member and runs every edge gate before the upstream mint (PR #4361). It also authenticates every verb before it resolves the unit and gates each tools/call once (PR #4475). Production stays parked on #1864 and the other milestone #40 gates.

1. Architecture & control flow (numbered, colored)​

Colour key: 🔵 blue = agent runtime · 🟡 amber = auth/trust · 🟢 green = gateway PEP · 🔴 red = egress/SSRF · 🟣 purple = upstream MCP (customer or first‑party) · ⚪ grey = data stores. The public‑edge node is amber because it is a trust surface. It decides which paths exist on auth-beta.upsquad.ai, not who may call them.

Walkthrough (numbers match the diagram)​

  1. (External agents only) The operator registers the agent once, then exchanges client_credentials at POST /oauth/token to get a short‑lived JWT identical to what an internal agent would carry. Internal agents skip this. For Claude Code / Codex the mcp-credential-helper binary performs this step on every refresh (§5). On beta‑dev an off‑platform agent reaches both the token endpoint and the team gateway through the public edge at https://auth-beta.upsquad.ai (infra/edge/envoy.yaml, vhost platform-issuer). The edge serves only the three issuer paths, /mcp/team/* and its RFC 9728 metadata, and seals everything else with a 404 (#4210, #4290).
  2. Session freeze. When a session starts, the Session Initializer (internal/runtime/session/initializer.go) resolves the agent's effective config through the Org‑v2.4 multi‑parent resolver.
    • 1a. D6 clearance‑floor drop: any MCP server whose min_clearance exceeds the agent's clearance is removed from the snapshot (dropMCPBelowClearanceFloor → filterMCPByClearanceFloor). Surviving tools are frozen as mcp:<serverID> and exposed to the model as {server}__{tool}.
  3. Hop‑A mint. On each ExecuteStep, the orchestrator mints a ~10‑minute RS256 JWT (RS256AgentTokenMinter.Mint, internal/auth/oauth/agent_token.go) — but only if the snapshot actually contains MCP servers and the tenant is enabled. Claims: aud=<base>/mcp/team/{unit}, azp=agent-runtime, org_id, agent_id, unit_id. The Python worker receives it as ExecuteStepRequest.agent_gateway_token and presents it as Authorization: Bearer (services/agent-worker/src/agent_worker/mcp/client.py); it mints nothing itself.
    • 2b. The agent opens the MCP session (initialize → JSON‑RPC result + Mcp-Session-Id), then calls tools/list / tools/call on the gateway. It carries that JWT as Authorization: Bearer on every request (#4270/#4271).
  4. Edge PEP — enforced in this exact order (internal/gateway/mcpproxy/{team,group}.go → aggregated.go serve → dispatch.go, gates in edge_policy.go). All gates fail closed. Both aggregated routes run one request order, aggregatedEndpoint.serve (aggregated.go:135‑161; #4289, PR #4475): path id → gate → DELETE → resolve → POST → 405.
    • 3.1 OAuth gate first, on every verb, before the unit is resolved. A path with no id is a 404 before anything else (team.go:91‑95, group.go:372‑376). Then Terminator.AuthenticateAggregate (aggregated.go:170‑182, terminator.go:210‑217) validates the JWT signature against JWKS and checks tenant, aud and confused‑deputy consent (Terminator.gate, terminator.go:268). A missing bearer, a bad bearer or another resource's aud gets 401 + the RFC 9728 challenge; a consent miss gets 403 (#4270, PR #4287). The gate mints nothing.
      • An anonymous caller therefore gets the same 401 challenge for an unknown, an approved and an empty unit, on /mcp/team/{unit} and /mcp/group/{id} alike. It learns only that the path wants a token, and costs at most one in‑memory signature verify and no database read.
      • The gate returns a proof, oauth.GatedClaims (terminator.go:179‑191). Its fields are unexported, so only AuthenticateAggregate can build a non‑zero value. Every later step binds the caller (org, agent) it carries. serve stamps the verified org into the request context (aggregated.go:140‑142), so the team membership read runs under the authenticated org (pg_team_resolver.go:63‑66; PR #4405).
      • DELETE comes next and needs no membership: it ends the session mapping and answers 204 (aggregated.go:143‑146,189‑197). It does not gate again. It deletes by session id alone, without a tenant check (#4478, open).
      • Only then is the unit resolved (aggregated.go:147‑150; the closures at team.go:105‑128, group.go:385‑416), and only an authenticated caller sees its answers: resolver error → 502; unknown unit/group → 404; no eligible (team) or approved (group) member → 403; on the group route an ineligible member transport → 403 and colliding raw tool names → 409.
      • POST is then served (aggregated.go:151‑154). Any other verb gets 405 + Allow: POST, DELETE (aggregated.go:155‑159). Before #4289 a valid token on GET got a 401 challenge instead, and a GET on the group route resolved the group before any token check.
      • Then the JSON‑RPC method is served (servePost, aggregated.go:206‑248). It does not gate again. The team route's repository‑source catalog is the one exception: it still re‑reads the bearer itself (aggregated.go:207‑209), as a catalog filter, not as the request's gate (#4476, open).
        • initialize fans out one upstream session per eligible member. A member that cannot be opened is left out of the session (#4308, PR #4361). One WARN line names it with a bounded reason (egress_denied / upstream_status / no_upstream_session / invalid_target / unreachable), and one mcp_member_initialize_failed audit row records it (group_session.go:56‑60,230; aggregated.go:277‑315). Only "no member reachable" gets 502 session initialize failed (aggregated.go:224); otherwise the answer is a JSON‑RPC result + Mcp-Session-Id;
        • tools/list answers the aggregate. A request carrying this aggregate's Mcp-Session-Id sees only the members that session reached (sessionSurface, aggregated.go:238,257). A sessionless list (the worker lists before it initializes) still shows the full derived surface. No list is narrowed by the caller's governance verdict yet (#4348);
        • a notification gets 202;
        • tools/call continues at 3.2.
    • 3.2 Reverse‑route {server}__{tool}; unknown → -32602 (never a misroute; dispatch.go:236‑240). The gates below bind the caller from the 3.1 proof for this request (dispatch.go:208, gated oauth.GatedClaims; caller := gated.Claims(), dispatch.go:258), not a re‑read token.
    • 3.3 EdgeClearanceFloor (D6) — coarsest gate; deny → -32602 + mcp_clearance_floor_denied audit (dispatch.go:292). The row keeps the transport session in its detail as mcp_session_id and leaves session_id NULL, so it lands exactly once (#4307, PR #4328).
    • 3.4 EdgeAgentAllowlist (#1744) — server not in the agent's creation‑time allowlist → deny (dispatch.go:312).
    • 3.5 EdgeToolPolicy (D3, tiered CEL guardrails) — tri‑state: allow / deny (-32602) / requires‑approval (-32001 + a governance_approvals row — a HITL pause, never a silent deny) (dispatch.go:331). Applies to internal and external callers alike (#1764, closed).
    • 3.6 Only when 3.3–3.5 all allow: resolve/mint the upstream credential for Hop‑B (Terminator.AuthorizeAggregatedWithClaims on the 3.1 proof, dispatch.go:361; #4310 PR #4361, #4289 PR #4475). A refused call never reads the vault and writes no oauth_upstream_token_* row. Before #4310 the mint ran before the gates, so a refused call had already read the vault and written oauth_upstream_token_issued.
      • The mint re‑verifies nothing, so each tools/call runs the gate once: one signature verify and one consent read. It refuses a proof the gate did not produce (the zero value, or an empty bearer, OrgID or resource) with ErrInvalidToken, before the minter or the audit sink (terminator.go:236‑244). AuthorizeAggregated and AuthenticateAggregateClaims are gone; no production code names either.
      • The first‑party branch runs first when the server has a builtin registration. Otherwise the tokenexchange minter handles bearer / oauth2, and none yields no header.
      • require_per_agent bindings fail closed here if no agent‑scoped credential exists.
      • A bearer server with nothing stored for the calling grain gets 403 and audits oauth_upstream_token_denied with reason no_stored_credential. Every other minter failure keeps token_exchange_failed (terminator.go:52,400‑402; #4311).
    • (Manager subtree‑withhold, D4b, is applied earlier at resolution time — a withheld server never even enters the member/upstream set — see pg_group_resolver.go / resolver.go.)
    • 3.7/3.8 Rewrite to the raw upstream tool name and forward through the shared, egress‑guarded upstream proxy.
  5. Egress guard (Hop‑B network layer) (internal/mcp/egress). The upstream HTTP client always‑denies RFC1918/ULA private IPs and the never‑overridable SSRF sinks (metadata 169.254/16, loopback, link‑local, 0.0.0.0/8). Private upstreams — including our own first‑party servers — are reachable only via an approval‑scoped tenant_egress_allowlist row (allow_private=true + pinned_cidr). The connect‑time IP is re‑validated at DialContext to defeat DNS‑rebind. Host patterns must be dotted FQDNs (a bare docker service name is rejected by design).
  6. Upstream call. The session initialize goes to every member the edge lets the caller see. Each one carries the Hop‑B credential minted for that member on the caller's own token, or no Authorization at all for type=none (#4507). The gateway captures each member's Mcp-Session-Id. Each tools/call mints again and is forwarded with the member's session id and the Hop‑B credential. A member whose configured credential cannot be minted is left out of the session, with reason upstream_credential_unavailable. A first‑party server validates the delegation bearer against the platform JWKS (internal/auth/mcpidentity) and scopes every query to the signed org_id/agent_id. Result flows back to the agent.

2. Component catalog & status​

ComponentPathStatusNotes
Session Initializer + D6 snapshot dropinternal/runtime/session/initializer.go🟢 LIVEmcp:<serverID> freeze; #1744 narrow; #2027/#2028 cache‑poisoning fixed
Org‑v2.4 multi‑parent resolver + cacheinternal/orgunit/resolver.go🟢 LIVEclone‑on‑get/put (#2028), invalidation (#2024), 45s TTL (#2026)
Hop‑A RS256 minterinternal/auth/oauth/agent_token.go🟢 LIVE (code)~10m TTL; prod blocked by #1864 (no prod key)
JWKS / issuer routesinternal/auth/oauth/issuer_routes.go (on context‑engine)🟢 LIVE (code)nil key → mounts nothing (fail‑safe); advertises client_credentials only
/oauth/token (external agents)internal/auth/oauth/token_endpoint.go🟢 LIVE (code)client_credentials; private_key_jwt or client_secret_post; parked for prod (#1864)
Public issuer hostname auth-beta.upsquad.aiinfra/edge/envoy.yaml vhost platform-issuer + Cloudflare tunnel🔵 LIVE on beta‑devissuer since 2026‑10‑22 (#4210); /mcp/team/* + its RFC 9728 metadata since 2026‑10‑26 (#4273, PR #4290); any other path → 404 issuer_path_not_published
RegisterExternalAgent / Rotate… / Revoke… / GetExternalAgentCredential + trust tableinternal/agent/external_service.go, external_agent_clients (mig 155)🟢 LIVE (code)DB trust‑table, not per‑runtime JWKS; metadata read without secret material (PR #4360); portal panel external-credential-panel.jsx on it (client#962)
mcp-credential-helper (stdio → streamable‑HTTP bridge)cmd/mcp-credential-helper/ (#2994)🟢 LIVEholds the long‑lived client credential, refreshes the 10‑min bearer; stdlib + go‑jose only; proven with Claude Code through the public edge (#4211); -check self‑test (#4215, PR #4351)
Team gateway edge dispatch (PEP)internal/gateway/mcpproxy/{aggregated,dispatch}.go🟢 LIVEbearer on every method, spec initialize (#4287); both routes gate before resolving the unit, on every verb, 405 for any verb but POST/DELETE, one gate per tools/call (#4289, PR #4475); a dead member is left out of the session, not fatal (#4308); ordered gates, all fail‑closed, all before the upstream mint (#4310, PR #4361)
EdgeClearanceFloor / AgentAllowlist / ToolPolicy CELinternal/gateway/mcpproxy/edge_policy.go🟢 LIVEwired in cmd/context-engine/edge_enforce_wiring.go; CEL applies to BYO callers too (#1764 closed)
Manager subtree‑withholdpg_group_resolver.go, resolver.go🟢 LIVEenforced at every resolution surface (#1992)
Hop‑B upstream minter (bearer / oauth2)internal/auth/tokenexchange/{config,exchanger,scoped_secret}.go🟢 LIVEgrant_type = token_exchange (default) or client_credentials (#1737); no token cache; both grants proven on beta‑dev against the fake AS (#4209); a bearer bag with nothing stored is marked ErrNoStoredCredential (#4311)
Hop‑B first‑party minterinternal/auth/oauth/first_party.go, internal/mcpserver/builtin.go🟢 LIVE (code, #4172)platform‑signed delegation bearer, aud=<base>/mcp/upsquad-{memory,knowledge}; beta‑dev wired and seeded (#4204, PRs #4236/#4242)
First‑party serverscmd/upsquad-memory-mcp, cmd/upsquad-knowledge-mcp, internal/auth/mcpidentity🟢 LIVEvalidate the delegation bearer; fail closed; team‑scoped reads, no clearance predicate (founder 2026‑09‑05)
Egress guard + SSRF floor + rebind re‑validateinternal/mcp/egress/{roundtripper,deny,patterns}.go🟢 LIVEADR‑0025 (#2019/#2020)
Upstream proxy + passthrough baninternal/gateway/mcpproxy/upstream_proxy.go🟢 LIVEinjects Hop‑B cred only; never forwards client token
Idempotency dedupupstream_proxy.go + pg_idempotency.go🟢 LIVEfolded in from ContextForge; fails OPEN (correctness backstop, not a gate)
GovernanceService #288 on the MCP pathinternal/governance🟢 EXITED (D2)the residue default‑deny was removed; the store survives only as the CEL policy store
/mcp/platform built‑in tools (ADR‑0026)internal/platformmcp🟢 LIVEsame JWT, aud=PlatformAudienceURI; no upstream hop; bearer on every method (#4287). The external‑client tool contract is pinned (internal/platformmcp/external_contract.go, golden tools_list.golden.json, PR #4433) but not served yet: 🟠 #4425, milestone #42. cmd/platform-mcp-fixture serves it with canned results and is not built into any image
ContextForge (services/mcp-proxy)—🟠 REMOVEDdeleted in #1909/#1912; idempotency folded into the Go edge
Structured oauth2 settingsinternal/mcpserver/oauth2_settings.go (oauth2_settings on Register/Update)🟢 LIVE (#4216, #4217)the six non‑secret keys; every bag write (settings, raw JSON, mode switch) passes ValidateOAuthBag once before the write (oauth2_settings.go:143, PR #4356); client SPA fields in client#945
Audit writer for edge deny rowsinternal/runtime/audit/{writer,pgstore}.go, mcpproxy.EdgeDenyAuditEntry🟢 LIVE (#4328)retries only the uncommitted entries; transport session in the detail; rows not hash‑chained (#4330); the team/group gateway writes its mcp_member_initialize_failed rows through the same writer (Config.Audit, cmd/context-engine/main.go:2151, #4308)
Beta‑dev proof + fixturesscripts/smoke-mcp-oauth-betadev.sh, test/harness/{betadev-refund-mcp,betadev-fake-as,betadev-smoke-mcp}🔵 DEV‑ONLY15‑case exit gate; 15/15 VERIFIED on main f868237bd, 2026‑10‑30 (#4214 closed); not re‑run since (main is 7ba02dcd3)
Per‑tool full inputSchema passthroughdispatch.go (permissive {"type":"object"})🟡 STUBBEDarg validation deferred to CEL edge + upstream; follow‑up
Repository‑source tools on the team cataloginternal/gateway/mcpproxy/source_catalog.go, wired at cmd/context-engine/main.go:2207🟠 OFF unless REPO_MAP_SOURCE_TOOLS_ENABLEDadds list_repository_paths / find_repository_paths / read_repository_file to an authenticated team request only (PR #4405); out of scope for this doc

3. The two hops in detail (auth mechanisms)​

Hop‑A — agent → our gateway (authenticate to us)​

One signing key, one validator, two ways to obtain the token.

MechanismWho uses itHow it worksStatus
Platform‑mintedagents running inside our platformorchestrator mints the RS256 JWT itself each ExecuteStep; gateway verifies against JWKS and trusts only the signed agent_id claim🟢 code LIVE · 🔵 proven on beta‑dev · 🟠 prod parked (#1864)
External‑agentagents running outside our platform (BYO runtime, or a developer's Claude Code / Codex)operator pre‑registers (RegisterExternalAgent → external_agent_clients row: client_id → org_id/agent_id/unit_id, plus a public JWK or a bcrypt secret), then calls POST /oauth/token grant client_credentials; the endpoint resolves the binding and mints the same JWT stamped runtime=external. mcp-credential-helper automates the loop for CLI tools.🟢 code LIVE · 🔵 proven on beta‑dev · 🟠 prod parked (#1864)
IdP federation / per‑runtime JWKS—customer‑IdP trust for Hop‑A; issuer federation for XAA on Hop‑B🟠 PARKED (#1953)
  • Client‑auth methods for the external path: private_key_jwt (preferred, RFC 7523) or client_secret_post. Exactly one credential per client (DB CHECK).

  • Signing key (beta‑dev):

    • Path: host $PLATFORM_SIGNING_KEY_HOST_DIR/platform-signing-key.pem → container /var/secrets/platform-issuer/platform-signing-key.pem (PLATFORM_SIGNING_KEY_FILE). On the devbox .env sets the host dir to /opt/upsquad/dev-secrets/platform-issuer/; the compose fallback /opt/upsquad-secrets/platform-issuer is not used there.
    • Custody is live (#4237, closed 2026‑10‑23). The key is 0600, owned by uid 65532 (the distroless nonroot user both containers run as), in a 2700 65532:65532 directory, so no devbox account can read it. The generator refuses a key or directory with any group/other bit, and it rotates with a kid bump (PR #4244). The group‑writable parent dirs remain a trusted‑operator boundary; see the issuer runbook.
    • Kid: rotated 2026‑10‑23 to dev-platform-20261023-094112. Read .env's PLATFORM_SIGNING_KEY_ID, because a rotation changes it.
    • Signing as the key owner: anything that has to sign (the smokes, the first‑party seed) runs in a throwaway docker run as that uid, with the key directory mounted read‑only (PR #4318; the trust‑root [2b] stage since PR #4331).
    • Generation: RSA‑2048, by scripts/dev-secrets/gen-platform-signing-key.sh.
    • Issuer and JWKS: the beta‑dev issuer is https://auth-beta.upsquad.ai (.env PLATFORM_ISSUER; compose default http://context-engine:8080). The JWKS is served on the devbox at 127.0.0.1:8083/.well-known/jwks.json and publicly at https://auth-beta.upsquad.ai/.well-known/jwks.json, both with the same single kid.
  • Public issuer hostname: https://auth-beta.upsquad.ai (founder ruling 2026‑10‑02), live on beta‑dev since 2026‑10‑22 (#4210). It is Access‑free and serves exactly:

    • POST /oauth/token, GET /.well-known/oauth-authorization-server and GET /.well-known/jwks.json;
    • since 2026‑10‑26, the team gateway /mcp/team/{unit_id} and its RFC 9728 metadata /.well-known/oauth-protected-resource/mcp/team/{unit_id} (#4273, PR #4290).

    Any other path gets 404 issuer_path_not_published. Three edge rate buckets are each shared by all callers: the mint (30/min), the team gateway (120/min) and the discovery documents (120/min). See infra/edge/envoy.yaml, infra/edge/README.md and docs/runbooks/model-gateway-external-agent-onboarding.md §3.1.

  • Validation: JWKSValidator checks the signature against the cached JWKS, then the terminator checks aud + confused‑deputy consent (consent is per‑team azp=agent-runtime, not per individual agent). A worker cannot forge a peer's agent_id. Since #4287 the same gate runs on every method of the team, group and platform routes, not only on tools/call. Since PR #4475 (#4289) both aggregated routes run it first on every verb, before the unit is resolved (aggregated.go:135‑161), and the team route reads membership under the authenticated org (PR #4405). It runs once per request: the mint takes its GatedClaims proof and re‑verifies nothing (terminator.go:236‑244).

  • #1864 (OPEN, blocker/arch‑concern/prod-enablement): production has no real platform signing key / JWKS and MCP_GATEWAY_ENABLED defaults false. So both Hop‑A paths are exercisable on dev but parked for prod until the platform issuer is provisioned. The "per‑runtime JWKS / BYO‑trust" third option is tracked on #1953 — not implemented; external trust today is the DB trust‑table. #1864 sits on milestone #40 with the other prod gates; it is not part of the beta‑dev milestone #41.

Hop‑B — our gateway → the upstream MCP server (we authenticate to the tool)​

The mode is the type key inside mcp_servers.oauth_config_json (parsed by ParseUpstreamOAuthConfig, internal/auth/tokenexchange/config.go). UpdateMCPServer accepts only none | bearer | oauth2; anything else is treated as no credential.

Upstream typeMeaningWhat we sendStatus
none (or {})anonymous MCP serverno Authorization header (audited oauth_upstream_token_none)🟢 LIVE · 🔵 proven on beta‑dev (hop-b-none, #4272)
bearerstatic shared tokenAuthorization: Bearer <vault token>; nothing stored for the grain → 403 + oauth_upstream_token_denied reason no_stored_credential (#4311)🟢 LIVE · 🔵 proven on beta‑dev (portal E2E #4213; hop-b-bearer, PR #4331)
oauth2 · grant_type: token_exchange (default when absent)gateway identity via RFC 8693 exchangethe agent's inbound JWT goes to the upstream AS as subject_token; the minted token is sent as Bearer. Only works when the upstream AS trusts our issuer/JWKS.🟢 LIVE · 🔵 proven on beta‑dev against the fake AS (#4209)
oauth2 · grant_type: client_credentialstwo‑legged RFC 6749 §4.4client_id + vault client_secret to the upstream token_endpoint; minted token sent as Bearer. The grant most SaaS tools need.🟢 LIVE (#1737) · 🔵 proven on beta‑dev against the fake AS (#4209)
first‑party (builtin registration, not a type)our own upsquad-memory / upsquad-knowledge serversplatform‑signed delegation bearer carrying the caller's org_id/agent_id/unit_id, aud=<base>/mcp/upsquad-memory or …/upsquad-knowledge, TTL capped by the inbound token🟢 LIVE code (#4172) · 🔵 proven on beta‑dev (first-party-memory, #4204)
oauth2 authorization‑code / refresh‑token——⛔ NOT SUPPORTED (unknown grant_type is rejected at parse)
API‑key header, HTTP basic, mTLS——⛔ NOT SUPPORTED (no such type)
XAA / ID‑JAG per‑agent identity upstream (RFC 7523 + 8693 + 9728)the planned top rung—⛔ NOT IMPLEMENTED (#1953 parked). RFC 7523 appears only on the inbound private_key_jwt path.
  • Passthrough ban: the agent's inbound token is never forwarded upstream; an empty upstream credential fails closed to no header, never to the client's cred.
  • oauth2 config fields (oauth_config_json): type, token_endpoint (must be https), client_id, audience and/or resource, scope (optional), grant_type (optional, default token_exchange). The secret itself is never in the bag — client_secret_vault_ref / token_vault_ref are back‑filled by SetMCPServerCredential. Since #4216 the six non‑secret keys can be set through the structured oauth2_settings message on RegisterMCPServer / UpdateMCPServer. Each value is paired with a *_set flag, and a set but empty value removes the key. The settings are merged into the bag, and every other bag key, the vault refs included, is carried over untouched. Since #4217 (PR #4356) every bag write is validated once before any SQL, by ValidateOAuthBag (internal/mcpserver/oauth2_settings.go:143). That covers structured settings, a raw oauth_config_json, and a mode switch. The rules are the gateway reader's own: the required fields, the grant_type enum, an https token endpoint, and a client_secret_vault_ref naming the server's own org. Raw secret material is refused.
  • Two operational caveats: there is no Hop‑B token cache — the terminator mints on every tools/call (Authorize on the single‑server route, AuthorizeAggregatedWithClaims on team/group, dispatch.go:361; #4289, PR #4475), so an oauth2 upstream sees one token‑endpoint POST per tool call, plus one per session open for each such member, because the session initialize mints too (#4507; the runtime opens a session per tool call, #4649); and there is no upstream AS discovery (RFC 9728 is published inbound only at /.well-known/oauth-protected-resource/mcp/...), so token_endpoint is hand‑entered.
  • Credential granularity (answers "are creds per agent?"): creds live in the vault keyed by team_id at three grains (internal/credentialscope/scope.go): org _default, team <unit_id>, agent _agent_<agent_id>. The binding carries credential_mode (team_shared default | per_agent) plus require_per_agent. Resolver precedence (credentialscope/resolve.go, tokenexchange/scoped_secret.go):
    • require_per_agent → agent‑slot only, fail closed if the agent has no cred;
    • per_agent → agent → team → org fallback;
    • team_shared → team → org.
    • So: per‑server/binding by default, optionally per‑team, optionally per‑agent — and per‑agent can be made mandatory (fail‑closed).
  • The "identity rung" badge in the portal (internal/mcpserver/entitlement.go) describes this hop only: gateway_identity (oauth2), shared_token (bearer), anonymous (none). It is not an inbound‑identity rung; there is no "per‑agent" rung value.

Responsibilities per mechanism​

MechanismPlatform / product sideCustomer sideExternal‑agent operator
Hop‑A platform‑mintprovision real signing key + JWKS (#1864); flip MCP_GATEWAY_ENABLED—n/a (internal)
Hop‑A external‑agentsame key/gate; publish the issuer hostname (beta‑dev: done, #4210/#4290); expose RegisterExternalAgent + /oauth/tokenregister the agent, hand out client_id + secret or register the agent's public JWK; rotate/revoke from the agent pagehold client_id + private key/secret; run mcp-credential-helper (CLI tools) or exchange client_credentials yourself every ~10m
Hop‑B bearer / oauth2vault + resolver (live)register the MCP server, set type (+ grant_type), run SetMCPServerCredential, choose credential_mode / require_per_agent, upload per‑agent creds if desiredn/a
Hop‑B none—register server with type=nonen/a
Hop‑B first‑partydeploy the server, set MCP_BUILTIN_*_ENDPOINT, run memory-onboardapprove the binding like any other servern/a

4. Onboarding an MCP server (operator checklist, per auth mode)​

4.0 Common steps — every mode​

Do these in order. Each row is one RPC/UI action and its DB effect.

#StepSurfaceEffect
1Register the server on a unit (team/pillar) — name, URL, auth mode, min_clearance (0–5), visibility, credential_mode, require_per_agentRegisterMCPServer · client SPA mcp-registry.jsx register form 🟢 (oauth2 settings: oauth2_settings, #4216 / client#945)inserts mcp_servers (status=pending) + mcp_server_units (approval_status=pending, binding_kind=grant); a best‑effort registration probe captures tool_schema (blocked by egress until the host is allowlisted — it re‑runs at step 3)
2Lifecycle approval (T1) — a unit Manager flips the server liveSetMCPServerStatus (Manager‑only, fail‑closed)mcp_servers.status pending→approved; only approved projects to the upstream view; evicts resolver cache
3Per‑team binding approval (T2)ApproveMCPServerBinding / decideBinding · team-gateway/pending-bindings-panel.jsxmcp_server_units.approval_status pending→approved; seeds the egress allowlist for the server's host; re‑probes if tool_schema is empty
4(optional) Subtree‑withhold a server for a subtreeSetMCPServerWithhold (Manager‑only)binding_kind='withhold' — subtracts the server from that unit + descendants (D4b)
5Guardrails (3‑tier) — registry/server → team → agent tool policiesGuardrailService / ToolPolicyService · team-gateway/entitlement-matrix.jsxmcp_tool_policies (CEL argument_rule / response_filter); unit_id NULL = org‑wide
6Per‑agent tool selection (narrow‑only) at agent creationAgentService.SetAgentTools (L4 admin or L3 Manager, IDOR‑guarded)agent_configurations.tools — a subset of the team's tools
7Credential — see the per‑mode subsection belowSetMCPServerCredential · team-gateway/credential-dialog.jsxwrites vault (mcp_bearer_token_* / mcp_oauth_client_secret_*) at the org / team / agent grain
8Egress allowlist — only for a PRIVATE upstream (L5 + Manager gated)binding fields private_upstream_approved + private_pinned_cidr → auto‑seeded on binding approval (seed_mcpapproval.go)tenant_egress_allowlist row allow_private=true + pinned_cidr, reason mcp_private_upstream_approval. Dev: docker bridge 172.18.0.0/16, dotted alias betadev-refund-mcp.mcp.internal. Prod: the GKE ClusterIP CIDR. SSRF sinks are never overridable.

Verification after onboarding: start a fresh session for an agent whose clearance ≥ min_clearance, confirm the tool appears (GetTeamEntitlementMatrix verdict allowed), then run a real tools/call.

4.1 Mode none — unauthenticated upstream​

  1. Steps 1–3 with auth mode None. Leave oauth_config_json empty.
  2. No credential, no step 7. The upstream must accept initialize / tools/list / tools/call without an Authorization header.
  3. Use only for servers that enforce nothing themselves or sit behind the pinned‑CIDR egress rule.
  4. Beta‑dev fixture: the server betadev-smoke-none → compose service betadev-smoke-mcp (http://betadev-smoke-mcp.mcp.internal:9000/, tools smoke_echo / smoke_escalate_probe). The registrations and their recreation record are in test/harness/betadev-smoke-mcp/README.md (#4272).

4.2 Mode bearer — static shared token​

  1. Steps 1–3 with auth mode Bearer token.
  2. Step 7: SetMCPServerCredential{registry_id, credential_type:"bearer_token", secret} (portal: team credential dialog, type Bearer token).
    • omit unit_id and agent_id → org _default slot;
    • unit_id → that team's slot;
    • agent_id → that agent's slot (L3 if the caller manages the agent's team, else L4). unit_id and agent_id are mutually exclusive.
  3. If every agent must present its own upstream token: set the binding to credential_mode=per_agent and require_per_agent=true (UpdateMCPServerBinding / server edit dialog), then upload one agent‑scoped credential per agent. Agents without one fail closed at step 3.6 (§1).
  4. Switching a server's mode in the edit dialog does not carry a secret over — the server is unauthenticated until a credential is set again.
  5. Beta‑dev fixtures:
    • betadev-refund-mcp: a bearer‑gated compose service (#4207).
    • betadev-smoke-rpa: bearer, require_per_agent, team‑grain credential only. An agent without its own credential fails closed with 403, which is the neg-require-per-agent-missing case (#4272).

4.3 Mode oauth2 — gateway obtains a token from the upstream's authorization server​

  1. Step 1 with auth mode OAuth 2.0 and the non‑secret settings. Either set the structured oauth2_settings fields on RegisterMCPServer / UpdateMCPServer (#4216; the client SPA register form and server edit dialog send them, client#945) or hand‑write oauth_config_json. Both produce this bag:
    {
    "type": "oauth2",
    "token_endpoint": "https://auth.vendor.example/oauth2/token",
    "client_id": "<client id issued by the vendor>",
    "audience": "https://mcp.vendor.example",
    "scope": "tools:call",
    "grant_type": "client_credentials"
    }
    • grant_type: client_credentials for ordinary SaaS tools (two‑legged, no subject token).
    • grant_type: token_exchange (or omit) only when the vendor's AS federates with our issuer and will accept our agent JWT as subject_token. This is what XAA will eventually ride on (#1953, parked).
    • token_endpoint must be https; audience / resource as the vendor requires.
    • The write is refused unless the bag is complete (ValidateOAuthBag, #4217). Switching an existing server to OAuth 2.0 without oauth2_settings in the same request is refused, and the refusal names that remedy.
  2. Steps 2–3.
  3. Step 7: SetMCPServerCredential{..., credential_type:"oauth_client_secret", secret} at the org / team / agent grain exactly as in 4.2.
  4. The token endpoint host must also pass egress. The binding‑approval seed covers the server URL host; if the AS lives on a different host, add it to tenant_egress_allowlist or the first mint fails with an egress denial. No code path seeds that host and no RPC writes the table; beta‑dev's fake-as.mcp.internal row was written by hand (test/harness/betadev-fake-as/README.md, step 6; #4209).
  5. Expect one token‑endpoint POST per tools/call (no Hop‑B cache).
  6. A private or self‑signed AS: the exchanger refuses an http token_endpoint and verifies TLS against context‑engine's trust store. Beta‑dev trusts its fixture CA, name‑constrained to fake-as.mcp.internal, through SSL_CERT_DIR on context‑engine; that arrangement is 🔵 dev‑only. The fixtures are betadev-refund-oauth2-cc (client_credentials) and betadev-refund-oauth2-tx (token_exchange), both against betadev-refund-oauth2-mcp (#4209).

4.4 First‑party servers — upsquad-memory-mcp, upsquad-knowledge-mcp (#4172)​

These are ours, run in‑cluster, and need a caller‑scoped credential so every read is tenant‑ and agent‑scoped at the server. The gateway mints a platform‑signed delegation bearer instead of using a vault secret.

  1. Deploy the server and set the matching endpoint in context‑engine: MCP_BUILTIN_MEMORY_ENDPOINT (default http://upsquad-memory-mcp:9100/) or MCP_BUILTIN_KNOWLEDGE_ENDPOINT (default http://upsquad-knowledge-mcp:9101/). Beta‑dev compose sets the dotted aliases http://upsquad-memory.mcp.internal:9100/ / http://upsquad-knowledge.mcp.internal:9101/, because a single‑label host cannot be an egress allow‑list pattern.
  2. Configure the server to validate against the platform issuer: JWKS_URL, TOKEN_ISSUER, and TOKEN_AUDIENCE = <base>/mcp/upsquad-memory or <base>/mcp/upsquad-knowledge (the path‑suffixed audience; beta‑dev compose derives it from MCP_GATEWAY_PUBLIC_BASE_URL, fixed by #4204 / PR #4236).
  3. Register with cmd/tools/memory-onboard (mcpserver.ConvertBuiltin / RegisterBuiltinTx), which inserts the mcp_servers row and the mcp_builtin_registrations row (mig 282). A plain RegisterMCPServer of the same URL is not enough — the selector (internal/mcpserver/builtin.go) requires a builtin registration whose URL byte‑matches the configured endpoint, and denies a row that only has the is_first_party flag. On beta‑dev, use scripts/dev-seed-first-party-mcp.sh (cmd/tools/first-party-seed; plan, --apply, --verify, --smoke). It runs in context‑engine's network namespace and writes the mapping, binding, pin, egress row and probed tool_schema (docs/runbooks/first-party-mcp-dev.md, #4204).
  4. Steps 2–3 of §4.0, with the binding marked private_upstream_approved + pinned in‑cluster CIDR (step 8) — the server is a private IP like any other in‑cluster upstream.
  5. No step 7: the credential is minted per call by FirstPartyMinter (internal/auth/oauth/first_party.go) and requires the inbound JWT's unit_id to equal the team and its aud to be exactly the team audience. If no platform signing key is loaded the mint fails closed.

4.5 Handout for the MCP server owner​

§4.0–§4.4 are for our operator. The other external party is the owner of the MCP server being registered, who asks what they must do on their side. Send them the user manual docs/manuals/mcp-server-owner-integration.md as-is (#4503, split by file in #4521). It carries no internal RPC names. The reviewer evidence that maps every claim in it to code stays internal in docs/runbooks/mcp-server-owner-integration.md. What the owner hands us, per mode:

  • none: the URL. Their server must serve tools/call with no Authorization header.
  • bearer: the URL and one static token (or one per team or per agent). We send it as Bearer on the session initialize and on tools/call. The registration capture sends it too, from the team's slot or the org default, unless the binding requires a per‑agent token.
  • oauth2 + client_credentials: an https token endpoint, a client_id and secret for UpsQuad (sent with HTTP Basic), and audience and/or resource (+ optional scope). Expect one token POST per session open for each such server on the team, one per tools/call, and one per registration capture (#4507; no token cache).
  • oauth2 + token_exchange: the same, plus an AS that trusts our issuer and JWKS. It must accept a subject_token whose aud is our team gateway and which has no sub (identity is agent_id). The registration capture has no agent token to exchange, so it sends no credential in this mode. Discovery must stay open here.

The registration capture sends the credential when one can be derived without an agent (the MintForDiscovery table). The two not_derivable cases are token_exchange and bindings with require_per_agent. They capture zero tools unless the server's discovery is open. A manual tool‑schema upload for those servers is a separate founder decision, not built. In both oauth2 modes a token‑endpoint host that differs from the server host still needs a hand‑written egress row (§4.3 step 4). The registration capture's egress posture is the tenant's allow‑list, not the server's approval. It runs inside the registering request, before any Manager approves the binding. So a capture that carries a credential reaches the server's host, and the token endpoint, exactly when those hosts are already on the tenant list, wildcards included. That is why the capture reads only this server's own vault ref.


5. Connecting an EXTERNAL agent (hand these steps to the operator)​

Use this when the agent runs on infrastructure we don't control — the customer's LangGraph / Claude‑SDK runtime, or a developer's Claude Code / Codex pointed at a team. Prereq (platform side): the platform issuer must be reachable — beta‑dev only today: the issuer and the team gateway are both public at https://auth-beta.upsquad.ai (since 2026‑10‑22 and 2026‑10‑26), and prod is parked on #1864.

One‑time registration (done by the customer's admin in our platform / by us on their behalf):

  1. Create the agent in the target team (unit) as an external agent and note its agent_id, unit_id, org_id.
  2. Register the external client: RegisterExternalAgent → returns a client_id. Choose the client‑auth method:
    • private_key_jwt (recommended): the operator generates an RSA keypair and registers the public JWK with us; the private key never leaves their side.
    • client_secret_post: we issue a client secret, shown once (store it in their secret manager). The agent detail page (external-credential-panel.jsx) shows the status and offers Rotate (new key or new one‑time secret, same client_id) and Revoke (refused at the next refresh, ≤10 min).

Per‑run — option A (recommended for Claude Code / Codex): mcp-credential-helper. Build with go build -o mcp-credential-helper ./cmd/mcp-credential-helper (pure Go, stdlib + go‑jose). It is a local stdio MCP server that holds the client credential, lazily mints the 10‑minute bearer, refreshes it -refresh-slack (default 1m) before expiry, retries a 401 once, never retries a 403, and sends the streamable‑HTTP DELETE on shutdown. Claude Code .mcp.json:

{
"mcpServers": {
"upsquad-team": {
"command": "/usr/local/bin/mcp-credential-helper",
"args": [
"--token-url", "https://<issuer host>/oauth/token",
"--mcp-url", "https://<gateway host>/mcp/team/<unit_id>",
"--client-id", "<client_id>",
"--private-key", "/home/me/.upsquad/client.pem"
]
}
}
}

Shared‑secret variant: drop --private-key and put UPSQUAD_CLIENT_SECRET in env — never in args (there is deliberately no flag). Codex: the same command/args under [mcp_servers.upsquad-team] in ~/.codex/config.toml. Key file must be 0600‑class; plaintext http:// to a non‑loopback host is refused; use --assertion-audience when the URL you POST to differs from the issuer's own token‑endpoint URL (tunnel / port‑forward). Full contract: cmd/mcp-credential-helper/README.md. Before wiring it into a client, run the same flags plus -check. It does one mint and one tools/list, prints aud / exp / kid / tool_count but never the token, and exits 0 on pass, 1 on refusal and 2 when it could not check (#4215).

Beta‑dev values: --token-url https://auth-beta.upsquad.ai/oauth/token and --mcp-url https://auth-beta.upsquad.ai/mcp/team/<unit_id>. The issuer requires the assertion aud to be exactly https://auth-beta.upsquad.ai/oauth/token. A helper that POSTs in‑network (http://127.0.0.1:8083/oauth/token) must therefore set --assertion-audience / UPSQUAD_ASSERTION_AUDIENCE to that value.

Proven (#4211, 2026‑10‑26, driven from the devbox rather than a laptop): Claude Code with the helper ran tools/call through the public hostname, and both client‑auth methods passed in‑network and through the public edge. The Codex configuration has not been exercised.

Per‑run — option B (any runtime): do the loop yourself, every ~10 minutes. 3. Obtain a gateway token:

POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
&client_id=<client_id>
# private_key_jwt:
&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion=<JWT: iss=sub=client_id, aud=<token endpoint URL>, jti, iat, exp≤5m>
# …or client_secret_post:
&client_secret=<secret>

→ returns a short‑lived RS256 JWT (aud=<base>/mcp/team/{unit}, runtime=external, expires_in=600 advisory — the token's own exp governs). 4. Call our gateway with it. Spec clients send initialize first and carry the returned Mcp-Session-Id on later calls. The bearer is required on every request, initialize and DELETE included (#4270/#4271):

POST /mcp/team/{unit}
Authorization: Bearer <token from step 3>
Content-Type: application/json

{ "jsonrpc":"2.0", "id":1, "method":"tools/call",
"params": { "name":"{server}__{tool}", "arguments": { … } } }
  1. Refresh the token before it expires (~10m) and retry once on 401.

What the operator must understand about errors (they are JSON‑RPC, not just HTTP):

  • -32602 → denied by a governance gate (clearance floor, not in allowlist, or a tool‑policy deny). Not retryable without a config change.
  • -32001 → requires human approval (HITL); a governance_approvals row was created. The call succeeds once approved — poll/retry.
  • 401 → token missing/expired/invalid aud → re‑mint at /oauth/token. A revoked client gets 401 forever. This applies to every method, initialize and DELETE included.
  • 403 → an authorization decision (consent, eligibility, audience); a fresh token with the same claims gets the same answer — do not retry.
  • 404 / 403 on /mcp/team/{unit} and /mcp/group/{id} come only after the token has passed, on every verb: unknown unit, or no eligible member (#4289, PR #4475; aggregated.go:135‑161). An anonymous caller only ever sees the 401 challenge. With a valid token, a verb other than POST/DELETE gets 405 + Allow: POST, DELETE (aggregated.go:155‑159), after the unit has resolved.
  • 502 session initialize failed → no member upstream answered initialize. One dead member no longer causes it. That member is left out of the session, its tools drop out of that session's tools/list, and an mcp_member_initialize_failed row records the reason (#4308). A sessionless tools/list still lists the member. Calling its tool then gets -32000 "no upstream session for member — initialize first" (dispatch.go:378).
  • 401 invalid_client from /oauth/token is uniform for unknown client, revoked client, bad secret and bad assertion aud (no enumeration oracle); the true reason is on the external_token_denied audit row. Check the assertion audience first.

About Hop‑B credentials for external agents: the external agent authenticates to us (Hop‑A). It does not hold the upstream MCP server's credentials — we inject those (Hop‑B) from our vault. If the binding is require_per_agent, an agent‑scoped upstream credential must have been uploaded for that agent_id (§4.2 step 2 with agent_id set), otherwise the call fails closed at step 3.6 with 403.


6. Data model reference​

TableKey columns / enumsMigrations
mcp_serversstatus (pending|approved|disabled), min_clearance 0–5, url, transport, tool_schema JSONB, oauth_config_json (type, grant_type, vault‑refs — no raw tokens), visibility, credential_mode, require_per_agent, is_first_party (informational only, mig 172)128, 162, 172
mcp_server_units (binding)approval_status (pending|approved|denied), binding_kind (grant|withhold), visibility (inherit_down|private|shared_siblings), credential_mode (team_shared|per_agent), require_per_agent, private_upstream_approved, private_pinned_cidr, requested_by/decided_by/decided_at126, 130, 143, 164, 168
mcp_builtin_registrationsmcp_servers row → builtin target (memory|knowledge); the selector for the first‑party minter282
tenant_egress_allowlistdomain_pattern, reason (incl. mcp_private_upstream_approval), allow_private, pinned_cidr (CHECK: allow_private ⇒ pinned_cidr NOT NULL). (tenant_egress_allowlist_config.enforcement_phase exists in mig 035 but no Go code reads it — the guard always enforces.)035, 168
mcp_tool_policiespolicy_kind (argument_rule|response_filter), cel_expr, filter_spec JSONB, action (deny|escalate), scope unit_id/server_id/agent_id132
external_agent_clientsclient_id → org_id/agent_id/unit_id, public JWK xor bcrypt secret (CHECK), status active|rotated|revoked155
governance_approvalsHITL pause rows created on -32001—
audit (audit_action_type, rows in agent_audit_log)mcp_binding_*, mcp_server_approved/_disabled, tool_policy_denied/_escalated, mcp_tool_allowlist_denied, mcp_subtree_withheld (165), mcp_clearance_floor_denied (163), mcp_egress_denied (285 — one row per egress DenialError, #4212), mcp_member_initialize_failed (286 — one row per member an initialize fan‑out left out, with its bounded reason, #4308), external_token_issued/_denied, oauth_upstream_token_issued/_denied/_none (_denied reason no_stored_credential for a bearer server with nothing stored, else token_exchange_failed, #4311). Edge deny rows (floor, allowlist, CEL) carry the client's Mcp-Session-Id as detail mcp_session_id and a NULL session_id, because session_id FKs to agent_sessions (#4307, PR #4328). These rows and the Hop‑B token rows are not hash‑chained (#4330).130, 143, 150, 163, 165, 285, 286

7. Governance model quick reference (ADR‑0024, all 9 decisions LIVE)​

#DecisionWhere enforced
D2#288 GovernanceService exits the MCP path; the gateway edge is the sole PEPdispatch.go (no governance import)
D3HITL / requires‑approval at the edge → -32001 + governance_approvals (never silent deny)edge_policy.go
D4aOrg kill‑switch = registry L5 mcp_servers.status='disabled'SetMCPServerStatus
D4bManager subtree‑withhold = binding_kind='withhold', subtract‑after‑union at every resolution surfaceresolver.go, pg_group_resolver.go
D5Guardrails = 3‑tier ToolPolicyService (registry→team→agent), edge‑enforcededge_policy.go
D6Registry clearance floor = mcp_servers.min_clearance, enforced at snapshot and edgeinitializer.go, edge_policy.go
D7Per‑agent MCP selection at creation (narrow‑only)SetAgentTools
D9Entitlement‑matrix denial reasons (most‑global‑first)GetTeamEntitlementMatrix

Egress/SSRF is ADR‑0025 (#2019/#2020): always‑deny private IPs, approval‑scoped allow_private+pinned_cidr override, never‑overridable SSRF floor, DNS‑rebind re‑validation.


8. Gaps, pending, dev‑only, parked — the honest state​

ItemRefState
MCP gateway shipped feature‑OFF — MCP_GATEWAY_ENABLED default false, per‑tenant opt‑in MCP_GATEWAY_TENANTS (beta‑dev's .env sets it true for the seed tenant …0001)cmd/{context-engine,agent-orchestrator}/config.go🟠 dark / ship‑then‑flip
External‑agent + governed‑MCP prod enablement PARKED — needs a real platform signing key + JWKS#1864 (OPEN, prod-enablement)🟠 parked; revisit with GCP migration · on milestone #40 with the other prod gates, not on #41
Public issuer hostname auth-beta.upsquad.ai not published — live on beta‑dev since 2026‑10‑22; the team gateway and its metadata joined it on 2026‑10‑26#4210, #4273 / PR #4290🟢 closed (beta‑dev)
First‑party dev stack: audience mismatch. Compose now derives the memory/knowledge TOKEN_ISSUER / TOKEN_AUDIENCE from PLATFORM_ISSUER / MCP_GATEWAY_PUBLIC_BASE_URL, so they match what FirstPartyMinter signs#4204, PR #4236; test/lint/dev_compose_platform_origin_4210_test.go🟢 closed
First‑party dev stack: no registration row. scripts/dev-seed-first-party-mcp.sh --apply seeds mcp_builtin_registrations, the binding, pin, egress row and tool_schema; --smoke passed 4/4 on the rotated key (#4237)#4204, PRs #4236/#4242, docs/runbooks/first-party-mcp-dev.md🟢 closed (beta‑dev)
Hop‑B fixtures are compose services: betadev-refund-mcp (bearer, #4207), betadev-fake-as + betadev-refund-oauth2-mcp (oauth2, #4209) and betadev-smoke-mcp (none, require_per_agent, escalate; #4272). They use dotted *.mcp.internal aliases on upsquad-dev, publish no host ports, and are created and restored by the reconciler. Their allow_private egress rows are pinned to the upsquad-dev bridge subnet (172.18.0.0/16 on the devbox). A dead fixture no longer takes its teams down: since #4308 it is left out of the session and audited, though calls to its own tools still cannot succeed. The oauth2 fixtures are registered by test/harness/betadev-fake-as/register-fixtures.sh (dry run by default, PR #4352)docker-compose.dev.yml, test/harness/*/README.md🔵 dev fixtures; all healthy 2026‑10‑29
No Hop‑B token cache — one upstream token‑endpoint POST per tools/call on oauth2 serversterminator.go, exchanger.go🟡 known; sizing follow‑up
No upstream AS discovery — token_endpoint is hand‑enteredconfig.go🟡 by design today
XAA / ID‑JAG, customer‑IdP federation#1953🟠 parked
FlagMultiParentResolver — the sole prod resolver path; compile‑default TRUE (GA #1981). Kill‑switch: platform_feature_flags["orgv24.multiparent_resolver"]=false → falls back to v2.3 → empty MCP set (governed MCP invisible); the orchestrator refuses to start with the trust root armed and the resolver offfeature_flags.go, cmd/agent-orchestrator/main.go🟢 on; ⚠️ do not flip off without knowing this
Dev‑only private‑CIDR path — 172.18.0.0/16 docker bridge + *.mcp.internal dotted alias; prod uses the GKE ClusterIP pinned CIDRdeny.go, seed.go🔵 dev‑only
enforcement_phase is fiction — tenant_egress_allowlist_config.enforcement_phase (mig 035) is read by no Go code; the egress guard always enforces. Do not plan around an "onboarding_log_only" modemig 035, internal/mcp/egress🟡 dead column
Portal cannot configure oauth2 — fixed by oauth2_settings on RegisterMCPServer / UpdateMCPServer (#4216) and the client SPA register form and server edit dialog (client#945). The residual is closed too: every bag write, including a mode‑only switch and a raw oauth_config_json, now passes ValidateOAuthBag (internal/mcpserver/oauth2_settings.go:143). Beta‑dev's never‑mintable test auth row ({"type":"oauth2"}) was deleted by the founder on 2026‑11‑12#4208; #4217 (closed 2026‑11‑12; PR #4356 cb6c7792)🟢 closed
Egress denials at the gateway are invisible — every guarded client in cmd/context-engine (forward, initialize fan‑out, token exchange, probe) now reports to real egress_requests_total / egress_denied_total counters, and every DenialError writes one tenant‑scoped mcp_egress_denied row (host, reason, agent, server). A no_tenant denial has no tenant to scope a row to: it is counted and logged, not auditedcmd/context-engine/egress_probe.go, internal/mcp/egress/roundtripper.go🟢 closed — #4212
One unreachable member takes the whole team gateway down — the initialize fan‑out was all‑or‑nothing, so one dead inherited server made every session on the gateway a 502 with no reason logged. A member whose upstream initialize fails is now left out of the session: a WARN line names it with a bounded reason (egress_denied / upstream_status / no_upstream_session / invalid_target / unreachable), one mcp_member_initialize_failed row records it (migration 286), and tools/list on that session omits its tools. Only "no member reachable" is a 502. Sessionless tools/list (the worker lists before it initializes) still shows the full derived surface, and the fan‑out is still sequential, so a black‑holed member costs up to the client timeoutgroup_session.go:49‑60,230, aggregated.go:224,257,277‑315, mig 286, cmd/context-engine/main.go:2151🟢 closed — #4308, PR #4361 (00e1ebc35)
Entitlement matrix shows an unreachable member as allowed — the portal matrix does not reflect the #4308 fan‑out outcome#4349 (P3, split from #4308)🟠 open
Per‑tool full inputSchema passthroughdispatch.go🟡 stubbed (permissive)
ContextForge services/mcp-proxy removed; idempotency folded into Go edge#1909/#1912🟠 removed (done)
CEL tool policies at the edge for external callers#1764🟢 closed — enforced in dispatch.go for every caller
HTTP‑proxy passthrough mode—🟠 deferred
Auth‑first was partial, and tools/call ran the gate twice. — both aggregated routes now gate first on every verb, before the unit is resolved, so an anonymous caller cannot tell an unknown unit or group from a known one (aggregated.go:135‑161). A valid token on a verb other than POST/DELETE gets 405 + Allow: POST, DELETE (:155‑159). The mint takes the gate's GatedClaims proof, refuses a zero‑value one, and re‑verifies nothing, so each tools/call costs one JWKS verify and one consent read (terminator.go:179‑244, dispatch.go:361). AuthorizeAggregated and AuthenticateAggregateClaims are gone. The #4287 review survivors were pinned separately (#4288, closed by PR #4361)aggregated.go, terminator.go, dispatch.go🟢 closed — #4289, PR #4475 (7ba02dcd3)
Team source catalog re‑validates the bearer — with the repository‑source catalog on and a Knowledge member present, servePost hands the raw bearer to SourceCatalog.Apply, a second signature verify outside the gate. A catalog filter, not the request's gate: cost and surface, not a bypassaggregated.go:207‑209, source_catalog.go · #4476 (open; not prod-enablement)🟠 open · architect + backend‑security
JWKS validator accepts a signed token with no exp — expiry is checked only when the claim is present. The platform issuer always sets exp today, so this is hardeningjwks_validator.go:141 · #4477 (P3, open; not prod-enablement)🟠 open · hardening
Session DELETE is not tenant‑bound — the verb is gated, but EndSession deletes the mapping by Mcp-Session-Id alone. Session ids are random and the caller is authenticatedgroup_session.go:319‑321 · #4478 (P3, open; not prod-enablement)🟠 open · hygiene
Mint before the floor — the floor, allowlist and CEL now decide on the gated caller before the mint (AuthorizeAggregatedWithClaims since #4289) resolves any credential. A refused call reads no vault and writes no oauth_upstream_token_* rowdispatch.go:292,312,331 → :361🟢 closed — #4310, PR #4361
tools/list advertises tools the caller's verdict denies — the floor and allowlist enforcers write a deny row on every check, so list‑time filtering needs side‑effect‑free reads#4348 (P3, split from #4310)🟠 open
A bearer server with no stored credential audits reason token_exchange_failed — it now audits no_stored_credential; the 403 is unchangedterminator.go:52,400‑402, tokenexchange/exchanger.go:215‑239🟢 closed — #4311, PR #4361
Client portal effective access showed every tool ✓ Allowed for an agent whose server pill says Denied — fixed in the client#4309, client#960🟢 closed
Audit writer follow‑ups. An InsertBatchError with an empty Uncommitted set reads as success. Edge deny rows and Hop‑B token rows are not hash‑chained (architect decision pending)#4329, #4330🟠 open
hop-b-bearer smoke case — the trust‑root [2b] stage signed on the host and read COULD‑NOT‑CHECK. It now runs as the key's owner in context‑engine's image and was VERIFIED in the 15/15 run on main#4283, PR #4331 (f868237bd)🟢 closed
Portal E2E none leg — both legs and the negative case passed through the client SPA (bearer 2026‑10‑26, none 2026‑10‑29). Caveat carried: both runs reached the SPA through the box's Envoy with the app Host header, not through the Cloudflare Access login on the public hostname#4213🟢 closed · caveat 🔵
mcp-credential-helper: Codex is documented but not exercised (Claude Code is proven, #4211). The -check self‑test mode is built (#4215 closed, PR #4351)#4211🟠 pending (Codex only)
Fixture CA trust: context‑engine trusts the fake‑AS CA through SSL_CERT_DIR (name‑constrained to fake-as.mcp.internal)docker-compose.dev.yml🔵 dev‑only
External‑agent credential UX in the client portal — GetExternalAgentCredential (PR #4360) feeds the panel's status, last use and rotate/revoke (client#962); the config block shows the real issuer origin (client#961). Beta‑dev's external clients for #4211 were registered through the RPCs#1958 (closed 2026‑10‑31)🟢 closed
External‑agent credential lifecycle gaps — DeregisterMCPServer and RevokeExternalAgentCredential write no audit row; DeleteAgent leaves an external agent's credentials active#4338 (P2), #4350 (P2)🟠 open
Smoke harness hardening — the #4318 review notes are done: roster delimiter, the timeout budget, signer‑side custody stat, and the trust‑boundary header#4321, PR #4367🟢 closed
Egress‑observer wiring pins (#4240) and the standup strays false positive (#4292) — test/tooling only, no gateway behaviour changePR #4351🟢 closed

9. Key files, flags & beta‑dev specifics​

Feature flags / env

  • orgv24.multiparent_resolver (FlagMultiParentResolver) — resolver path; default ON, kill‑switch to v2.3.
  • MCP_GATEWAY_ENABLED — gateway on/off, default false; MCP_GATEWAY_TENANTS — per‑tenant allowlist. Beta‑dev's .env sets it true for the seed tenant …0001.
  • PLATFORM_SIGNING_KEY_FILE / PLATFORM_SIGNING_KEY / PLATFORM_SIGNING_KEY_ID / PLATFORM_ISSUER — Hop‑A trust root (absent → minting + JWKS off, fail‑safe). On beta‑dev PLATFORM_ISSUER=https://auth-beta.upsquad.ai. Unless set explicitly, compose derives MCP_GATEWAY_PUBLIC_BASE_URL, MCP_AUTHORIZATION_SERVER and the first‑party TOKEN_ISSUER / TOKEN_AUDIENCE from it (#4210, PR #4236). So changing it changes every token's iss and aud.
  • MCP_GATEWAY_JWKS_URL — where the gateway fetches the JWKS (dev http://context-engine:8080/.well-known/jwks.json).
  • MCP_BUILTIN_MEMORY_ENDPOINT / MCP_BUILTIN_KNOWLEDGE_ENDPOINT — first‑party upstream URLs the builtin selector byte‑matches.
  • First‑party servers: JWKS_URL, TOKEN_ISSUER, TOKEN_AUDIENCE (must be the path‑suffixed audience).
  • Worker: WORKER_MCP_TEAM_GATEWAY_URL — base the Python worker prefixes to /mcp/team/{unit}.
  • SSL_CERT_DIR on context‑engine (beta‑dev compose only) — adds the name‑constrained fake‑AS fixture CA to the trust store for the oauth2 fixtures (#4209).

beta‑dev topology (docker‑compose + host Envoy + Cloudflare tunnel; the app at beta-dev.app.upsquad.ai, the public issuer and team gateway at auth-beta.upsquad.ai)

  • Gateway host port 127.0.0.1:8083; the SPA reaches it via Envoy route /rpc/ → app_rpc_dev (8083). JWKS: curl -s http://127.0.0.1:8083/.well-known/jwks.json. Public: https://auth-beta.upsquad.ai serves /oauth/token, /.well-known/jwks.json and /mcp/team/<unit> from the same app_rpc_dev cluster.

  • Deploy is the Deploy Dev Stack reconciler (.github/workflows/dev-deploy.yml, self‑hosted dev-box runner), not a hand‑run compose command.

    • Triggers: workflow_run after Publish Images to GHCR succeeds on main; repository_dispatch deploy-dev (client image publishes); a */15 cron drift sweep (5 → 15 min in #4519; the real path when a bot-token merge fires no event); workflow_dispatch.
    • Each run resets /opt/upsquad/upsquad-core to origin/main. Then scripts/dev-reconcile.sh pulls and runs docker compose up -d --remove-orphans, which recreates only the containers whose image digest or rendered config changed. It polls health for up to 60 s and rolls back to the previous digest snapshot on failure.
    • Verify a deploy by comparing the container's org.opencontainers.image.revision label (docker inspect upsquad-context-engine) with the merge SHA.
  • Postgres: docker exec upsquad-postgres psql -U upsquad -d upsquad.

  • Signing key: $PLATFORM_SIGNING_KEY_HOST_DIR/platform-signing-key.pem. On the devbox that is /opt/upsquad/dev-secrets/platform-issuer/ (2700 65532:65532), and the key is 0600 uid 65532, unreadable to every devbox account by design. The kid is in .env PLATFORM_SIGNING_KEY_ID (dev-platform-20261023-094112 since 2026‑10‑23). To sign anything, run as that uid in a throwaway container the way scripts/dev-seed-first-party-mcp.sh --smoke does; never loosen the mode (docs/runbooks/platform-token-issuer.md, "Key custody on a shared host").

  • Hop‑B fixtures are compose services with no host ports and *.mcp.internal aliases on upsquad-dev:

    • betadev-refund-mcp, bearer (docker logs betadev-refund-mcp shows AUTH_OK / TOOLCALL_RECEIVED);
    • betadev-fake-as, a TLS authorization server at https://fake-as.mcp.internal:8443, plus betadev-refund-oauth2-mcp, which accepts only its tokens;
    • betadev-smoke-mcp, an auth‑none stub.

    Registrations and recreation records: test/harness/{betadev-refund-mcp,betadev-fake-as,betadev-smoke-mcp}/README.md.

  • The proof: PATH=/usr/local/go/bin:$PATH bash scripts/smoke-mcp-oauth-betadev.sh. Pin SMOKE_NONE_SERVER_ID / SMOKE_OAUTH2_CC_SERVER_ID / SMOKE_OAUTH2_TX_SERVER_ID to the fixture servers, and pass the external clients in SMOKE_EXT_* (operator‑held, env only).

    • Exit codes: 0 = all 15 cases VERIFIED; 1 = a case FAILED, or a custody finding; 2 = could not check. A subset (SMOKE_ONLY) can never exit 0.
    • Side effects: none on configuration. A run leaves the audit rows any call leaves and one pending approval row.
    • Bearer‑only trust‑root smoke: MCP_LIVE_SMOKE=1 … bash scripts/smoke-mcp-trust-root.sh (recipe in its header). Since PR #4331 its [2b] stage runs as the key's owner in context‑engine's image, so an account that does not own the key can run it (it still needs Docker and the Go toolchain).

Source map

  • Runtime/session: internal/runtime/session/initializer.go, internal/orgunit/resolver.go, internal/runtime/server/lifecycle_server.go (mintAgentGatewayToken)
  • Hop‑A auth: internal/auth/oauth/{agent_token,issuer_routes,token_endpoint,jwks_validator,signing_key}.go, internal/agent/external_service.go
  • Hop‑B auth: internal/auth/oauth/terminator.go, internal/auth/tokenexchange/{config,exchanger,scoped_secret}.go, internal/auth/oauth/first_party.go, internal/mcpserver/builtin.go
  • Gateway PEP: internal/gateway/mcpproxy/{aggregated,dispatch,edge_policy,upstream_proxy,team,group,group_session,platform,pg_group_resolver,pg_team_resolver}.go, cmd/context-engine/edge_enforce_wiring.go, Config.Audit wiring at cmd/context-engine/main.go:2151
  • Egress: internal/mcp/egress/{roundtripper,deny,patterns,seed,seed_mcpapproval}.go
  • Audit: internal/runtime/audit/{writer,pgstore}.go, mcpproxy.EdgeDenyAuditEntry (internal/gateway/mcpproxy/edge_policy.go), runtime.AuditActionMCPMemberInitializeFailed (internal/runtime/types.go:294), internal/context/store/migrations/286_mcp_member_initialize_failed_audit.up.sql
  • Registry/credential: internal/mcpserver/{service,entitlement,oauth2_settings}.go, internal/credentialscope/{service,scope,resolve}.go
  • First‑party servers: internal/auth/mcpidentity/identity.go, internal/context/memory/mcpsrv, internal/context/knowledgemcp, cmd/tools/memory-onboard, cmd/tools/first-party-seed, scripts/dev-seed-first-party-mcp.sh
  • External CLI bridge: cmd/mcp-credential-helper/ (+ README.md)
  • Worker: services/agent-worker/src/agent_worker/mcp/client.py
  • Client SPA (upsquad-client repo): app/src/pages/mcp-registry.jsx, app/src/components/team-gateway/{credential-dialog,server-edit-dialog,entitlement-matrix,identity-rung-badge,pending-bindings-panel}.jsx, app/src/components/external-credential-panel.jsx, app/src/components/mcp-oauth2/oauth2-settings-fields.jsx
  • Beta‑dev proof & fixtures: scripts/smoke-mcp-oauth-betadev.sh, scripts/smoke-mcp-trust-root.sh, test/harness/{betadev-refund-mcp,betadev-fake-as,betadev-smoke-mcp}/ (oauth2 registration: betadev-fake-as/register-fixtures.sh), infra/edge/envoy.yaml (vhost platform-issuer), .github/workflows/dev-deploy.yml, scripts/dev-reconcile.sh

Related ADRs & runbooks: ADR‑0021/0022 (MCP gateway + trust root), ADR‑0024 (MCP governance realignment), ADR‑0025 (egress/SSRF), ADR‑0026 (/mcp/platform); docs/runbooks/platform-token-issuer.md; docs/runbooks/model-gateway-external-agent-onboarding.md §3.1 (public issuer hostname); infra/edge/README.md (edge routes and rate buckets); docs/runbooks/first-party-mcp-dev.md (first‑party seed on beta‑dev); docs/manuals/mcp-server-owner-integration.md (user manual for an MCP server owner, §4.5, #4503; its evidence stays in the internal companion docs/runbooks/mcp-server-owner-integration.md). Trust‑root blocker: #1864. Beta‑dev milestone #41 tracker: #4206; prod gates: milestone #40.


Doc reflects main @ 7ba02dcd3 (2026‑11‑14). The beta‑dev proof is the 15/15 VERIFIED run of scripts/smoke-mcp-oauth-betadev.sh on f868237bd (2026‑10‑30). It has not been repeated since f868237bd: no later run is recorded on #4206, #4289 or PR #4475. At 19:54Z on 2026‑11‑14 beta‑dev's context‑engine still ran d6d6d8c03, a pre‑#4289 build (docker inspect upsquad-context-engine revision label); the reconciler picks up 7ba02dcd3 once its images publish. On d6d6d8c03 an anonymous GET on /mcp/team/{unit} already answers 401 (PR #4405); the group route's gate-first order, the 405, and the single gate on tools/call reach beta-dev with 7ba02dcd3. Refreshed under #4206 for milestone #41's beta‑dev end state. Invalidated by: #4476 (source catalog on the gate's proof), #4477 (exp required) or #4478 (tenant‑bound DELETE); #4348 (tools/list by verdict) or #4349 (matrix health); #4338 / #4350 (external credential lifecycle); #4329 / #4330 (audit writer); serving the external /mcp/platform contract (#4425); changing the platform-issuer edge routes; rotating the issuer key; flipping MCP_GATEWAY_ENABLED outside beta‑dev; resolving #1864; or adding a Hop‑B type or grant_type. Update the changelog, §1, §3, §5, §8 and §9 when any of these happens.