Back to blog
November 17, 2026•24 views

MCP Server Security Patterns: Authentication, Authorization, and Rate Limiting for Production

MCPAI automationsecurityNode.jsOAuthrate limitingNext.js
MCP Server Security Patterns: Authentication, Authorization, and Rate Limiting for Production

Most MCP servers I audit in the wild have no authentication at all. Someone wires up a stdio server, exposes it over HTTP because their agent needs a remote endpoint, and suddenly a tool that can read your Postgres database is listening on a port with nothing in front of it. I have seen this on client projects in Dhaka, in Sydney, and in a US startup's staging environment that was, embarrassingly, publicly reachable.

The Model Context Protocol is young, and the security story is still being written. But the MCP server security patterns you need are not novel. They are the same patterns we have used for REST APIs and internal microservices for a decade, applied to a protocol where the "user" is often an LLM making tool calls on someone's behalf. That shift changes the threat model in ways that matter.

This is a working catalog of MCP server security patterns I use when shipping these things to production: authentication, authorization, rate limiting, and the logging that makes all three debuggable. Concrete code, not a risk listicle.

The MCP threat model, briefly

Before patterns, name the attacks. If you cannot describe what you are defending against, your security controls are decoration.

  • Confused deputy. The MCP server holds broad credentials (a service account with write access), but the caller is a low-privilege user. The LLM dutifully calls a tool and the server does what it is told with credentials far above the caller's pay grade.
  • Token passthrough. The client forwards a user's OAuth token straight to the upstream API without checking scope. If the token is stolen or over-scoped, the MCP server becomes a laundering layer.
  • Tool poisoning. A malicious or compromised tool description injects instructions the model follows. The tool schema itself is an attack surface because the model reads it.
  • Prompt injection via tool output. A tool returns attacker-controlled text (a scraped web page, a support ticket) that tells the model to call a different, more dangerous tool.
  • Unbounded consumption. No rate limit means a looping agent can hammer your database or run up an LLM API bill in minutes.

Every pattern below maps to at least one of those. Keep that mapping in your head.

Pattern 1: OAuth 2.1 with resource indicators for authentication

If your MCP server is remote and multi-user, you want OAuth. Not an API key in a header. API keys are fine for a single-tenant internal server where the caller is a trusted service, but the moment a human's identity matters, you need a real token flow.

The MCP authorization spec builds on OAuth 2.1 and recommends the Resource Indicators extension (RFC 8707) so that clients request tokens scoped to a specific MCP server. That last part is the piece people skip. Resource indicators bind a token to a specific MCP server audience, which mitigates the token passthrough attack: a token minted for your calendar service cannot be replayed against your billing server. (Note that the MCP spec has evolved since its initial release, check the current authorization section of the MCP specification for the latest requirements, since details like the required OAuth version and discovery flow have changed across revisions.)

Here is the shape of a validation middleware in Node with a JWKS-backed verifier. This is the pattern I reach for with jose:

import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(new URL(process.env.OIDC_JWKS_URI!));

export async function authenticate(req: Request) {
  const auth = req.headers.get("authorization");
  if (!auth?.startsWith("Bearer ")) throw new HttpError(401, "missing_token");

  const token = auth.slice(7);
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: process.env.OIDC_ISSUER,
    audience: process.env.MCP_RESOURCE_URI, // e.g. https://mcp.acme.com
  });

  return {
    sub: payload.sub as string,
    scopes: String(payload.scope ?? "").split(" "),
    tenant: payload.tenant as string | undefined,
  };
}

Two things to get right here. First, audience must match your MCP server's canonical URI, not the client's. Second, never trust a token that failed signature verification even if it "looks right." I have watched developers skip the JWKS check in dev and ship it to prod.

For stdio servers (local, launched by the client process), authentication is less about tokens and more about process isolation. The trust boundary is the OS user. Do not add an HTTP listener to a stdio server "just for testing" and forget to remove it. If you are still deciding which transport to expose, my breakdown of MCP transport: stdio vs Streamable HTTP covers when each one widens your attack surface.

Anti-pattern: API key in the query string

I still see ?api_key=... in MCP examples. Query strings end up in access logs, browser history, and referrer headers. Put credentials in headers or the OAuth flow, nowhere else.

Pattern 2: Per-tool authorization scoping

Authentication answers "who are you." Authorization answers "what can you do." In MCP, authorization happens at two levels: the session (which tools are visible) and the call (which arguments are allowed).

The confused deputy attack lives here. Your server has a service account that can delete rows. A user with read-only access asks the agent to "clean up old records." If your server only checks "is the caller authenticated," it deletes.

The fix is a scope check on every tool invocation, keyed to the tool and the caller's scopes:

const TOOL_SCOPES = {
  search_customers: "customers:read",
  update_customer: "customers:write",
  delete_customer: "customers:delete",
  send_invoice: "billing:write",
} as const;

function authorizeToolCall(tool: string, scopes: string[]) {
  const required = TOOL_SCOPES[tool];
  if (!required) throw new HttpError(403, "unknown_tool");
  if (!scopes.includes(required)) throw new HttpError(403, "insufficient_scope");
}

That is the floor. Two things make it production-grade.

Filter the tool list by scope. When the model lists tools, only return the ones the caller can actually use. This is not just security, it is prompt quality. A model that sees delete_customer in its tool list will try to use it. Hiding it removes the temptation and saves tokens.

Scope the data, not just the tool. Authorization on the tool name is table stakes. The dangerous part is row-level access. If a tenant A user calls search_customers, the SQL must include WHERE tenant_id = $1 with the tenant from the token. Never trust a tenant_id argument the model passes in. That argument is attacker-controlled the moment prompt injection succeeds.

Multi-tenant scoping pattern

I use a small wrapper that injects tenant context from the verified token and strips any client-supplied tenant fields:

function scopeArgs(args: Record<string, unknown>, ctx: AuthContext) {
  const { tenant_id...rest } = args; // discard caller-supplied tenant
  return { ...rest, __tenant: ctx.tenant };
}

Then every query builder reads __tenant. Boring, effective, and I have caught real bugs with it.

Pattern 3: Rate limiting that respects the agent loop

Agents do not make one request. They loop. A single user prompt can trigger twenty tool calls in a minute, and a bug in the agent's reasoning can trigger two hundred. Standard per-IP rate limiting is the wrong shape because all those calls come from the same IP.

You want layered limits:

Layer Key Purpose Typical limit
Edge / IP client IP Block floods and scrapers 300 req/min
Session OAuth sub + session ID Fair use per user 60 req/min
Tool sub + tool name Stop expensive tools being hammered 10 req/min for send_invoice
Cost sub + estimated tokens Cap spend, not just requests configurable budget
Global server Protect downstream DB/API DB connection pool size

Implementing this in Redis with a fixed window is straightforward. A counter per key:

async function checkRateLimit(key: string, limit: number, windowSec: number) {
  const now = Date.now();
  const redisKey = `rl:${key}`;
  const count = await redis.incr(redisKey);
  if (count === 1) await redis.expire(redisKey, windowSec);
  if (count > limit) {
    const ttl = await redis.ttl(redisKey);
    throw new HttpError(429, "rate_limited", { retryAfter: ttl });
  }
}

The snippet above is a fixed-window counter, which is simple but allows bursts at window boundaries. For smoother behavior, use a sliding-window log or a token bucket (for example, via a library like rate-limiter-flexible or Redis's own rate limiting patterns). The details that matter in production:

  • Return Retry-After. Agents that get a 429 with a retry hint back off gracefully. Agents that get a bare 429 tend to retry immediately and make it worse.
  • Different limits for different tools. A read_file tool and a deploy_to_production tool should not share a bucket.
  • Budget, not just count. Tokens cost money. Track estimated token spend per user and cap it. I have seen a runaway loop burn through a client's API budget in an afternoon because the only limit was a request count that was set too high.
  • Fail closed on Redis outage. If your rate limiter is down, do not silently allow everything. Fail the expensive tools, allow the cheap reads. This is a judgment call, and it depends on the tool. Make it explicit in code.

Pattern 4: Input validation and output sanitization

The model is not a trusted input source. Tool arguments arrive from an LLM that has read untrusted text. Treat every argument as hostile.

Validate with a schema library (Zod is my default in TypeScript) and reject anything that does not match. Then, critically, sanitize outputs. If a tool returns a scraped page, strip anything that looks like an instruction before it re-enters the model context. This is imperfect, but it raises the cost of prompt injection meaningfully.

import { z } from "zod";

const SearchSchema = z.object({
  query: z.string().min(1).max(200),
  limit: z.number().int().min(1).max(50).default(10),
});

// reject unknown keys, do not pass them to the DB
const args = SearchSchema.strict().parse(rawArgs);

Use .strict() so extra keys fail loudly. A model that hallucinates a __tenant field should not be able to smuggle it past validation. If you are parsing these payloads on the client side too, the same discipline applies, see TypeScript type guards for Next.js for surviving unknown API responses without trusting them.

Pattern 5: Audit logging and runtime monitoring

You cannot investigate what you did not log. Every tool call should produce a structured audit record: who, what tool, what arguments (redacted), what the outcome was, and how long it took.

Field Example Why
trace_id abc-123 Correlate across services
sub user_8812 Attribution
tool update_customer What ran
args_hash sha256:... Detect tampering without storing PII
scopes ["customers:write"] Prove authorization
status ok / denied / error Spot anomalies
duration_ms 142 Catch slow tools
tenant acme Multi-tenant isolation

The anomaly patterns worth alerting on: a spike in denied for one user (probing), a sudden increase in tool call volume per session (runaway loop), and calls to a tool a user has never used before (compromised token). None of these require ML. Simple thresholds catch most of it.

Gateway, sidecar, or in-server: choosing your enforcement point

You have three places to put these controls, and the choice affects everything downstream.

Approach Pros Cons Best for
In-server enforcement Simple, no extra infra, low latency Must be re-implemented per server, easy to miss Small teams, single server, early stage
Gateway / proxy Central policy, one place to audit, language-agnostic Extra hop, another thing to operate, can bottleneck Multiple MCP servers, compliance needs
Sidecar Isolated per server, good for K8s Complex, still per-server config Kubernetes-heavy infra, strict isolation

My default: in-server enforcement for the first server, gateway when you have three or more. The gateway is where rate limiting and audit logging live at scale, because duplicating that logic across every MCP server is how you get drift and gaps. If you are building that first server now, my guide to building a production MCP server in Next.js walks through auth, tool schemas, observability, and deployment end to end.

A security checklist you can actually use

Copy this into your repo's README and tick the boxes before you ship:

  • TLS everywhere. No plaintext HTTP, ever.
  • OAuth with resource indicators for remote, multi-user servers.
  • JWKS signature verification on every token, cached with a TTL.
  • Per-tool scope checks, plus tool list filtering by scope.
  • Tenant/row scoping from the token, never from tool arguments.
  • Zod (or equivalent) schema validation with .strict().
  • Layered rate limits: IP, session, tool, cost, global.
  • Retry-After on 429 responses.
  • Structured audit log with trace IDs and redacted arguments.
  • Alerting on denied-spike and volume anomalies.
  • Secrets in a vault, not in env files committed to git.
  • Dependency scanning and pinned versions for the MCP SDK.

One more item that belongs on every list like this: version and test your tool definitions. A schema change that silently widens a parameter is a security regression, and agent skills drift is how you catch it before an agent does. And because MCP servers are a supply chain like any other, keep the dependency-scanning discipline from my AI hallucinated dependencies verification checklist in your CI.

FAQ

Do I need OAuth if my MCP server is only used internally?

If it is single-tenant and the caller is a trusted service with its own authentication, a scoped API key over TLS is defensible. The moment a human's permissions matter, or the server is reachable from outside your network, use OAuth. The cost of adding it later, after you have built assumptions on top of a shared key, is much higher than adding it now.

How do I stop an agent from looping and hammering my tools?

Rate limit on the session key, not just the IP, and add a cost budget per user. Return Retry-After so well-behaved agents back off. Also cap the number of tool calls per conversation turn at the orchestration layer. That last one is the cheapest fix and catches most runaway loops before they reach your server.

Is in-server authorization enough, or do I need a gateway?

For one or two MCP servers, in-server is fine and simpler to operate. Once you have several, a gateway centralizes rate limiting, audit logging, and policy so you are not re-implementing the same checks in every codebase. The pattern I use: in-server for the fast, tool-specific checks, gateway for the cross-cutting controls.

What is the biggest MCP security mistake you see?

Skipping authorization entirely because the server "only has read tools." Read tools expose data, and data is the thing attackers want. A read-only tool that returns customer records is a data breach waiting for a prompt injection to point it at the wrong table.

Conclusion

MCP server security is not a product you bolt on. It is a handful of patterns applied consistently: real authentication with resource-bound tokens, per-tool and per-row authorization, layered rate limits that respect the agent loop, strict input validation, and audit logging that lets you answer "what happened" at 2am. None of it is exotic. All of it is easy to skip when you are racing to ship.

If you are building an MCP server or an AI automation layer and want a second pair of eyes on the security model before it hits production, that is exactly the kind of work I do. I have shipped MCP servers and AI automation for clients across Bangladesh, the US, the UK, and Australia, and I am happy to talk through your setup. Reach out through the contact page and tell me what you are building.

Frequently asked questions

Do I need OAuth if my MCP server is only used internally?

If it is single-tenant and the caller is a trusted service with its own authentication, a scoped API key over TLS is defensible. The moment a human's permissions matter, or the server is reachable from outside your network, use OAuth with resource indicators. Adding it later is far more expensive than building on it from the start.

How do I stop an agent from looping and hammering my tools?

Rate limit on the session key (OAuth subject plus session ID), not just the IP, and add a cost budget per user. Return a Retry-After header on 429s so well-behaved agents back off. Also cap tool calls per conversation turn at the orchestration layer, which is the cheapest fix and catches most runaway loops before they reach your server.

Is in-server authorization enough, or do I need a gateway?

For one or two MCP servers, in-server enforcement is simpler and fine. Once you run several, a gateway centralizes rate limiting, audit logging, and policy so you are not re-implementing the same checks in every codebase. A common split is in-server for tool-specific checks and gateway for cross-cutting controls.

What is the biggest MCP security mistake you see?

Skipping authorization because the server "only has read tools." Read tools expose data, and data is what attackers want. A read-only tool returning customer records is a data breach waiting for a prompt injection to point it at the wrong table.

Share this post

Native Web Share is available on mobile, so that share sheet includes Instagram and any other app you have installed.

Let's Connect

Get In Touch

Let's build something premium together.

Contact info

Follow me
Chat on WhatsApp