Dev.to Security 🔐 Cybersecurity 👁 0 📖 5 min read

Securing MCP Tools with an Enterprise Gateway

When you test Model Context Protocol (MCP) tools locally, you usually launch a process on your laptop. Your desktop client runs a local command over standard input and output (stdio). That workflow is simple for one dev

When you test Model Context Protocol (MCP) tools locally, you usually launch a process on your laptop. Your desktop client runs a local command over standard input and output (stdio).

That workflow is simple for one developer. The trouble starts when several teams need the same internal tool. You cannot safely distribute production database credentials and internal API keys to every developer's laptop community scaling discussions.

To share tools safely, you need to run them on private networks behind a central gateway. If you build that gateway like a basic reverse proxy, you create immediate security hazards. Let us look at what breaks, and how to build a proper policy gateway.

The naive proxy trap

The most common first attempt is a lightweight Express or Node proxy. The client sends a JSON-RPC request over HTTP, and the proxy forwards it straight to an internal tool:

// Naive forwarding proxy: illustrative anti-pattern
import express from "express";
import axios from "axios";

const app = express();
app.use(express.json());

app.post("/mcp", async (req, res) => {
  const response = await axios.post("http://internal-orders-mcp:8080", req.body, {
    headers: { Authorization: req.headers.authorization }
  });
  res.json(response.data);
});

app.listen(3000);

This forwards requests, but it introduces three critical flaws.

First, it passes the incoming client credential straight through to the downstream server. In MCP, forwarding user tokens directly creates confused deputy vulnerabilities. The official specification states that downstream token passthrough is forbidden MCP auth spec. Downstream servers must receive scoped service tokens, not raw user credentials.

Second, the proxy does not evaluate tool permissions. An OAuth token verifies who connected over HTTP, but it does not restrict what actions they can take. An agent querying read-only order status has the exact same network access to run destructive schema updates AuthZed action-level models.

Finally, connecting local environments to untrusted remote tools carries direct host risks. In mcp-remote, JFrog disclosed CVE-2025-6514, an OS command injection flaw where an untrusted OAuth endpoint was passed to the system shell JFrog advisory. Trusting remote tool responses or connection metadata without boundary checks leaves developers open to host compromise.

Moving the policy boundary to the gateway

A secure gateway is not a simple pipe. It is a policy enforcement point that intercepts and validates every JSON-RPC message before contacting backend tools.

Because MCP clients communicate using JSON-RPC 2.0 over HTTP, any error returned by the gateway for a request containing an id must use HTTP 200 with a standard JSON-RPC error payload JSON-RPC HTTP transport spec. In addition, error code -32001 is reserved in the MCP SDK for request timeouts, so custom authorisation denials should use unreserved application error codes such as -32003 MCP protocol error definitions.

A hardened gateway handles four essential tasks:

  1. It filters tools/list so users only discover tools permitted for their role, always including the required inputSchema.
  2. It verifies tools/call to ensure the caller has permission to execute that specific action.
  3. It verifies manifest hashes to ensure downstream tools match approved schemas registered in version control.
  4. It validates input parameters against a strict schema and strips raw client tokens before dispatching to internal services.

You can explore these tool boundaries in depth in the CodeReviewLab MCP security guide.

Here is an illustrative gateway route that enforces these controls:

// Hardened gateway route: action checks, manifest hashing, and token stripping
app.post("/v1/mcp", async (req: Request, res: Response) => {
  const { id, method, params } = req.body;
  const user = req.user; // Verified OAuth identity context

  if (method !== "tools/call") {
    return res.json({ jsonrpc: "2.0", id, error: { code: -32601, message: "Method unsupported" } });
  }

  const toolMeta = TOOL_REGISTRY[params?.name];
  if (!toolMeta || !user.roles.includes(toolMeta.role)) {
    return res.json({ jsonrpc: "2.0", id, error: { code: -32003, message: "Action forbidden" } });
  }

  const currentHash = crypto.createHash("sha256").update(JSON.stringify(toolMeta.schema)).digest("hex");
  if (currentHash !== toolMeta.schemaHash) {
    return res.json({ jsonrpc: "2.0", id, error: { code: -32003, message: "Manifest integrity failed" } });
  }

  const validation = OrderParams.safeParse(params?.arguments);
  if (!validation.success) {
    return res.json({ jsonrpc: "2.0", id, error: { code: -32602, message: "Invalid params" } });
  }

  try {
    const upstream = await fetch(toolMeta.url, {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-MCP-User-Id": user.id },
      body: JSON.stringify(req.body)
    });
    return res.json(await upstream.json());
  } catch (err) {
    return res.json({ jsonrpc: "2.0", id, error: { code: -32603, message: "Upstream tool call failed" } });
  }
});

Why manifest pinning matters

In standard MCP setups, tool definitions can change dynamically at runtime. If an internal service is modified without review, it could rewrite its advertised tool description or alter parameter schemas.

We have seen how dangerous unpinned tooling configurations can be in client tools. In Cursor IDE (CVE-2025-54136, dubbed MCPoison), Check Point Research demonstrated that workspace configuration files in .cursor/mcp.json trusted servers solely by name Check Point Research. A collaborator could get a benign tool name approved, then alter the underlying executable command to run malicious binaries without re-prompting the user.

While CVE-2025-54136 affected local IDE workspace configuration trust, the broader lesson applies directly to remote gateways. An enterprise gateway should pin approved tool manifests and argument schemas in version control using cryptographic hashes. If a downstream server advertises an unapproved schema change, the gateway blocks it from being exposed to agents.

Identity provenance and token exchange

In the gateway code, we stripped the client's raw authorization token and attached an X-MCP-User-Id header instead.

This stops token passthrough, but it raises another question: how does the downstream microservice know that this header came from your trusted gateway, rather than another process on the internal network?

To solve this, use mutual TLS (mTLS) between the gateway and backend tools, or issue short-lived, signed service tokens. If you want to see how to prevent forged identity context on internal service meshes, take a look at the CodeReviewLab guide on identity provenance.

Where the gateway boundary stops

An enterprise gateway provides deterministic protection: strict role checks, schema validation, and credential isolation. But it cannot solve every security challenge on its own.

First, a gateway cannot eliminate indirect prompt injection. If an approved tool fetches a third-party webpage or ticket that contains hidden natural language instructions, those instructions pass through the JSON-RPC response untouched indirect injection research.

Second, tools that make outbound HTTP requests need network-level protection. In Azure MCP Server, Microsoft resolved CVE-2026-26118, an authenticated SSRF vulnerability that allowed callers to reach internal endpoints including the Azure Instance Metadata Service at 169.254.169.254 and extract managed identity tokens Microsoft MSRC advisory. Even with strict gateway parameter validation, tool execution containers must be isolated with egress firewall rules that block cloud metadata addresses and private subnets.

Enterprise MCP review checklist

When reviewing an MCP gateway implementation before shipping to production, verify these essential checks:

  • Token termination: The gateway terminates the caller's OAuth token and never passes raw user credentials downstream.
  • Protocol compliance: All error responses with an id return HTTP 200 and standard JSON-RPC objects, avoiding reserved codes like -32001.
  • Mandatory schemas: The tools/list handler returns only tools the authenticated user can see, with complete inputSchema definitions.
  • Action authorisation: The tools/call handler evaluates permissions and validates input arguments before dispatching.
  • Manifest pinning: Tool schemas are pinned in version control to prevent unreviewed runtime changes.
  • Egress controls: Subprocess runners and tool containers block outbound connections to cloud metadata services.
📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.