Features / MCP security gateway

MCP security gateway

The MCP security gateway sits between AI agents and an MCP server you run. It checks each caller's token, rejects malformed or oversized requests, decides which tools may be called, filters the tool list agents see, and writes an audit record for each decision. This page shows a working setup, what each check does, and what the gateway does not cover.

What MCP is

MCP (the Model Context Protocol) lets an AI agent discover and call tools on a server, such as "search the docs" or "delete an order". Its messages are JSON-RPC: small JSON objects with a method (for example tools/list or tools/call) and params. An MCP server exposed directly gives every caller every tool. The gateway lets you put authentication and a tool policy in front of it without changing the server.

Smallest working setup

server {
    listen ":443" protocols="h3,h2,h1"
    tls {
        cert "/etc/miraserve/certs/example.com.crt"
        key "/etc/miraserve/certs/example.com.key"
    }
}

site "ai.example.com" {
    route "/mcp/*" {
        mcp-gateway upstream="https://10.0.1.20:8443" {
            jwt-public-key "ed25519:/etc/miraserve/mcp-oauth.pub"
            jwt-issuer "https://auth.example.com"
            jwt-audience "https://ai.example.com/mcp"
            required-scope "mcp:tools"
            allow-tools "docs_search" "catalog_read"
            deny-tools "*_delete" "*_exec"
            audit-log "structured-json"
        }
    }
}

Agents connect to https://ai.example.com/mcp/. Requests that pass every check are forwarded to https://10.0.1.20:8443.

What the gateway checks

In order, for each request on the route:

  1. Protocol shape. HTTP Upgrade requests and request bodies with a Content-Encoding (compressed bodies) are refused, because they would bypass inspection.
  2. Token. The caller must send Authorization: Bearer <JWT>. A JWT (JSON Web Token) is a signed set of claims. The gateway accepts only the EdDSA algorithm and verifies the signature with jwt-public-key or a key from jwks-url. It requires a non-empty sub and an unexpired exp, checks nbf and iat with 60 seconds of clock tolerance, and, when configured, requires iss to equal jwt-issuer, aud to equal jwt-audience, and the scope or scp claim to contain required-scope. A failure returns 401 with a WWW-Authenticate header pointing to the metadata document below.
  3. Size and depth. The body may be at most max-request-bytes (413 otherwise) and JSON may nest at most max-json-depth levels (400).
  4. Well-formed JSON-RPC. The Content-Type must be application/json. The body must be one JSON object (no batches), with no duplicate keys, including keys that differ only in case. Top-level fields other than jsonrpc, id, method and params are refused, and for tools/call, parameters other than name, arguments and _meta are refused. The gateway then forwards a re-encoded copy containing only the accepted fields, so the upstream sees exactly what was checked.
  5. Tool policy on tools/call. The tool name in params.name is checked against deny-tools first, then allow-tools. A match in deny-tools, or no match in allow-tools, returns 403 with JSON-RPC error code -32003.
  6. Filtering tools/list. The gateway asks the upstream for an uncompressed reply and removes every tool the policy would refuse, so agents are not shown tools they cannot call. Both JSON and server-sent-event (SSE) replies are filtered; a reply in another format, compressed, larger than 4 MiB, or slower than 30 seconds is replaced by an error.

Tool patterns support * as a wildcard matching any run of characters, so "*_delete" matches orders_delete. deny-tools always wins over allow-tools.

Here is the gateway answering a tools/list request and a denied call, with an upstream that offers five tools:

{"id":1,"jsonrpc":"2.0","result":{"tools":[{"name":"docs_search"},{"name":"catalog_read"}]}}
{"error":{"code":-32003,"message":"tool 'orders_delete' matched deny-tools pattern '*_delete'"},"id":2,"jsonrpc":"2.0"}

OAuth protected resource metadata

With oauth-resource-metadata on (the default), the site serves /.well-known/oauth-protected-resource, the RFC 9728 document that tells MCP clients which authorization server issues tokens for this resource. It lists jwt-issuer as the authorization server, and required-scope (or mcp:tools and mcp:resources if none is set) as the supported scopes. Because of that, jwt-issuer is required while this option is on.

Audit log

Every decision is written to the server log: allow at info level and deny at warning level. With audit-log "structured-json" each record is one JSON object:

MCP gateway denied request mcp_audit={"timestamp_unix":1795106440,"client_ip":"127.0.0.1","rpc_method":"tools/call","tool":"orders_delete","decision":"deny","reason":"tool 'orders_delete' matched deny-tools pattern '*_delete'","principal":"sub:agent-1","arguments_redacted":{"id":7}}
MCP gateway allowed request mcp_audit={"timestamp_unix":1795106440,"client_ip":"127.0.0.1","rpc_method":"tools/call","tool":"docs_search","decision":"allow","reason":"permitted by MCP RBAC policy","principal":"sub:agent-1","arguments_redacted":{"api_token":"[REDACTED]","q":"tls"}}
  • The principal is the token's sub once verified. Raw tokens are never logged; for unauthenticated requests only the authorization scheme is recorded, as in Bearer [REDACTED].
  • In tool arguments, any key containing password, secret, token, apikey, authorization, credential, privatekey, cookie, bearer, session, jwt or signature (ignoring case, dashes and underscores) is replaced with [REDACTED], as are string values that look like bearer tokens, JWTs, PEM keys or well-known API keys.
  • "redacted-text" writes the same information as plain log fields. "off" disables the audit log and produces warning W006.

Directive reference

mcp-gateway goes inside a route and takes the upstream as a property: upstream="https://...".

DirectiveDefaultMeaning
upstream (property)requiredURL of the MCP server.
allow-toolsrequiredTool name patterns that may be called. An empty list is an error (E403). "*" without any deny-tools warns (W006).
deny-toolsnoneTool name patterns that are always refused.
jwt-public-keynoneEd25519 key for token signatures: "ed25519:/path" or "miraserve-ed25519-pub:<base64>".
jwks-urlnoneJWKS URL (a published set of keys) providing Ed25519 keys, selected by the token's kid. Must be https:// unless it is a loopback address. Refreshed at most once a minute.
jwt-issuernoneRequired iss. Required when oauth-resource-metadata is on.
jwt-audiencenoneRequired aud.
required-scopenoneA scope the token must carry.
oauth-resource-metadata#trueRequire tokens and serve the RFC 9728 metadata document. Turning it off warns (W006).
audit-log"structured-json""structured-json", "redacted-text" or "off".
max-json-depth32Maximum JSON nesting, 1 to 128.
max-request-bytes1 MBMaximum request body.

Any token setting (jwt-issuer, jwt-audience, required-scope, or oauth-resource-metadata) requires jwt-public-key or jwks-url; otherwise check reports E403. When any of them is set, every request on the route needs a valid token.

Recommendations

  • Set jwt-audience. Without it, a token your identity provider issued for a different service is accepted as long as the signature and issuer match. check warns about this (W006) only when you use jwks-url, but it applies to jwt-public-key as well.
  • Keep the allow list short and explicit, and add deny-tools patterns for destructive verbs as a second line.
  • Make the upstream accept only UTF-8 JSON with Content-Type: application/json, and reject anything else. The gateway checks and re-encodes request bodies as UTF-8 JSON; an upstream that also accepted other encodings or formats could interpret a request differently from the gateway.
  • Make the upstream reachable only through the gateway, for example on a private address, so callers cannot go around it.

Limits

  • Policy is enforced on tools/call only. Every other method, such as resources/read, prompts/get or initialize, is authenticated and size-checked but then forwarded unchanged, and is recorded as allow in the audit log. If your MCP server exposes sensitive resources or prompts, protect them in the server itself.
  • Requests with an empty body, such as a GET that opens an event stream, are forwarded after authentication without JSON inspection.
  • The tool policy applies to every authenticated caller of the route. There are no per-user tool lists; use separate routes with different required-scope or jwt-audience values if different callers need different tools.
  • Only Ed25519 (EdDSA) tokens are accepted. Tokens signed with RSA or ECDSA are refused.
  • The gateway does not inspect what the upstream returns, other than filtering tools/list.