mech.app

The mech.app newsletter

Agentic AI, minus the noise.

Get practical field notes on AI agents, automation, developer tools and security delivered to your inbox.

No spam. Unsubscribe anytime.

Dev Tools

OAuth MCP Gateways: Why Shared Admin Keys Break Enterprise Agent Deployments

Per-user OAuth gateway pattern for MCP servers solves the shared service-account credential problem blocking enterprise AI agent deployments.

Source: dev.to
OAuth MCP Gateways: Why Shared Admin Keys Break Enterprise Agent Deployments

Most enterprise AI prototypes stall at security review because they run on shared service-account keys. A junior analyst in marketing can ask the agent about restricted finance documents, and the only defense is a line in the system prompt. That does not pass audit.

The problem is not the LLM. The problem is the credential boundary. When you drop a tenant-wide admin token into an agent workflow, you have given every user the blast radius of that token. Prompt-level access control fails the moment an indirect injection lands in a retrieved PDF.

This article walks through the OAuth MCP gateway pattern: a FastAPI proxy that sits between your agent orchestrator and your MCP tool servers, swapping the shared admin key for the signed-in user’s OAuth token on every tool call.

The Shared Key Problem

A typical internal agent prototype connects to SharePoint, Google Drive, HubSpot, or Snowflake using a service account with broad read/write permissions. The agent retrieves documents, the LLM processes them, and the user gets an answer.

The credential flow looks like this:

  1. User sends a query to the agent.
  2. Agent calls a tool (e.g., search_sharepoint).
  3. Tool uses SERVICE_ACCOUNT_KEY to authenticate.
  4. SharePoint returns all documents the service account can read.
  5. LLM processes the documents and returns an answer.

The security gap: the service account can read board minutes, HR files, and deal-room documents. The user might only have access to marketing collateral. The agent has no way to enforce the user’s native permissions because it never sees the user’s identity.

Prompt-level filtering does not work. An attacker can embed instructions in a document title or metadata field, and the LLM will process it as part of the context window. The model cannot distinguish between your system prompt and injected content.

The OAuth Gateway Pattern

The solution is to move the credential boundary. Instead of handing the agent a shared key, you hand it a gateway URL. The gateway intercepts every MCP tool call, extracts the user’s OAuth token from the session, and forwards the request with per-user credentials.

Architecture

User → Agent Orchestrator → OAuth MCP Gateway → MCP Tool Server → External API
         (LangGraph, CrewAI)   (FastAPI)         (SharePoint, Drive)

The gateway does three things:

  1. Session binding: Maps each agent session to a user identity and OAuth token.
  2. Token injection: Rewrites outbound MCP tool calls to include the user’s token instead of a shared key.
  3. Audit logging: Records which user authorized which tool call, with inputs and latency.

Implementation Sketch

Here is a minimal FastAPI gateway that intercepts MCP tool calls and injects per-user OAuth tokens:

from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
import httpx

app = FastAPI()

# In-memory session store (use Redis in production)
sessions = {}

@app.post("/mcp/tool/{tool_name}")
async def proxy_tool_call(tool_name: str, request: Request):
    body = await request.json()
    session_id = request.headers.get("X-Session-ID")
    
    if not session_id or session_id not in sessions:
        raise HTTPException(status_code=401, detail="No valid session")
    
    user_token = sessions[session_id]["oauth_token"]
    
    # Forward to the real MCP server with user token
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"http://mcp-server:8080/tools/{tool_name}",
            json=body,
            headers={"Authorization": f"Bearer {user_token}"}
        )
    
    # Log the call for audit
    log_tool_call(session_id, tool_name, body, response.status_code)
    
    return JSONResponse(content=response.json(), status_code=response.status_code)

def log_tool_call(session_id, tool_name, inputs, status):
    # Write to structured log or observability backend
    print(f"User {sessions[session_id]['user_id']} called {tool_name} with {inputs}, status {status}")

The orchestrator (LangGraph, CrewAI, or custom) calls the gateway instead of the MCP server directly. The gateway looks up the user’s token, injects it, and forwards the request.

Token Refresh and Session State

OAuth tokens expire. If a token expires mid-execution, the gateway must refresh it without breaking the agent’s execution flow.

Options:

  • Proactive refresh: Check token expiry before each call and refresh if needed.
  • Reactive refresh: Catch 401 responses, refresh the token, and retry the call once.
  • Fail fast: Return an error to the orchestrator and let the user re-authenticate.

The right choice depends on your agent’s execution model. If the agent runs a long-running workflow (e.g., a multi-step research task), proactive refresh is safer. If the agent is stateless and session-bound, fail fast is simpler.

State management becomes critical. If the gateway refreshes a token, it must update the session store atomically. If you are running multiple gateway instances, use Redis or a distributed cache with compare-and-swap semantics.

Audit and Observability

The gateway is the natural place to log every tool call with full context:

  • User identity (email, Entra ID object ID, or Google Workspace UID)
  • Tool name and inputs
  • OAuth scope used
  • Response status and latency
  • Timestamp

This gives you a structured audit trail that maps agent actions back to real employees. You can answer questions like:

  • Which user triggered the agent to read a restricted document?
  • How many times did the agent call the delete_file tool this week?
  • What was the average latency for SharePoint search calls?

If you are using OpenTelemetry, the gateway can emit spans for each tool call. The orchestrator emits a parent span for the agent session, and the gateway emits child spans for each tool invocation. This gives you distributed tracing across the agent, gateway, and external APIs.

Trade-offs and Failure Modes

DimensionShared Service AccountOAuth Gateway
Access boundaryTenant-widePer-user ACL
Prompt injection impactCan expose restricted filesLimited to user’s native permissions
Audit trailSingle bot identityReal user identity per call
Token refresh complexityNoneMust handle expiry mid-execution
Deployment overheadLow (single key)Medium (gateway + session store)
Failure modeSilent over-permissionVisible auth errors

The gateway introduces new failure modes:

  • Token refresh race: Two concurrent tool calls trigger two refresh attempts, and one overwrites the other.
  • Session store outage: If Redis goes down, all active agent sessions lose their credential mapping.
  • Gateway bottleneck: If the gateway is a single instance, it becomes a scaling choke point.

Mitigations:

  • Use distributed locks (Redis SETNX) for token refresh.
  • Replicate session state across multiple gateway instances.
  • Run the gateway as a sidecar or in-process library to avoid network hops.

When to Use This Pattern

Use the OAuth MCP gateway when:

  • Your agent accesses enterprise SaaS APIs (SharePoint, Drive, HubSpot, Salesforce).
  • You need to enforce native ACLs at the tool call level.
  • Security review requires per-user audit trails.
  • You are deploying agents to users with different permission levels.

Avoid it when:

  • Your agent only reads public data or data with uniform access control.
  • You are prototyping and not yet at security review.
  • Your orchestrator already handles per-user credentials natively (e.g., some LangGraph deployments).

The gateway adds latency (one extra network hop per tool call) and operational complexity (session store, token refresh). If your agent runs in a single-user context or does not touch restricted data, a shared key is simpler.

Technical Verdict

The OAuth MCP gateway pattern solves the credential boundary problem that blocks enterprise agent deployments. It moves access control from the prompt layer (unreliable) to the protocol layer (enforceable).

The trade-off is operational complexity. You now have a stateful gateway, a session store, and token refresh logic. If your agent is a weekend prototype, skip it. If your agent is heading to production and touching restricted data, this pattern is the difference between a demo and a governed deployment.

The key insight: the agent should never hold more permission than the user who invoked it. The gateway enforces that boundary at the tool call level, where it belongs.


Tags

agentic-ai orchestration infrastructure

Primary Source

dev.to ↗