Build, configure, test and roll out two custom Rust/WASM PDK policies for MCP tool calls on MuleSoft Flex/Omni Gateway: Approval-to-Execution Binding (the executed call must be the approved call: action, canonical arguments, freshness, separate attester, optional single-use nonce) and a Cross-Session Aggregate-Risk Gate (reserve-then-authorize against a shared exposure budget). Covers chain order, monitor-to-block rollout, fail-closed behavior, and honest limits: per-replica state, symmetric HMAC, no certification claim.
Tags: flex-gateway, omni-gateway, pdk, custom-policy, rust, webassembly, mcp, ai-agents, agent-governance, authorization, api-security, api-manager
Agent Tool-Call Authorization Integrity: Approval Binding and Aggregate-Risk Gate on Flex/Omni Gateway
Deliverable: Two custom Rust/WebAssembly policies built with the Flex Gateway Policy Development Kit (PDK) and applied to an MCP API instance, so an AI agent's tools/call is executed only if it is the exact call a separate party approved, and only if it fits a shared exposure budget, with the upstream tool never reached when either check fails.
Objective: Authorizing each agent tool call on its own is not enough. An approval is granted for one action and the call that finally executes can differ: another tool, changed arguments, an expired or replayed approval, or an approval attested only by the executor itself. Separately, every call can clear its own per-session cap while the calls added together, across sessions, blow past an exposure budget nobody decided on. A per-call gate sees one call and catches neither. This blueprint covers building, configuring, deploying, testing and rolling out two gateway checks that do.
What's Getting Built
- Approval-to-Execution Binding (custom inbound PDK policy, MCP API instances) — on
tools/call only, checks the approval record carried with the call against predicates P1 action, P2 canonical argument bytes, P4 freshness, P5 separate attester, and opt-in P6 single use · applied to POST {mcp-route}
- Cross-Session Aggregate-Risk Gate (custom inbound PDK policy, MCP API instances) — reserves each governed call's contribution against a per-scope budget before forwarding, commits on a 2xx/3xx upstream response, releases on 4xx/5xx · applied to
POST {mcp-route}
Prerequisites
- An Anypoint organization that can publish custom policies to Exchange and apply them in API Manager, and a connected Flex/Omni Gateway fronting the MCP server. Both policies declare
assetTypes: mcp; no agent-to-agent or model-proxy coverage is claimed.
- An authentication policy that sets verified identity before these two run (Client ID Enforcement, JWT Validation or OAuth introspection). Both policies key on verified authentication data, never on a caller-set header.
- A separate approver service that signs approval envelopes with HMAC-SHA256 under an identity different from the executing agent. This is usually the long pole.
- Toolchain as stated by the reference: Rust 1.89.0 with
wasm32-wasip1, PDK 1.10.0, Docker; tested on Flex Gateway 1.14.0. Check current releases and re-run tests before upgrading.
- The open-source reference implementation (MIT, the package URL) as the starting point. It ships source only, so you build and publish under your own organization.
Choose your path
- Deploy from P4A or build from source — Both policies are listed on the P4A (Policies for Agents) marketplace: Approval-to-Execution Binding and Cross-Session Aggregate-Risk Gate. P4A publishes and deploys them to your Anypoint organization, which skips the build and Exchange publishing steps. Build from source when you must pin a release tag, change the code, or run your own CI; the listings track the repository's main branch.
- Binding only (P1, P2, P4, P5) — the risk is a swapped or stale approval and approval reuse is acceptable. It keeps no cross-call state, so replica count does not matter.
- Binding plus P6 single use — each approval must authorize exactly one execution and you can run one gateway replica for the route. The nonce store is node-local, so a replay can succeed on a second replica or after a restart.
- Aggregate gate only — no approval exists but you need a ceiling on spend, tokens or calls per agent, tenant or fabric.
- Both, binding first — an altered or unapproved call is rejected before it consumes budget.
- On MCP traffic — put the out-of-box MCP policy chain in place first, as in the companion blueprint "Defense-in-Depth Policy Chain for MCP Servers You Don't Own, on Flex/Omni Gateway", and add these as its optional custom layer. "Cyber-Deception for AI Agent and MCP Traffic: Honeytoken, Decoy-Tool and Breadcrumb Policies on Flex Gateway" covers the detection side of the same layer.
Architecture
1. Build and test both policies from source
- Each policy is its own PDK project with its own lockfile; there is no workspace-wide build. Per policy:
cargo +1.89.0 test --lib --locked, then cargo +1.89.0 build --release --target wasm32-wasip1 --locked. Run cargo fmt --check and cargo clippy --lib --locked -- -D warnings in CI, and the Docker-based integration tests (a real Flex Gateway container) before every release.
- Set your Anypoint organization id as
group_id in each policy's Cargo.toml, and keep that change out of any public fork. Regenerate Exchange assets with make build, fail CI if generated configuration drifts from the policy definition, publish a development version with make publish and a production one with make release.
2. Configure Approval-to-Execution Binding
approvalSource: header (one JSON object in the header named by approvalHeader, default x-approval) or rpc-param (a top-level body member named by approvalRpcField, default approvalBinding; JSON-RPC member names are rejected). sidecar is not implemented and fails startup, so it cannot look like an armed binding. With rpc-param, keep stripApprovalEnvelope: true so the MCP server never sees the approval or MACs.
requiredPredicates: [P1, P2, P4, P5]. An empty list is rejected. Add P6 only per the path above, and always with P4.
- P5 needs
attesterKeys (kid, key, at least 32 bytes) and non-empty expectedAudience, expectedTenant, expectedEnvironment. The MAC covers a versioned mcp-v1 payload: v, iss, aud, tenant, env, sub (the verified executor), action, arguments_digest, not_after, nonce. This stops an approval for one gateway, tenant or environment verifying at another, and makes the attester separate from the executor.
- Set
maxApprovalLifetimeSeconds (for example 900); without it an attested not_after years away is accepted. It bounds remaining lifetime on the gateway clock, not total. Keep clockSkewSeconds small (default 60, max 3600).
- The executor comes first from verified authentication data (
client_id, then principal); executorHeader is a fallback only, and with P5 required and no verified subject the call is denied.
clientResponses: by default (forward) a client's reply to a server-initiated roots/list, sampling or elicitation request passes through unbound by the approval. Set deny if approvals must cover that input; it breaks those MCP features.
3. Define canonical form in the approver
- Compute
arguments_digest as lowercase hex SHA-256 over a fail-closed subset of RFC 8785 JCS: members sorted by key, compact separators, only objects, arrays, strings, booleans, null and integers (equivalent to Python json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)). Absent arguments is the empty object.
- The policy rejects what it cannot canonicalize: non-integer numbers, integers beyond plus or minus 2^53 minus 1, and objects whose key order differs between UTF-8 and UTF-16 ordering. Keep arguments to strings and integers; carry decimals as minor units.
- Approvals carry
scope.action, scope.arguments_digest, not_after (RFC 3339) and, for P6, a unique nonce. Arguments containing a $ref object are denied under P2.
4. Configure the Aggregate-Risk Gate
budgetScope: agent (one total per verified identity), tenant, or fabric (one total for everything the instance sees). Keep identitySource: authentication (identityField client_id, principal or properties.<dot.path>). trusted-header is safe only if an earlier policy strips the caller's copy and injects the verified value; the gate cannot check that.
contribution and aggregateBudget share one unit: fixed-weight (fixedWeight points), spend-amount (integer minor units at spendAmountField, default params.amount, in spendCurrency) or estimated-token-weight (a fixed estimatedTokens charge; real usage is never read, so size it conservatively). Budgets are exact integers, 0 to 2^53 minus 1.
- Leave
governedMethods at ["tools/call"]. initialize, ping, tools/list, notifications, teardown and client responses are forwarded uncharged (pass;reason=ungoverned-method), so an exhausted budget never blocks session setup or cancellation.
- Set
scopeDigestKey from a secret (empty leaves digests unkeyed). Changing it, window or windowMs starts every scope at zero.
- Set
reservationTimeoutMs (default 60000) above twice the longest upstream time a client can provoke, or a slow call can settle uncharged.
- Settlement uses HTTP status only: 2xx/3xx commit, 4xx/5xx release; an error inside an HTTP 200 is still charged.
- Window:
fixed-period resets totals every windowMs from the Unix epoch (24-hour windows start 00:00 UTC); worker-lifetime never resets until the ledger is lost.
- Keep
ledgerBackend: node (all workers of a replica share one compare-and-swap ledger). worker lets a caller multiply the budget across Envoy workers; cluster is not implemented and is rejected.
5. Order the chain and deploy
- Order: authentication, MCP admission (
mcp-support, mcp-access-control), Approval-to-Execution Binding, Aggregate-Risk Gate. The filters are independent: no shared state, no control state passed in headers.
- Start both in
mode: monitor (the default): every verdict is recorded but the call is always forwarded. Move to block after reviewing real traffic.
- Apply with a UI Save and Apply in API Manager; a change made only through the REST API is not reliably pushed to a running gateway, so do not count it as enforced until the deployment shows applied.
- Both signal a policy violation on a failed predicate or budget breach in either mode, so monitoring sees would-deny events.
6. Security and compliance
- Claim boundary, binding: it checks that the record proves the executed call is the approved one. It does not prove approving it was wise or that the attester was entitled to. P5 uses a symmetric HMAC: separation of duties, not non-repudiation, since the gateway holds the verifying key.
- Claim boundary, gate: it bounds exposure per gateway replica, not globally. Framework mappings (NIST, OWASP, EU AI Act, AIUC-1) are design context, not certification.
- Inspection is bounded: JSON-RPC bodies up to 64 KiB with a declared
content-length, application/json, UTF-8, no content-encoding. Paths, query strings and other headers are never inspected.
- Never log envelopes, MACs, keys or arguments. Verdict headers carry only predicate codes, or a scope pseudonym and numeric totals, so they are safe to forward to SIEM.
Sample payload — one policy configuration, an allowed call, a denied call
Binding configuration (secrets from your store):
- policyRef:
name: approval-execution-binding-v1-0-impl
config:
approvalSource: header
approvalHeader: x-approval
requiredPredicates: [P1, P2, P4, P5]
attesterKeys:
- kid: approver.example
key: "{attester-key-from-secret-store}"
clockSkewSeconds: 60
maxApprovalLifetimeSeconds: 900
expectedAudience: mcp-gateway-prod
expectedTenant: "{tenant}"
expectedEnvironment: prod
mode: block
Gate configuration (calls of 800 against a budget of 3000):
- policyRef:
name: aggregate-risk-gate-v1-0-impl
config:
budgetScope: agent
identitySource: authentication
scopeDigestKey: "{digest-key-from-secret-store}"
aggregateBudget: 3000
contribution: fixed-weight
fixedWeight: 800
governedMethods: [tools/call]
mode: block
Approval envelope in x-approval (the digest is SHA-256 of the canonical form of {"replicas":3,"service":"checkout"}):
{"approval":{"scope":{"action":"deploy.scale","arguments_digest":"f7b3f0e4e5d3887c08a64cd0bd4b35f5e7867c8d19a2fc5d76172e91ea082cf2"},
"not_after":"{rfc3339-timestamp}","nonce":"n-0003"},
"attestations":[{"claim":"approval","authority":"approver.example","mac":"{hmac-sha256-hex}"}]}
Allowed: a tools/call for deploy.scale with {"service":"checkout","replicas":3} is forwarded with x-approval-binding: allowed.
Denied: the same envelope with "replicas":300 (digest differs) fails P2. The call never reaches the upstream and returns HTTP 200 with the error in-band, stamped x-approval-binding: denied;predicate=P2:
{"jsonrpc":"2.0","id":1,"error":{"code":-32008,"message":"approval-to-execution binding denied (P2)"}}
Gate: the first three 800-unit calls from one client commit (allowed;scope=...;contribution=800;total=2400/3000;unit=points;settlement=committed). The fourth is refused with denied;scope=...;would-be-total=3200;budget=3000;unit=points and the same -32008 code.
Deterministic checks
- A
tools/call whose action, argument digest or any signed claim (aud, tenant, env, sub, not_after, nonce) differs from the attested approval is denied (-32008 in-band with HTTP 200, or empty 403), stamped with the failed predicate, with zero upstream hits.
- A missing approval, malformed envelope, or attestation from an unlisted authority fails closed in
block mode: under P5 when required, otherwise the first required predicate.
- Order is fixed: P5, P6 presence, P1/P2, P4. P6 reserves the nonce only when the call is forwarded, so a denied attempt never burns it.
- Non-
tools/call methods are forwarded stamped out-of-scope. Batches, duplicate members and bodies nested past 128 levels are denied as malformed in block mode; a POST without a valid content-length of at most 64 KiB is denied denied;framing=content-length.
- Gate: with budget 3000 and contribution 800, exactly three of any concurrent burst from one scope are admitted across all workers.
- Library suites pass on a locked toolchain (the reference reports 116 binding and 209 gate tests) and the integration suite passes on a real gateway container.
Testing and validation
- Happy path: a signed call from an authenticated agent hits the upstream once, reads
allowed, and raises the gate total by the contribution.
- Canonical form: approver and gateway must produce byte-identical digests. Test shuffled key order, unicode, integers near 2^53, and floats (which must be rejected, not rounded).
- Identity: a call with no authentication data (binding denies under P5; gate
reason=missing-identity), and a caller-set executor header with no verified subject (not trusted).
- Concurrency: burst one scope across workers; a read-then-write counter over-admits, this ledger admits exactly the budget.
- Replica and restart: with P6, replay an approval on a second replica and after a restart; it reopens.
- Fail closed: a missing, malformed or unparseable approval, or absent
not_after, is denied; expiry is judged only on the gateway clock, never a caller-supplied time. A full or erroring P6 nonce store denies. On the gate, store errors give reason=ledger-unavailable, retry exhaustion ledger-contention, a reservation already past deadline stale-admission, a full scope table scope-capacity or scope-saturated; monitor forwards and stamps these. Gaps: a host storage error on the nonce store could not be induced on a real gateway (inspection only); a clock reading 0 disables the gate's stale-admission guard.
Phased rollout
Phase 1 — Connect
- Publish both as development Exchange assets and apply in
monitor on a non-production MCP API behind real authentication; confirm verdict headers (x-approval-binding, x-aggregate-risk-gate) and violation events reach monitoring.
Phase 2 — Map and validate
- Wire the approver to the real canonical form and keys. Replay recorded traffic and confirm every would-deny is a true mismatch. Calibrate budget, timeout and approval lifetime; divide the budget by replica count.
Phase 3 — Production
- Switch binding to
block on the highest-risk tools first, then the gate. Pin a production Exchange version; alert on denial rate and on restarts or replica changes, which reset state.
Success metrics
- Share of governed
tools/call traffic carrying a valid approval; would-deny rate by predicate during monitor.
- Budget utilization per scope per window, and scopes refused.
- Added gateway latency per governed call; rate of
ledger-contention and ledger-unavailable (target near zero).
Troubleshooting
- Every call denied under P5 — Likely cause: no verified identity reaches the binding,
expectedAudience/expectedTenant/expectedEnvironment differ from what the approver signed, or the kid is unlisted or the key under 32 bytes. Fix: authenticate first, align the three claims exactly, check attesterKeys.
- P2 denies calls that look identical — Likely cause: non-canonical digest, a float, or an integer beyond 2^53 minus 1. Fix: canonicalize as in step 3.
- Valid approvals denied under P4 — Likely cause: clock drift, or
not_after beyond maxApprovalLifetimeSeconds. Fix: sync clocks, shorten approvals.
- Replay accepted — Likely cause: P6 is node-local and the replay hit another replica or followed a restart. Fix: one replica for P6 flows, or accept the limit.
- P6 stops admitting approvals — Likely cause: P6 without P4, so nonces never expire and the store fills. Fix: require P4 with P6.
- Budget admits more than expected — Likely cause: several replicas,
ledgerBackend: worker, or a restart or key change. Fix: divide by replicas, use node.