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:
- Protocol shape. HTTP
Upgraderequests and request bodies with aContent-Encoding(compressed bodies) are refused, because they would bypass inspection. - Token. The caller must send
Authorization: Bearer <JWT>. A JWT (JSON Web Token) is a signed set of claims. The gateway accepts only theEdDSAalgorithm and verifies the signature withjwt-public-keyor a key fromjwks-url. It requires a non-emptysuband an unexpiredexp, checksnbfandiatwith 60 seconds of clock tolerance, and, when configured, requiresissto equaljwt-issuer,audto equaljwt-audience, and thescopeorscpclaim to containrequired-scope. A failure returns401with aWWW-Authenticateheader pointing to the metadata document below. - Size and depth. The body may be at most
max-request-bytes(413otherwise) and JSON may nest at mostmax-json-depthlevels (400). - Well-formed JSON-RPC. The
Content-Typemust beapplication/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 thanjsonrpc,id,methodandparamsare refused, and fortools/call, parameters other thanname,argumentsand_metaare refused. The gateway then forwards a re-encoded copy containing only the accepted fields, so the upstream sees exactly what was checked. - Tool policy on
tools/call. The tool name inparams.nameis checked againstdeny-toolsfirst, thenallow-tools. A match indeny-tools, or no match inallow-tools, returns403with JSON-RPC error code-32003. - 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
subonce verified. Raw tokens are never logged; for unauthenticated requests only the authorization scheme is recorded, as inBearer [REDACTED]. - In tool arguments, any key containing
password,secret,token,apikey,authorization,credential,privatekey,cookie,bearer,session,jwtorsignature(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 warningW006.
Directive reference
mcp-gateway goes inside a route and takes the upstream as a property: upstream="https://...".
| Directive | Default | Meaning |
|---|---|---|
upstream (property) | required | URL of the MCP server. |
allow-tools | required | Tool name patterns that may be called. An empty list is an error (E403). "*" without any deny-tools warns (W006). |
deny-tools | none | Tool name patterns that are always refused. |
jwt-public-key | none | Ed25519 key for token signatures: "ed25519:/path" or "miraserve-ed25519-pub:<base64>". |
jwks-url | none | JWKS 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-issuer | none | Required iss. Required when oauth-resource-metadata is on. |
jwt-audience | none | Required aud. |
required-scope | none | A scope the token must carry. |
oauth-resource-metadata | #true | Require 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-depth | 32 | Maximum JSON nesting, 1 to 128. |
max-request-bytes | 1 MB | Maximum 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.checkwarns about this (W006) only when you usejwks-url, but it applies tojwt-public-keyas well. - Keep the allow list short and explicit, and add
deny-toolspatterns 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/callonly. Every other method, such asresources/read,prompts/getorinitialize, is authenticated and size-checked but then forwarded unchanged, and is recorded asallowin 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
GETthat 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-scopeorjwt-audiencevalues 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.