ontoloji.orgOpen Reference Hub
MCP & Agent Security14 min read·Updated: 2026-12-05·Türkçe sürüm →

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.

Executive Summary — Key Takeaways
  • 01Forwarding a user’s raw IdP OIDC token unchanged across Orchestrator -> MCP Gateway -> Downstream ERP/MES MCP Servers ("God-Token passthrough") directly violates the MCP 2026-07-28 Authorization Specification and NSA CSI_MCP_SECURITY guidance.
  • 02RFC 8693 OAuth 2.0 Token Exchange trades subject_token (human caller) + actor_token (agent/gateway workload identity) for short-lived, single-audience (aud: "https://mcp-ontology.internal") tokens carrying structured act (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 hard HTTP 401 rejections with zero anonymous fallback on tokenless retries.
  • 04Network transport enforces mutual TLS (mTLS) with SPIFFE SVIDs + RFC 8705 certificate thumbprint binding, while shared SQL connection pools prevent cross-tenant bleed via transaction-scoped session principals (SET LOCAL / sp_set_session_context) and W3C traceparent audit 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 Authorization header; servers configured with permissive default/guest roles leak schema metadata or cached rows instead of failing closed.
MCP 2026-07-28 & NSA CSI_MCP_SECURITY Mandate

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.

Security & Audit Comparison of Multi-Hop MCP Authentication Architectures
Auth Delegation PatternCompromise Blast RadiusHuman Row-Level RBACAgent Harness ProvenanceMCP 2026-07-28 & CSI_MCP Status
Raw IdP Token PassthroughCritical: Compromised tool server replays token across enterprise APIsPreserved, but over-scopedNone (no act claim)Explicit Violation (Forbidden)
Shared Service-Account KeyCatastrophic: Single prompt injection exposes all tenants & plantsDestroyed (Confused Deputy)Gateway only; human identity lostExplicit Violation (Identity stripping)
Standard OBO (No act Claim)Low: Audience restricted per hopPreserved (sub retained)Partial (azp only, loses multi-agent chain)Partial (Lacks agent-specific policy)
RFC 8693 Token Exchange + act ClaimMinimal: Single aud, 120s TTL, tool-scoped, mTLS certificate-boundExact: sub + tenant_id drive SQL RLSFull Cryptographic Chain (act.sub + act.act)Compliant Reference Architecture
1POST /mcp (Bearer user_jwt + W3C traceparent)2POST /oauth/token (grant_type=token-exchange, audience=ontology-mcp)Verify subject_token (human) + actor_token (SPIFFE)Mint 120s OBO JWT bound to cnf.x5t#S256 thumbprint3200 OK Downscoped OBO token (aud=ontology-mcp, act)4mTLS POST /mcp (SPIFFE SVID + OBO JWT)alt[Valid Tenant Claim & Verified aud=ontology-mcp + mTLS Binding][else Audience Mismatch, Unbound mTLS Cert, or Unauthorized Tenant]BEGIN READ ONLY; SET LOCAL app.tenant_idEnforce Human RBAC ∩ Agent Ceiling RLS scope5200 OK Tenant-isolated rows (zero pool bleed)6200 OK Governed MCP result7HTTP 403 Forbidden (rejected before SQL pool checkout)8HTTP 403 Forbidden (zero guest fallback)MCP Client(User JWT)Enterprise MCP GatewayEnvoy / AuthzIdP / STS (RFC 8693)OAuth 2.0 STSTenant Ontology NodemTLS + SQL RLSMCP Client(User JWT)Enterprise MCP GatewayEnvoy / AuthzIdP / STS (RFC 8693)OAuth 2.0 STSTenant Ontology NodemTLS + SQL RLS
The Enterprise MCP Gateway never forwards raw user JWTs downstream; it exchanges credentials via RFC 8693 for a single-audience (audience=ontology-mcp) OBO token, binds mTLS client certificates, and enforces transaction-scoped SET LOCAL app.tenant_id.
HTTP & JWT: RFC 8693 Token Exchange Request, Single-Audience JWT with Nested act Claims & Hard-401 Gate
// 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.

  • PostgreSQL Transaction-Scoped RLS (SET LOCAL / set_config(..., true)): Wrap every MCP tool query inside an explicit BEGIN block and bind app.tenant_id, app.human_sub, and app.agent_spiffe_id with is_local = true (SET LOCAL). PostgreSQL guarantees automatic cleanup upon COMMIT or ROLLBACK before the socket returns to PgBouncer or pg.Pool.
  • SQL Server Locked Session Context & Per-Tenant Pool Routing: On SQL Server ERP replicas, bind sys.sp_set_session_context @key = N'tenant_id', @value = ..., @read_only = 1 (or cookie-guarded EXECUTE AS + REVERT in a TRY...FINALLY block), 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’s rbac_roles and 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 that act chain.
TypeScript + PostgreSQL: Zero-Bleed Transaction-Scoped RLS Principal Binding + W3C traceparent SQL Tagging
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 sub possesses approver authority over the exact proposal_payload_hash and trace_id—preventing an agent from self-approving mutations with its actor_token.
Pre-Production MCP Gateway Red-Team Gate

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

Open License (CC BY 4.0) · Cite This Page

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)

More Guides in This Series

Core Architecture
How AI Uses an Ontology
9 min read
Agent Engineering
Agent Harness vs. Ontology
8 min read
Data Engineering
ERP, CRM & MES Patterns
10 min read
Strategy & Governance
30-Day Ontology Strategy
7 min read
ERP Integration
ERP Ontology Integration Guide
11 min read
ERP Data Engineering
Logo Tiger, Nebim V3 & Turkish Unicode Traps
14 min read
Agent Governance
Adversarial Verification, Permissions & Compaction
13 min read
Verification Engineering
Absence-Aware Gates & Ratio Reconstruction
13 min read
Provenance & Governance
Draft vs. Normative Provenance Hygiene
12 min read
SAP & Protocol Architecture
SAP BTP, Cloud Connector & ORD Ontology
11 min read
ERP Write-Safety
Logo REST, Nebim Integrator & UBL-TR Safety
12 min read
Platform Architecture Comparison
Cortex, Genie, dbt & Cube vs. Ontology
12 min read
Systems Engineering & Forensics
ERP Integrator Anti-Patterns & Forensics
13 min read
Platform Architecture Comparison
Fabric IQ, D365 MCP & SAP Joule vs. Ontology
12 min read
Retrieval & RAG Architecture
PageIndex Vectorless Tree RAG vs. Vector DBs
11 min read
Platform Architecture Comparison
Atlan, Stardog & Neo4j vs. Ontology
12 min read
Statutory & Financial Governance
GİB UBL-TR, VUK/TMS 29 & KVKK Ontology
13 min read
Agent Memory & Ontology Architecture
Cognee & Zep Graphiti vs. Ontology
11 min read
Protocol & Multi-Agent Architecture
MCP vs. OpenAPI & Specialist Agents
12 min read
Protocols & Standards
MCP 2026-07-28: Tasks, Events & Apps
13 min read
Agent Architecture & Governance
Agent Harness Engineering Rubric
12 min read
Agent Architecture & Governance
Multi-Agent Task Boards & Mailboxes
12 min read
Verification & Security
Generate-Evaluate-Repair & Observers
12 min read
Verification & Security
NSA MCP Security & CIMD vs. DCR
13 min read
Agent Architecture & Governance
OpenTelemetry for AI Agents & MCP
11 min read
Agent Architecture & Governance
MCP Gateway vs. Enterprise AI Ontology
12 min read
MCP & Agent Security
MCP Apps Nonces, Elicitation & Refusal Traps
13 min read
ERP & SQL Ontology
Logo Tiger STLINE, Karmakoli & UINFO1 SQL Traps
14 min read
Manufacturing, MES & OEE Ontology
TRUMPF OPC UA & Siemens Energy SQL OEE Fix
13 min read
MCP & Agent Architecture
Claude Mobile, Desktop & OpenWebUI MCP Bugs
13 min read
ERP & SQL Ontology
AI on ABAP, TROIA, Delphi & Stored Procedures
13 min read
Core Ontology Specification
Operational Ontology: Action Types, Links & Interfaces
15 min read