Front any MCP server (SaaS-hosted, public, or your own) with a governed MCP API instance on MuleSoft Flex/Omni Gateway and layer eleven out-of-box policies in a tested order: token metering, tool renaming, global allow/block, PII masking, Cedar ABAC, rate limiting, JSON threat and injection protection, logging. Includes where custom approval-binding, risk-gate and decoy policies slot in, plus live-verified checks (hidden deletes, masked phones, 429, 400) and honest limits.
Tags: api-security, cedar, api-manager, cross-industry, rate-limiting, mcp, flex-gateway, custom-policy, ai-agents, pii-masking, agent-governance, omni-gateway
Defense-in-Depth Policy Chain for MCP Servers You Don't Own, on Flex/Omni Gateway
Deliverable: A governed MCP API instance on MuleSoft Flex/Omni Gateway in front of any MCP server, hosted by a SaaS vendor, public, or your own, with an eleven-policy out-of-box chain in a defined order. Agents see a renamed, trimmed tool surface, destructive tools are hidden and refused, PII is masked, and abusive or malformed traffic is rejected, all without touching the upstream server.
Objective: Agents are being pointed at MCP servers their owners did not write: a SaaS platform's hosted MCP, a public documentation server, a partner's endpoint. Those servers expose whatever tools the vendor ships, including delete tools, return PII in clear, and give you no per-agent rate limit or audit trail. You cannot patch them, so the control has to sit in the path. Working looks like this: the same tools/call that reaches the vendor directly is, through the gateway, renamed, filtered, masked, metered and logged, and a call a policy forbids never leaves the gateway. Enforcement is claimed only for behaviors exercised against a live gateway; this is not a compliance certification.
What's Getting Built
- Governed MCP instance (API Manager, Agent and Tool Instances, type MCP server, one per upstream) — fronts an existing MCP server by URL; consumers call
POST /{base-path}/ with JSON-RPC (initialize, tools/list, tools/call)
- Identity and admission policies —
mcp-support (token metering), Header Removal, MCP Access Control (Cedar attribute-based rules), MCP Global Access (allow and block by tool name)
- Tool surface policies — MCP Tool Mapping (rename, shorten descriptions), MCP Payload Optimization (
mcp-tool-response-sanitization)
- Data and traffic protection policies — MCP PII Detector, Rate Limiting, JSON Threat Protection, Injection Protection
- Audit — Message Logging plus per-tool token metering from
mcp-support
- Optional custom layer (companion blueprints, not rebuilt here) — Approval-to-Execution Binding and Cross-Session Aggregate-Risk Gate; Honeytoken, Decoy Tool and Breadcrumb policies
Prerequisites
- A Flex or Omni Gateway that can reach the upstream, and API Manager rights to create and apply policies. A managed gateway reaches only upstreams with public IPs; an upstream in a private network gave an instant empty-body 503.
- For a SaaS-hosted MCP: that vendor's MCP activation and OAuth client. Hosted Salesforce MCP, for example, needed an External Client App using Authorization Code + PKCE (not a Connected App, not JWT bearer), the RFC 8707
resource parameter on both the authorize and token calls, and JWT-format access tokens enabled; opaque tokens return JWT Token is required.
- A named owner for the tool list (read, write, destructive). Deciding what to hide is the slow part.
- Time for a UI step: instance creation was only proven through the API Manager wizard.
Choose your path
- SaaS-hosted MCP with user identity — Choose this when the upstream is a vendor platform issuing per-user OAuth tokens. The client sends its own bearer and the gateway forwards it, so no secret is stored on the gateway and the identity the Cedar rules see is real. Outbound credential injection was not usable on MCP instances in this setup (see Troubleshooting); the Microsoft Entra On-Behalf-Of exchange was proven on a plain HTTP API instance, not an MCP one.
- Public third-party MCP — Choose this for a server you only consume, such as a public documentation MCP. Start minimal (
mcp-support, Message Logging), then add Global Access and Rate Limiting. You gain an audit trail and a cost meter for a tool you will never own.
- Your own MCP server — Choose this when you can still change the server. Keep authorization in the server too; use the gateway for what should not depend on each server team: metering, rate limits, threat protection, and the optional approval and decoy policies. One Mule app built with the MCP Connector hit a confirmed incompatibility with PII Detector (Troubleshooting).
Architecture
The diagram groups policies by role (request side, response side, custom); the table in step 2 is the execution order.
1. Register the upstream as an MCP instance
- In API Manager choose Agent and Tool Instances, Add, MCP Server (not "MCP Bridge", which converts a REST API into tools). Pick "Register a new MCP server", set a base path, and enter the upstream MCP URL in the Upstream URL field. Set the upstream once, in the UI; a UI Save and Apply overwrote an upstream changed through the API.
- Use one instance per exposure level: read-only and full-CRUD instances gave two clean allowlists.
- Routes are exact: most served MCP at
/{base-path}/ (the bare path returned 404), one at /{base-path}/mcp. Probe before blaming a policy.
- Every session is the streamable-HTTP handshake:
initialize (returns an Mcp-Session-Id header), notifications/initialized, then tools/list or tools/call with that header. Send Accept: application/json, text/event-stream. Replies may be plain JSON or SSE; time out on a held-open stream.
2. Apply the chain, one policy at a time
Apply each policy, confirm the instance shows the change applied, probe, then add the next. One bad or empty configuration can break the whole route (instant empty-body 503), and repeated edit-and-apply cycles corrupted one instance's route state until it was deleted and recreated. This is the order exercised live, lowest first:
| Order |
Policy |
Why it sits here |
| 0 |
MCP Support (mcp-support, 1.0.8 or later) |
Required for MCP handling; meters tokens per call. Below 1.0.8 an instance showed zero tokens. External-URL instances ship without it, so add it. |
| 1 |
Header Removal |
Strips inbound Accept-Encoding, so later body-inspecting policies can read uncompressed bodies (advice: that is the design intent; the strip itself was exercised). |
| 2 |
MCP Tool Mapping |
Renames tools and shortens descriptions before access rules run, so later rules see the final names. |
| 3 |
MCP Global Access |
Coarse allow and block by tool name (regex allow, literal block). Blocked tools vanish from tools/list and fail at call time. |
| 4 |
MCP PII Detector |
Masks listed entities in the response before the model sees them. |
| 5 |
MCP Payload Optimization |
Shapes responses: HTML to Markdown, strip base64, minimum size threshold. |
| 6 |
MCP Access Control (Cedar) |
Fine-grained allowlist by identity and tool. Runs after Tool Mapping, so permit both names of a renamed tool. |
| 7 |
Rate Limiting |
Caps calls per session, keyed on the mcp-session-id header. |
| 8 |
JSON Threat Protection |
Rejects pathological JSON before it reaches the upstream. |
| 9 |
Injection Protection |
Rejects SQL and XSS patterns in the body. |
| 10 |
Message Logging |
Per-call audit line. |
Advice, not proven: running 8 and 9 earlier is a sensible reordering. If you reorder, repeat every check below; Tool Mapping and Cedar interact by order.
3. Configure the coarse controls
- Global Access: allow everything by pattern, then block destructive tools by their raw upstream name.
{"rules":[{"rule":"Allow","match_type":"pattern","value":".*"},
{"rule":"Block","match_type":"literal","value":"deleteSobjectRecord"},
{"rule":"Block","match_type":"literal","value":"deleteRelatedRecord"}]}
- Tool Mapping:
{"logMappings":true,"toolMappings":[{"sourceToolName":"soqlQuery","mappedToolName":"salesforce_soqlQuery","mappedDescription":"{shorter description}","mappingType":"literal"}]}.
- Header Removal:
inboundHeaders: ["Accept-Encoding"]. PII Detector: {"entities":["Phone Number","Email"],"action":"Log and mask","customPatterns":[]}.
4. Configure the fine controls
- Cedar rules (MCP Access Control): set
authType to Other when callers present a JWT rather than a client ID. Write one permit per tool; deny comes by omission.
permit(principal, action == Action::"tools/list", resource);
permit(principal, action == Action::"tools/call", resource == Tool::"getUserInfo");
permit(principal, action == Action::"tools/call", resource == Tool::"salesforce_soqlQuery");
permit(principal, action == Action::"tools/call", resource == Tool::"soqlQuery");
permit(principal, action == Action::"tools/call", resource == Tool::"createSobjectRecord");
Traps: the list form [Tool::"a", ...].contains(resource) and resource.tool attribute references silently denied everything. A single permit(principal, action, resource); is a useful wiring check before you tighten. Writes were gated by tool identity in the verified build. Gating writes by an identity claim (such as an access-level attribute) needs that claim on the Cedar principal, which required a custom claims-enrichment policy that was not available; treat claim-based write gating as unproven.
- Rate Limiting: key on
#[attributes.headers['mcp-session-id']], 20 requests per 60000 ms, distributed, block on unknown quota. A new session gets a new budget; keying on identity is advice to evaluate.
- JSON Threat Protection:
maxContainerDepth 10, maxStringValueLength 8192, maxObjectEntryNameLength 256, maxObjectEntryCount 1000, maxArrayElementCount 1000.
- Injection Protection:
builtInProtections [sql, xss], protect path, query and body, reject requests.
- Message Logging:
itemData needs message, level, firstSection and secondSection all set. An empty {} configuration broke the route.
5. Add the custom layer (optional)
Build these only after the out-of-box chain is stable. They are separate blueprints: Agent Tool-Call Authorization Integrity: Approval Binding and Aggregate-Risk Gate on Flex/Omni Gateway and Cyber-Deception for AI Agent and MCP Traffic: Honeytoken, Decoy-Tool and Breadcrumb Policies on Flex Gateway. Where they slot in:
- After the admission policies (
mcp-support, mcp-access-control) and before the call reaches the upstream.
- Approval binding first (reject an altered or unapproved action before it consumes budget), then the aggregate-risk gate.
- Deception policies run after the standard MCP policies. The custom filters share no state.
- They gate MCP
tools/call only, not agent-to-agent or model-proxy traffic. Start each in monitor mode.
6. Security and compliance
- Identity: the verified model is pass-through. The client's token is forwarded and the gateway stores no upstream secret.
- What the chain is: layered, independent controls that each narrow what an agent can discover, call, receive or repeat. None certifies compliance with any framework.
- Data: masking happened before the response left the gateway and was shown for phone numbers; test other entities on your data.
- Logging: Message Logging writes what your expression writes; never log bearer tokens or full payloads. Ingestion lagged by minutes, and one sub-path route logged nothing while its metrics dashboard still counted calls.
- Limit: policies do not understand tool semantics; a read tool that returns secrets, or an allowed write tool, remains your risk.
Sample payload — one session through the governed endpoint
Standard JSON-RPC after initialize and notifications/initialized, with Authorization: Bearer {user-token}, Accept: application/json, text/event-stream and Mcp-Session-Id: {session-id}.
tools/list through the gateway returned 9 tools where the upstream returned 11: the two delete tools are absent and soqlQuery appears as salesforce_soqlQuery.
Allowed, renamed, masked:
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"salesforce_soqlQuery",
"arguments":{"q":"SELECT Name, Phone FROM Contact WHERE Phone != null LIMIT 3"}}}
Direct to the vendor a row carried "Phone":"(875) 555-6626". Through the gateway the same row carried "Phone":"(*******626". The surrounding result envelope is the vendor's and is not reproduced here.
Hidden and blocked (arguments are irrelevant; the call never reaches the upstream):
{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"deleteSobjectRecord","arguments":{}}}
{"jsonrpc":"2.0","id":4,"error":{"code":-32008,"message":"Access denied to: deleteSobjectRecord"}}
A tool outside the Cedar allowlist (find in the live build) returned the same -32008 form. The 21st call on one Mcp-Session-Id inside 60 seconds returned HTTP 429. A body containing a SQL injection pattern returned HTTP 400 with header x-injection-protection: blocked. A 15-level nested JSON body returned HTTP 400.
Deterministic checks
tools/list through the gateway omits every Global-Access-blocked tool; calling one returns -32008 Access denied to: {tool} and the upstream sees nothing.
- A renamed tool lists under the mapped name, and a call under the mapped name reaches the upstream.
- A tool absent from the Cedar allowlist returns
-32008; permitted read and write tools reach the upstream. A write reaching the vendor can still fail the vendor's own validation.
- A phone number in a tool result is masked through the gateway and clear on the same call made directly.
- Exactly 20 calls on one
Mcp-Session-Id in 60 seconds succeed; the 21st returns 429. On an instance configured to expose them, the response carries x-ratelimit-limit, x-ratelimit-remaining and x-ratelimit-reset.
- A body with SQL injection content returns
400 with x-injection-protection: blocked; JSON nested deeper than 10 returns 400.
- With
mcp-support at 1.0.8 or later, tokens appear on the Cost Management dashboard; volume tracks tools/list descriptions more than calls.
Testing and validation
- Raw versus governed: run the same four calls directly and through the gateway (list, allowed read, delete, PII read) and diff the output. This is the acceptance test.
- One change at a time: after each policy, probe
initialize, tools/list and one tools/call. An instant empty-body 503 means a bad configuration or corrupted instance, not an upstream fault; a slow 503 or timeout means the gateway tried and failed to reach the upstream.
- Rename and session: with Cedar active, call a renamed tool under both names; test the rate limit from one session and from a fresh one.
- Gaps: claim-based write gating unproven; masking proven on one vendor's response envelope; rate-limit enforcement inconsistent across runs.
Phased rollout
Phase 1 — Connect
- Register the instance, add
mcp-support and Message Logging, confirm tokens and audit lines, inventory tools.
Phase 2 — Restrict
- Add Tool Mapping, Global Access and Cedar on a read-only instance, run the raw-versus-governed diff, then the remaining policies.
Phase 3 — Extend
- Open a write-capable instance only after allowlist sign-off. Add custom policies in
monitor mode, then block on reviewed traffic.
Success metrics
- Share of agent MCP traffic going through a governed instance.
- Blocked-tool calls,
429s, 400s and Cedar denials per instance (what policies saw, not prevented loss).
- Tools exposed versus tools upstream; tokens per
tools/list.
Troubleshooting
- Instant empty-body 503 right after a policy change — Likely cause: an empty or invalid policy configuration (Message Logging with
{} was one), or route state corrupted by repeated edit-and-apply cycles. Fix: remove the last policy; if the instance stays dead, delete and recreate it.
- 404 on the route — Likely cause: missing trailing slash or sub-path. Fix: probe both forms.
- Policy applied but not enforcing — Likely cause: the change reached the management layer but not the running gateway. Redeploying the deployment record through the REST API did not push policy changes in one test and a UI Save and Apply was needed; in another run, policies posted through the API took effect without it. Fix: treat only an applied status plus a probe as proof.
- No 429 on an earlier route — A first attempt (60 per 60 seconds keyed on client ID, 65 rapid calls) saw none; the later 20 per 60 seconds session-keyed configuration enforced. Cause not isolated. Fix: test the limit on your own instance.
- Masking returns empty responses on a Mule MCP Connector upstream — The same PII Detector configuration masked correctly on a vendor-hosted server. Suspected cause: the tool-response envelope; unresolved. Fix: add PII Detector last, test, and be ready to remove it.
- Credential injection causes 503 on an MCP instance — The outbound API-key policy is not supported on MCP instances. Fix: pass the client token through, or inject credentials in a front HTTP API.
- Cedar denies everything — Likely cause: list-form or attribute-form rules. Fix: one
permit per tool.
- Upstream unreachable — Likely cause: private-network host. Fix: use a public upstream.