Enterprise MCP Gateway Architecture: RFC 8693 Token Exchange, mTLS & Tenant Isolation
Eliminating "God-Token" passthrough and confused-deputy exploits in multi-hop MCP deployments with RFC 8693 OAuth 2.0 Token Exchange, SPIFFE mTLS, and transaction-scoped SQL tenant isolation.
- 01Forwarding a user’s raw IdP
OIDCtoken unchanged acrossOrchestrator -> MCP Gateway -> Downstream ERP/MES MCP Servers("God-Token passthrough") directly violates the MCP2026-07-28Authorization Specification and NSACSI_MCP_SECURITYguidance. - 02
RFC 8693OAuth 2.0 Token Exchange tradessubject_token(human caller) +actor_token(agent/gateway workload identity) for short-lived, single-audience (aud: "https://mcp-ontology.internal") tokens carrying structuredact(actor) claims. - 03Downstream ontology MCP servers cryptographically verify both which human employee owns the RBAC row scope (
sub) and which agent harness mediated the call (act.sub), enforcing hardHTTP 401rejections with zero anonymous fallback on tokenless retries. - 04Network transport enforces mutual TLS (
mTLS) withSPIFFESVIDs +RFC 8705certificate thumbprint binding, while shared SQL connection pools prevent cross-tenant bleed via transaction-scoped session principals (SET LOCAL/sp_set_session_context) and W3Ctraceparentaudit spans.
1. The "God-Token" Passthrough & Confused-Deputy Problem in Multi-Hop MCP
As enterprise AI moves from local developer laptops to multi-user production deployments, the topology inevitably becomes multi-hop: Enterprise Chat / Agent Orchestrator -> Enterprise MCP Gateway -> Downstream ERP, MES, PLM, and Document MCP Servers. Most architectural security failures occur right at the identity boundary between those hops.
Early enterprise rollouts routinely fall into one of two broken anti-patterns. Under Raw "God-Token" Passthrough, the orchestrator takes the human employee’s primary IdP OIDC token (Entra ID, Keycloak, Okta) and forwards Authorization: Bearer ... unchanged through the gateway to every downstream MCP server. Under the opposite anti-pattern—Static Service-Account Bridging—the gateway strips the user token and calls downstream ERP/SQL MCP servers using a shared SVC_MCP_ADMIN API key.
Both patterns violate the MCP 2026-07-28 Authorization Specification and NSA CSI_MCP_SECURITY hardening requirements. Forwarding a raw multi-audience user token lets any compromised or buggy downstream tool server replay that token laterally against unrelated enterprise Graph, mail, HR, or finance APIs. Conversely, authenticating via a shared service account creates a textbook Confused Deputy: an indirect prompt injection inside a regional sales rep’s session tricks the agent into querying executive payroll or sister-plant cost margins through the gateway’s god-mode database credentials.
- Audience (
aud) Boundary Collapse: Accepting an upstream orchestrator token on a downstream MCP server destroys Zero-Trust segmentation; every MCP resource server must validate that the token was minted exclusively for its own canonical resource URI. - Erased Agent Provenance: Passing only human user identity blinds security telemetry—downstream ERP audit logs cannot tell whether a sensitive inventory query came from an interactive human analyst or a runaway background agent loop.
- Tokenless Client Retry Fallbacks: Several open-source MCP clients and UIs retry failed calls without an
Authorizationheader; servers configured with permissive default/guest roles leak schema metadata or cached rows instead of failing closed.
An MCP server MUST NEVER accept access tokens minted for an upstream client/orchestrator audience and MUST NEVER forward incoming bearer tokens verbatim to downstream services. Every hop across trust boundaries requires cryptographic audience downscoping.
2. OAuth 2.0 Token Exchange (RFC 8693) Delegation Mechanics & Hard-401 Policy
Preserving exact human RBAC/RLS row boundaries while simultaneously proving which AI agent harness mediated the call is solved cleanly by RFC 8693 (OAuth 2.0 Token Exchange).
At the Enterprise MCP Gateway boundary, the gateway authenticates the incoming user token and calls the internal Security Token Service (STS) using grant_type=urn:ietf:params:oauth:grant-type:token-exchange, supplying two cryptographic inputs: subject_token (the verified human caller JWT) and actor_token (the gateway/agent workload SPIFFE JWT-SVID).
The STS evaluates delegation policy and mints a short-lived (TTL: 60–180s), single-audience (aud: "https://mcp-ontology-erp.internal.corp"), tool-scoped access token carrying structured nested act (actor) claims (RFC 8693 Section 4.1). Downstream ontology MCP servers verify both sub (which human owns the data scope) and act (which gateway and agent harness brokered the execution)—while rejecting any missing, expired, or mis-scoped token with a strict HTTP 401 and zero default identity fallback.
| Auth Delegation Pattern | Compromise Blast Radius | Human Row-Level RBAC | Agent Harness Provenance | MCP 2026-07-28 & CSI_MCP Status |
|---|---|---|---|---|
| Raw IdP Token Passthrough | Critical: Compromised tool server replays token across enterprise APIs | Preserved, but over-scoped | None (no act claim) | Explicit Violation (Forbidden) |
| Shared Service-Account Key | Catastrophic: Single prompt injection exposes all tenants & plants | Destroyed (Confused Deputy) | Gateway only; human identity lost | Explicit Violation (Identity stripping) |
Standard OBO (No act Claim) | Low: Audience restricted per hop | Preserved (sub retained) | Partial (azp only, loses multi-agent chain) | Partial (Lacks agent-specific policy) |
RFC 8693 Token Exchange + act Claim | Minimal: Single aud, 120s TTL, tool-scoped, mTLS certificate-bound | Exact: sub + tenant_id drive SQL RLS | Full Cryptographic Chain (act.sub + act.act) | Compliant Reference Architecture |
// 1. Enterprise MCP Gateway -> Internal STS: RFC 8693 Token Exchange
POST /oauth2/token HTTP/1.1
Host: sts.internal.corp
Content-Type: application/x-www-form-urlencoded
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange
&resource=https%3A%2F%2Fmcp-ontology-erp.internal.corp
&audience=https%3A%2F%2Fmcp-ontology-erp.internal.corp
&scope=ontology%3Aread%20ontology%3Aaction%3Apropose
&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token
&subject_token=eyJhbGciOiJSUzI1NiIsImtpZCI6ImlkcC0yMDI2In0...
&subject_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Ajwt
&actor_token=eyJhbGciOiJFUzI1NiIsImtpZCI6InNwaWZmZS1zdmlkIn0...
&actor_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Ajwt
// 2. Minted Single-Audience Downstream JWT Payload (Decoded)
{
"iss": "https://sts.internal.corp",
"sub": "urn:corp:employee:emp-88412",
"aud": "https://mcp-ontology-erp.internal.corp",
"exp": 1796472720,
"iat": 1796472600,
"jti": "tok-9f31c8b2-77d1-4a22-9e04-12f8a90c4411",
"tenant_id": "ten_anatolia_mfg_01",
"rbac_roles": ["PLANT_PLANNER_TR01", "INVENTORY_READER"],
"scope": "ontology:read ontology:action:propose",
"cnf": {
"x5t#S256": "fU4x9kP2mN8vQ1rL7zW3cB6yH0jD5sA2eG9iK4oP7uM"
},
"act": {
"sub": "spiffe://internal.corp/ns/mcp-dmz/sa/enterprise-mcp-gateway",
"act": {
"sub": "spiffe://internal.corp/ns/ai-agents/sa/mrp-shortage-copilot"
}
}
}
// 3. Downstream Ontology MCP Server Enforcement: Hard 401 on Tokenless Retry or Audience Mismatch
// Zero anonymous/guest principal fallback is permitted:
// HTTP/1.1 401 Unauthorized
// WWW-Authenticate: Bearer resource_metadata="https://mcp-ontology-erp.internal.corp/.well-known/oauth-protected-resource", error="invalid_token"3. Zero-Trust Transport (mTLS / SPIFFE SVIDs) & SQL Connection-Pool Tenant Isolation
Application-layer JWTs must be paired with cryptographic transport binding whenever an MCP gateway bridges cloud or DMZ agent orchestrators into on-premises plant and ERP networks. Every connection between the Enterprise MCP Gateway and on-prem ontology pods enforces mutual TLS (mTLS) backed by short-lived, auto-rotated SPIFFE X.509-SVID workload certificates. Binding the exchanged JWT’s cnf.x5t#S256 thumbprint (RFC 8705) to the caller’s client certificate ensures a captured bearer token is useless outside that exact mTLS channel.
Once a request reaches the ontology server, a subtle systems bug threatens multi-tenant and row-level isolation: shared database connection-pool bleed. High-throughput Node.js, Go, and Python MCP servers pool database sockets via PgBouncer, pg.Pool, HikariCP, or mssql pools rather than opening fresh TCP handshakes per tool call.
Setting session-level context variables (SET app.tenant_id = ...) outside an explicit transaction leaves residual principal state on the pooled socket whenever an exception, cancellation, or transaction-mode pool handoff occurs—leaking an executive’s or another tenant’s row scope to the very next caller who borrows that connection! Eliminating pool bleed requires strictly transaction-scoped session principals.
PostgreSQLTransaction-Scoped RLS (SET LOCAL/set_config(..., true)): Wrap every MCP tool query inside an explicitBEGINblock and bindapp.tenant_id,app.human_sub, andapp.agent_spiffe_idwithis_local = true(SET LOCAL). PostgreSQL guarantees automatic cleanup uponCOMMITorROLLBACKbefore the socket returns toPgBouncerorpg.Pool.SQL ServerLocked Session Context & Per-Tenant Pool Routing: On SQL Server ERP replicas, bindsys.sp_set_session_context @key = N'tenant_id', @value = ..., @read_only = 1(or cookie-guardedEXECUTE AS+REVERTin aTRY...FINALLYblock), supplemented by dedicated connection pools per tenant tier for regulated workloads.- Effective Permission Intersection (
Human RBAC ∩ Agent Ceiling): Compute effective tool and column access as the intersection of the human’srbac_rolesand the mediating agent’s registered capability ceiling (act.act.sub). Even if a CFO invokes a read-only forecasting copilot, kinetic write tools remain cryptographically disabled for thatactchain.
import { Pool } from 'pg';
export interface VerifiedMcpPrincipal {
tenantId: string;
humanSub: string;
rbacRoles: string[];
gatewaySpiffeId: string;
agentSpiffeId: string;
traceparent: string;
}
export async function executeIsolatedOntologyQuery<T>(
pool: Pool,
principal: VerifiedMcpPrincipal,
compiledSql: string,
params: unknown[],
): Promise<T[]> {
// Hard fail closed BEFORE borrowing a database socket
if (!principal.tenantId || !principal.humanSub || !principal.agentSpiffeId) {
throw new Error('HTTP_401_HARD_FAIL: Missing verified RFC 8693 subject or actor claim');
}
const client = await pool.connect();
try {
await client.query('BEGIN READ ONLY');
// third argument 'true' = SET LOCAL (strictly scoped to current transaction).
// Automatically cleared on COMMIT or ROLLBACK—immune to PgBouncer transaction-pool bleed.
await client.query(
`SELECT
set_config('app.tenant_id', $1, true),
set_config('app.human_sub', $2, true),
set_config('app.rbac_roles', $3, true),
set_config('app.agent_spiffe_id', $4, true),
set_config('app.w3c_traceparent', $5, true)`,
[
principal.tenantId,
principal.humanSub,
principal.rbacRoles.join(','),
principal.agentSpiffeId,
principal.traceparent,
],
);
// Correlate database audit logs directly with upstream W3C distributed trace span
const taggedSql = `/* traceparent=${principal.traceparent.replace(/[^a-f0-9-]/g, '')} */ ${compiledSql}`;
const result = await client.query(taggedSql, params);
await client.query('COMMIT');
return result.rows as T[];
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}4. End-to-End W3C traceparent Audit Spans & Defense-in-Depth Checklist
In regulated manufacturing, defense, financial, and healthcare deployments, proving who was authorized is only half of compliance—auditors also require reconstructing which user prompt triggered which agent tool call and read or mutated which exact ERP rows. Propagating a W3C Trace Context (traceparent: 00-<trace-id>-<span-id>-01) inside MCP JSON-RPC params._meta.traceparent stitches every hop into one tamper-evident forensic timeline.
The Enterprise MCP Gateway preserves the root trace-id, generates a child span-id, embeds it in the RFC 8693 STS audit event, injects it into compiled SQL comments, and writes an immutable record to an append-only audit store (trace_id, jti, human_sub, agent_act_sub, ontology_version, compiled_sql_sha256, and row_count).
- Default-Deny Pod Egress (
NetworkPolicy): Lock down ontology MCP pods so they can communicate only with the internal ERP read replica, official kernel queue, and STS—blocking prompt-injected exfiltration to external URLs even if a tool response contains sensitive rows. - Composite Row & Rate Budgets: Enforce token-bucket rate limits and maximum returned row caps keyed on
(tenant_id, human_sub, agent_spiffe_id)so a compromised agent harness cannot bulk-dump authorized tables one page at a time. - Cryptographic Human Approval Binding: For kinetic ERP writes, require an out-of-band human approval signature whose
subpossesses approver authority over the exactproposal_payload_hashandtrace_id—preventing an agent from self-approving mutations with itsactor_token.
Automate three CI security assertions before go-live: (1) Replay a valid upstream orchestrator OIDC token directly against the ontology MCP server (must return 401), (2) Retry a tool call with stripped Authorization headers (must return 401 with RFC 9728 metadata), and (3) Blast 100 concurrent interleaved two-tenant queries against a max=4 SQL pool verifying zero app.tenant_id cross-reads.
Frequently Asked Technical Questions
If we already use Microsoft Entra ID On-Behalf-Of (OBO), why do we still need RFC 8693 nested act claims?
Standard Entra ID OBO solves audience downscoping (aud), preventing upstream token replay, which is a major step forward. However, standard OBO tokens flatten delegation history and rarely preserve a multi-hop cryptographic chain distinguishing which specific internal AI agent harness (mrp-copilot vs. ap-invoice-triage) invoked the gateway on the user’s behalf. Pairing cloud IdP OBO validation at the edge with an internal RFC 8693 STS (Keycloak, Ory, or a SPIFFE-backed STS) adds structured act claims and mTLS thumbprint binding for internal hops.
Why does session-level SET app.tenant_id leak data under PgBouncer transaction pooling?
In PgBouncer transaction pooling mode, physical PostgreSQL backend connections are reassigned across completely different application clients at every COMMIT boundary. Running SET app.tenant_id = 'tenant_a' (without LOCAL) mutates connection-session state that persists after COMMIT, causing the next tenant assigned that backend socket to inherit tenant_a RLS policies. Using SET LOCAL (or set_config(..., true)) inside an explicit BEGIN ... COMMIT block guarantees reset at transaction end.
How should RFC 8693 handle scheduled overnight MCP agents where no interactive human employee is logged in?
Never mint fake "service-human" superuser tokens for cron agents. Issue the batch workload its own narrowly scoped SPIFFE identity as sub (spiffe://internal.corp/ns/batch-agents/sa/nightly-oee-reconciler) with an explicit "human_present": false claim. The ontology policy engine inspects human_present: false to block all kinetic ERP write actions automatically while permitting allowlisted read/alerting views within that single plant scope.
Does enforcing a hard HTTP 401 with zero guest fallback break standard MCP clients during initial connection discovery?
No—returning HTTP 401 Unauthorized with a WWW-Authenticate: Bearer resource_metadata="..." header (RFC 9728 OAuth Protected Resource Metadata) is the exact discovery handshake mandated by the MCP 2026-07-28 authorization spec. Compliant clients parse the 401 challenge to discover the authorization server without ever requiring unauthenticated tool access.
Glossary Concepts Referenced in This Guide
UPDATE/INSERT statements on ERP/CRM databases, requiring typed action proposals validated against preconditions and approved by a named human role.Free to reference in engineering docs, ADRs, articles, and course syllabi with attribution.
[Enterprise MCP Gateway Architecture: RFC 8693 Token Exchange, mTLS & Tenant Isolation — Ontoloji.org](https://ontoloji.org/en/guides/enterprise-mcp-gateway-rfc-8693-token-exchange-mtls-and-tenant-isolation)