Est.

Building a Lightweight MCP Proxy in Code That Owns Routing, Policy, and Structured Tool Call Logs

A header-routed proxy enforces tool policy and logs without parsing bodies.

· 9 min read
Cover illustration for “Building a Lightweight MCP Proxy in Code That Owns Routing, Policy, and Structured Tool Call Logs”
MCP Server Management · November 28, 2026 · 9 min read · 1,974 words

An MCP gateway is a layer between AI agents and MCP servers that authenticates callers, applies access policy, and produces audit records. This walkthrough explains how a lightweight proxy can take on routing, policy enforcement, and structured tool call logs using the headers introduced by the 2026-07-28 MCP revision. A small platform team can build a governable layer in code without waiting for a commercial gateway.

What the 2026-07-28 MCP spec change actually gives a proxy to work with

The 2026-07-28 MCP specification revision moves the information needed to classify a request into its HTTP headers. Before this revision, classifying a POST to /mcp required buffering and parsing the JSON-RPC body. That put deep packet inspection on the routing path. Now Mcp-Method identifies the JSON-RPC method, while Mcp-Name identifies the targeted tool, prompt, or resource. The proxy can choose where to send the request before it reads the body.

The Mcp-Param-{Name} family extends that mechanism to primitive arguments annotated with x-mcp-header. A routing decision can therefore use an exposed argument, such as region. The headers provide the signals needed for routing and policy, while the body remains the request the upstream server processes.

The same revision removes protocol-level sessions and the Mcp-Session-Id header from Streamable HTTP. Every request is self-describing and stateless at the protocol level, so any compatible replica can receive it without a session handshake. Sticky-session machinery is no longer needed for that purpose. Together, these changes give the proxy a small, explicit routing envelope instead of a body to excavate and a session to remember.

Why proxy and gateway are different things, and which one this walkthrough builds

An MCP proxy moves traffic, while an MCP gateway governs it. A proxy can bridge stdio and Streamable HTTP, aggregate servers behind one endpoint, and forward messages. A gateway adds caller authentication, policy for each user and tool, a registry of reviewed servers, and audit records. Neither name has official standing in the MCP specification. These names describe how systems are deployed without adding participants to the protocol.

The data path here is client → proxy → upstream pool. That single endpoint provides the entry point for an agent using multiple internal MCP servers, while the proxy selects the approved upstream. The build starts with header-based routing and adds budgets, credential separation, and structured logs. It has no IdP integration or multi-tenant RBAC, and its scope is a working layer that a small platform team can ship in a day, then extend or hand off later.

The header-body agreement rule and the correctness traps it sets

The headers mirror the body. A server that processes the body must reject a request when a mirrored header disagrees with the corresponding body value. The HTTP response for that mismatch is 400. A proxy that changes Mcp-Name has not redirected the operation to another tool. It has made the request inconsistent, so the routing layer must read the headers and stream the body through unchanged.

Decoding comes before comparison, including comparison with a denylist. The specification defines the Base64 sentinel =?base64?<payload>?= for encoded values and requires inspecting intermediaries to decode them. A denylist check against the raw header can miss a name containing a leading space or a non-ASCII character. The decoding function therefore recognizes that sentinel and decodes its payload before returning the value for comparison. The same requirement applies to inspected Mcp-Param-{Name} values.

Missing headers create a separate failure path. If Mcp-Method is absent, the proxy must return 400. Header editing is equally unsafe for arguments. In the supplied region-mismatch example, changing the header to eu-west1 while leaving us-west1 in the body produces HTTP 400 from the upstream. Finally, stateless transport does not make a state-changing operation safe to repeat. The proxy must not retry tools/call without application-level confirmation of idempotency.

Building the routing layer: header reads, backend pools, and the denylist

Diagram: The Five-Step decide() Function: From Headers to Destination. Visualizes: Show the sequential decision logic inside the proxy's single `decide(headers)` function, which is the request's sole decision point.

The routing layer centers on a single decide(headers) function. It reads mcp-method, decodes mcp-name, checks the denylist, checks the budget, and returns either a denial code or a port or pool assignment. This is the request’s decision point. Keeping those checks together makes the selected destination depend on the same policy evaluation that permits forwarding, rather than on a later check after the body has been read.

The denylist is a Set of decoded names. A match produces 403 with a JSON-RPC error body, never a silent forward. The handler must also reject an unsupported value in MCP-Protocol-Version, rather than send the request upstream and leave the client with an opaque failure. Once forwarding is allowed, the handler connects to the chosen upstream and uses req.pipe(upstream) to stream the body. Routing never buffers or parses that body.

Aggregation introduces a constraint that a single-server proxy avoids. Bare tool names are unique only within their originating server, so duplicate names need stable prefixes or namespaces and a map back to the approved upstream. That map identifies the destination. It is not permission to rewrite a mirrored header while leaving the body untouched.

The supplied six-call test output shows what can be checked. Each call reports its routing or denial result and bodyBytesReadBeforeRouting, so the routing decision can be seen without showing the payload. The region-rewrite case also exposes an important boundary. A proxy can make a routing choice from a header, but the upstream still rejects a header-body contradiction.

Adding policy enforcement: per-tool budgets, token isolation, and the control/data plane split

The same decision function should check per-tool budgets. The spend map increments before forwarding and denies a request on overage, so the budget is part of admission. This keeps enforcement on the header path. Reading the body first would surrender the main advantage of the design before the policy had even made its decision.

Configuration needs a different path from requests. The control plane manages server identity, policy snapshots, and credential rotation, while the data plane validates and routes against immutable snapshots of that configuration. Ordinary agents must not be able to register servers, alter gateway settings, or widen their permissions. The admin path therefore needs its own protection, separate from the data path. An agent asking to use a tool is not also applying for the keys to the routing table.

Token isolation is the non-negotiable part of this extension. The inbound bearer token must never pass through to an upstream MCP server. The proxy validates its issuer and audience, then issues a separate credential scoped to that upstream. The credentials serve different trust boundaries.

Discovery must reflect the same access policy. The tools/list response should show only the tools the calling identity may see, and direct calls to forbidden tools must also be blocked. Hiding a name is not access control. Tool descriptions are also untrusted input because a compromised upstream can use them for prompt injection, so the proxy should pass only fields required by the approved tool schema. This filtering handles the response, separate from the zero-body-parse request routing.

Zuplo’s public beta illustrates how these controls can compose around a standard route handler. Its inbound policies include MCP OAuth, MCP Auth0 OAuth, MCP Token Exchange, and MCP Capability Filter. Those policies are a production reference for extending the same pattern.

Structured tool call logs built entirely from headers

The routing function already has the fields needed for a structured call record. At its return path, the proxy can emit the method, decoded name, region or other safe decoded parameter values, selected destination, denial code if present, and bodyBytesReadBeforeRouting. No extra body parsing is needed for that record. Logging becomes a byproduct of the decision rather than a second system trying to reconstruct what the router did.

The audit record must still be selective. Credentials, full request bodies, and sensitive argument values do not belong in it, even when an argument is available in a header. Safe decoded tool names, routed pools, denial reasons, and correlation IDs provide the useful trail. Header visibility is not permission to retain everything. The same restraint applies whether the request succeeds or is refused.

The 2026-07-28 revision deprecated protocol-level Logging, while OpenTelemetry’s GenAI semantic conventions define MCP span names, attributes, and metrics. Those conventions are still at Development status and have yet to become stable. Mapping structured records to their attribute names supports compatibility with downstream observability stacks without pretending the naming contract is settled. The proxy is also the natural place to open and close the client span for what the agent requested and the server span for what the upstream received.

The resulting records support alerts for repeated denials from one identity, sharp increases in a principal’s tool-call volume, and use of an expired credential. Those alerts also need details about the identity and credential beyond the routing record built from headers. The gain is inexpensive classification at scale. A body-parsing approach has to pay to inspect each payload to get the same view of routing and denials.

What breaks when you skip the governed registry and let tools self-register

A routing table is only as trustworthy as its admission rules. If any server can claim a tool name and receive traffic, the proxy amplifies shadow MCP. Its log may show exactly where the request went without showing that it was approved to go there. A reviewed registry gives the router a set of approved server identities to choose from.

The visibility gap begins outside the proxy. Every MCP server a developer adds to a coding agent creates another path from internal systems to a model, using that developer’s credentials and escaping controls designed for other traffic. Teams that believed they had only a handful of servers have discovered many times more during audits. A registry helps close that gap only if it lists servers that have been reviewed.

The routing table must therefore be keyed on configured server identity. Stable namespacing ties duplicate tool names to the approved servers they came from, so a legitimate database server and a shadow server claiming the same name cannot leave it unclear where db_query should go. Registration is a control-plane operation. The data plane accepts only the destinations in its immutable configuration snapshot, which prevents an ordinary agent from changing where future calls go.

Where the lightweight proxy ends and an enterprise gateway begins

The lightweight proxy owns a defined set of controls. It provides zero-body-parse routing, a decode-safe denylist, per-tool budgets, per-call structured logs, capability filtering, and separation between inbound and upstream credentials. These are useful governance functions in their own right. They do not, however, bind agent identity to an existing IdP such as Okta or Microsoft Entra ID, or provide multi-tenant RBAC across many teams.

The remaining gap is identity and authorization infrastructure. This build does not issue short-lived, task-scoped credentials through an OAuth 2.1 flow or support Enterprise-Managed Authorization. That feature, promoted to stable in June 2026, lets an organization’s SSO provision which MCP servers each role may reach. Teams that need those controls need more than a small routing service. Token separation alone is not identity federation.

The handoff becomes appropriate when many clients or teams use many servers, access must be isolated per user or tenant, or compliance requires a central audit trail attributed to individuals. Extending the proxy in-house preserves the code-first approach, while Zuplo offers the composable policy pattern described earlier. Cloudflare Gateway offers richer HTTP logging and DLP scanning for MCP server portal traffic. Those capabilities are distinct criteria.

The practical starting architecture remains a protected control plane, a reviewed registry, and a data plane that reads headers, enforces policy, isolates credentials, and records decisions. When broader identity requirements arrive, the router, denylist, and audit records remain reusable whether the team extends the implementation or moves to a managed gateway. The useful boundary is explicit responsibility. A lightweight proxy earns trust by enforcing the controls it owns and making the controls it lacks unmistakable.

Sources

  1. Route MCP server portal traffic through Cloudflare Gateway · Changelog

More in MCP Server Management