Plug-ins
Connect the systems you already run
A plug-in is a thin wrapper that runs in your own backend and asks Agent Control Room before an agent's step executes. Plug-ins are optional: a direct application connection uses exactly the same operations. Each recipe is a starting point, not a packaged product — review, test and adapt it to your platform before production. For MCP servers in TypeScript and for Python agents, supported open-source packages do the same job and are the recommended way to start.
Server-side only
Every plug-in runs on your server — in your MCP server process or backend service — and reads the API key from its environment. Never embed a key in browser JavaScript or mobile apps.
Four places it fits
One recipe for each of the four connection points described on How it fits, plus identity token verification, which works before all of them. All are optional. How it fits →
API and AI gateways
API gateway plugins (Kong & APISIX)
Asks Agent Control Room before your gateway forwards an agent's request, with an advanced option that checks a grant offline against the published Ed25519 key. Available as the supported kong-plugin-agent-guard and apisix-plugin-agent-guard packages, or built by hand in Lua.
decideActionreportExecutionOutcomegetGrantVerificationKey
MCP gateways
MCP server interceptor
Wraps each tool handler in your MCP server so it asks Agent Control Room before the tool runs and reports the outcome afterwards. Also available as the supported @complyee/mcp-guard package.
decideToolCallgetApprovalStatusreportExecutionOutcome
Agent platforms and orchestration
LangGraph tool node interceptor
Governs the tools in a LangGraph ToolNode, with an advanced option that adds the hand-off chain when one agent passes work to another. Also available as the supported complyee-agent-guard package, which includes ready-made wrappers for CrewAI and LlamaIndex tools.
decideToolCallgetApprovalStatusreportExecutionOutcome
Policy engines and security scanners
Scanner and policy engine recipes (Presidio, Lakera Guard, OPA)
Turns your own scanner's findings into standard security facts and asks before a data export runs, with an advanced option that adds a prompt-injection signal next to the personal-data one. A second tab passes an OPA verdict as one input — it never grants on its own.
decideActionreportExecutionOutcome
Identity · Before every place
Identity token verification
Verifies the sign-in token from your identity provider in your own backend and turns its verified claims into context facts, so rules rely on who is really asking — never on what the agent says. Works in front of all four recipes above.
Works with
- Microsoft Entra ID
- Okta
- Any OpenID Connect provider
decideActiondecideToolCall
API gateway plugins — Kong & Apache APISIX (Lua)
Use this when Kong Gateway or Apache APISIX already routes agent traffic to your APIs. The plugin asks Agent Control Room before the gateway forwards each request. The gateway routes, Agent Control Room decides, and your upstream service does the work. Both supported plugins behave the same way, so you can run either gateway — or both — against the same rules.
Recommended
Supported companion: kong-plugin-agent-guard
The recommended way to put the gate in Kong. Install the plugin from LuaRocks and enable it on the routes agents call; other routes stay as they are.
luarocks install kong-plugin-agent-guard
# 1. Install on every Kong node, then load it (kong.conf) and restart Kong
# luarocks install kong-plugin-agent-guard
# plugins = bundled,agent-guard
# 2. kong.yml (declarative) — enable on the route that agents call
_format_version: "3.0"
services:
- name: payments
url: http://payments.internal:8080
routes:
- name: transfers
paths: ["/payments/transfers"]
plugins:
- name: agent-guard
config:
gateway_url: https://<workspace>.agent-cr.com/api/public/v1/gateway
api_key: "{vault://env/acr-api-key}" # resolved at runtime, never plain text
mode: decide # or verify / verify_jwt
action_map:
"POST /payments/transfers": payments.transfer.createWhat it takes care of
- decide (default): maps each request to a governed action, fingerprints the body inside Kong and asks Agent Control Room before forwarding — the body never leaves your network.
- verify: checks a grant the request already carries offline against the published key set, bound to this agent, route and body, with no call back.
- verify_jwt: after a JWT plugin has checked a grant token's signature, binds it to this agent, route and body.
- Fails closed: a refusal returns 403, a hold returns 202, and no answer returns 503 — the request is not forwarded. A 202 is an authorization hold, not upstream acceptance or execution; the caller handles polling and resumption.
- In decide mode, attempts one non-blocking outcome report after the response using ngx.timer.at. Delivery is best-effort: no retries, durable queue or guarantee across worker restarts. The authorization decision is recorded independently during the ACR call; missing outcome evidence means execution is unknown.
kong-plugin-agent-guard on LuaRocks →kong-plugin-agent-guard on GitHub →
Recommended · apisix-plugin-agent-guard
Supported companion: apisix-plugin-agent-guard
The same gate, packaged for Apache APISIX. It behaves exactly like the Kong plugin — same three modes, same refusals, same outcome reports — so you can run either gateway, or both, against the same rules.
luarocks install apisix-plugin-agent-guard
# conf/config.yaml — enable the plugin (keep the other plugins you use)
nginx_config:
envs:
- ACR_API_KEY # also supply this variable to the APISIX process
plugins:
- key-auth
- agent-guard
# Admin API — enable it on the route agents call
curl http://127.0.0.1:9180/apisix/admin/routes/transfers -X PUT \
-H "X-API-KEY: $APISIX_ADMIN_KEY" -d '{
"uri": "/payments/transfers",
"methods": ["POST"],
"upstream": { "type": "roundrobin", "nodes": { "payments.internal:8080": 1 } },
"plugins": {
"agent-guard": {
"gateway_url": "https://<workspace>.agent-cr.com/api/public/v1/gateway",
"api_key": "$env://ACR_API_KEY",
"mode": "decide",
"action_map": { "POST /payments/transfers": "payments.transfer.create" }
}
}
}'What it takes care of
- decide (default), verify and verify_jwt, with the same route map, body fingerprint and acr-grant-v3 check as the Kong plugin.
- Runs after APISIX authentication plugins such as key-auth and jwt-auth, so agent_source: consumer uses the authenticated Consumer's username as the agent name.
- The plugin resolves $env:// or $secret:// references for every ACR call, including standalone YAML. Supply the environment variable and expose it to workers through nginx_config.envs; an unresolved key fails closed.
- Fails closed the same way: 403 refused, 202 held for a person, 503 no answer — the request is not forwarded.
Or build it by hand
Prefer to own every line, or need to adapt the logic? The steps below are the same plugin, built by hand for Kong; the APISIX plugin above follows the same flow.
Before you start
- Your workspace address: https://<workspace>.agent-cr.com/api/public/v1/gateway
- An API key with the policy.decide scope, held in a Kong vault or environment variable — never as plain text in plugin config
- The calling agents registered in your workspace, and rules for each mapped action
- Kong Gateway 3.x with the lua-resty-http library (bundled with Kong)
- For production, authenticate the caller before the guard (priority 900). consumer uses an authenticated Kong Consumer custom_id (or explicitly id); jwt_claim requires a trusted preceding adapter to set kong.ctx.shared.acr_verified_identity = { claims = verified_identity_claims } only after signature, allowed algorithm, issuer, audience and expiry checks. No common JWT/OIDC shared-claims field is assumed; the adapter is deployment-specific and not bundled. Header identity alone is not authentication.
- These safeguards are pending a repository release. Existing unmapped header-only actions must add route mappings or explicitly opt in behind a trusted boundary. Validate with real Kong and your authentication plugin before production rollout; bundled tests mock those APIs.
1. Plugin configuration
The API key is a vault reference that Kong resolves at runtime. Each route can carry its own action map.
-- kong/plugins/acr/schema.lua
local typedefs = require "kong.db.schema.typedefs"
return {
name = "acr",
fields = {
{ protocols = typedefs.protocols_http },
{ config = { type = "record", fields = {
-- https://<workspace>.agent-cr.com/api/public/v1/gateway
{ gateway_url = { type = "string", required = true } },
-- A Kong vault reference such as {vault://env/acr-api-key}, never the key itself
{ api_key = { type = "string", required = true, referenceable = true, encrypted = true } },
{ agent_header = { type = "string", default = "X-Agent-Id" } },
{ agent_source = { type = "string", default = "header", one_of = { "header", "consumer", "jwt_claim" } } },
{ consumer_id_field = { type = "string", default = "custom_id", one_of = { "custom_id", "id" } } },
{ agent_claim = { type = "string", default = "sub" } },
{ action_header = { type = "string", default = "X-Acr-Action" } },
{ allow_action_header = { type = "boolean", default = false } },
-- "POST /payments/transfers" = "payments.transfer.create"
{ action_map = { type = "map", keys = { type = "string" }, values = { type = "string" }, default = {} } },
{ timeout_ms = { type = "integer", default = 3000 } },
} } },
},
}2. Map the request to an action
The method/path action map always wins. Unmapped action headers require allow_action_header = true behind a trusted boundary. Choose header, authenticated Consumer or verified JWT identity; missing authenticated identity never falls back to caller headers.
-- handler.lua (part 1): which action is this request?
local function resolve_action(conf)
local key = kong.request.get_method() .. " " .. kong.request.get_path()
local mapped = (conf.action_map or {})[key]
if mapped and mapped ~= "" then return mapped end
if conf.allow_action_header then
local from_header = kong.request.get_header(conf.action_header)
if type(from_header) == "string" and from_header ~= "" then return from_header end
end
return nil
end
local function resolve_agent(conf)
local source = conf.agent_source or "header"
local agent
if source == "consumer" then
local consumer = kong.client.get_consumer()
agent = consumer and consumer[conf.consumer_id_field or "custom_id"]
elseif source == "jwt_claim" then
-- A trusted preceding authentication adapter sets this ONLY after verifying
-- signature, allowed algorithm, issuer, audience and expiry. Not a bearer decode.
local identity = kong.ctx.shared.acr_verified_identity
local claims = type(identity) == "table" and identity.claims
agent = type(claims) == "table" and claims[conf.agent_claim or "sub"]
elseif source == "header" then
agent = kong.request.get_header(conf.agent_header)
end
if type(agent) ~= "string" or agent == "" or agent:find("|", 1, true) then return nil end
return agent
end3. Fingerprint the body
Kong hashes a successfully read body; nil/error reads refuse, including disk-buffered bodies. A genuinely empty body remains valid. Configure bounded body buffers and request-size limits; only the hash is sent.
-- handler.lua (part 2): one-way fingerprint of the body
local resty_sha256 = require "resty.sha256"
local str = require "resty.string"
local function payload_hash()
local body, err = kong.request.get_raw_body()
-- Kong returns "" for a genuinely empty/absent body; nil means failure.
if err or type(body) ~= "string" then
return nil, "Unable to read request body for cryptographic binding."
end
local h = resty_sha256:new()
h:update(body)
return str.to_hex(h:final()) -- only this hash is sent, never the body
end4. Ask before forwarding
A grant forwards the request with its decision id. A refusal returns 403. A hold returns 202; it means policy review is pending, not that the upstream accepted or executed the action. The caller handles polling and resumption. No answer returns 503 — the request is not forwarded.
-- handler.lua (part 3): ask before Kong forwards
local http = require "resty.http"
local cjson = require "cjson.safe"
local AcrHandler = { PRIORITY = 900, VERSION = "0.1.0" }
local function acr_call(conf, operation, parameters, idem_key)
local client = http.new()
client:set_timeout(conf.timeout_ms)
local res, err = client:request_uri(conf.gateway_url, {
method = "POST",
body = cjson.encode({ operation = operation, parameters = parameters }),
headers = {
["content-type"] = "application/json",
["x-api-key"] = conf.api_key, -- resolved from the vault by Kong
["idempotency-key"] = idem_key,
},
})
if not res then return nil, err end
-- Never log response bodies: they may contain sensitive upstream diagnostics.
if type(res.status) ~= "number" or res.status < 200 or res.status >= 300 then
return nil, "HTTP " .. tostring(res.status or "unknown")
end
local answer = cjson.decode(res.body)
if type(answer) ~= "table" then return nil, "Invalid JSON response" end
if answer.error then return nil, "ACR application error" end
return answer
end
function AcrHandler:access(conf)
local action = resolve_action(conf)
if not action then
return kong.response.exit(403, { message = "No governed action mapped for this route." })
end
local agent = resolve_agent(conf)
if not agent then
return kong.response.exit(403, { message = "Missing or invalid agent identity." })
end
local hash, hash_err = payload_hash()
if not hash then
return kong.response.exit(400, { message = hash_err })
end
local params = {
agent = agent,
action = action,
resourceRef = kong.request.get_path_with_query(),
payloadHash = hash,
}
local idem = "kong-" .. ngx.md5(cjson.encode(params))
local answer, err = acr_call(conf, "decideAction", params, idem)
if not answer then
kong.log.err("ACR unreachable: ", err)
return kong.response.exit(503, { message = "Not forwarded: no decision." }) -- fail closed
end
local d = answer.decision or {}
if d.effect == "grant" then
kong.ctx.plugin.decision = { decisionId = d.decisionId, payloadHash = hash } -- the hash Kong computed
kong.service.request.set_header("X-Acr-Decision-Id", d.decisionId)
return -- forward to the upstream service
end
if d.effect == "pending" then
-- Held for a person. Return once; the caller polls getApprovalStatus. No loop here.
return kong.response.exit(202, { message = "Held for review.", approvalId = d.approvalId or answer.approvalId })
end
return kong.response.exit(403, { message = "Refused.", rationale = d.rationale })
end5. Report the outcome
In decide mode, ngx.timer.at schedules one non-blocking, best-effort report: no retries or durable buffering. Worker exit, a premature callback, scheduling failure or a failed call can leave the outcome unrecorded; Scheduling failures, premature shutdown callbacks and failed reports log the decision id; hard crashes can still lose evidence silently. Non-2xx ACR responses are rejected without logging response bodies. Upstream 2xx maps to executed, 4xx to aborted, and 5xx/timeouts to downstream_error; other statuses map to aborted. Each report includes http_<status>, with http_202_accepted for an upstream 202: acceptance is not completed business work. These are proxy-observed classifications, not proof of whether a side effect committed. Missing evidence means unknown execution, not refusal or pending approval. ACR records one outcome per decision; a later different completion report conflicts rather than replacing this proxy observation. For durable completion evidence, reconcile through the upstream service or orchestrator. Offline verify and verify_jwt never schedule outcome reports; durable completion reporting belongs to the upstream service or orchestrator.
-- handler.lua (part 4): report what happened, without delaying the response
local function report(premature, conf, decision, outcome, detail_code)
if premature then
kong.log.warn("reportExecutionOutcome dropped on worker shutdown for decision ", decision.decisionId)
return
end
local _, err = acr_call(conf, "reportExecutionOutcome", {
decisionId = decision.decisionId,
payloadHash = decision.payloadHash,
outcome = outcome,
detailCode = detail_code,
}, "outcome-" .. decision.decisionId)
if err then
kong.log.warn("reportExecutionOutcome failed for decision ", decision.decisionId, ": ", err)
end -- evidence only; no retries and no change to the response
end
function AcrHandler:log(conf)
-- Offline verification never schedules outcome reports, even with shared state.
if conf.mode == "verify" or conf.mode == "verify_jwt" then return end
local decision = kong.ctx.plugin.decision
if not decision then return end
local status = kong.response.get_status()
local outcome = "aborted"
if status >= 200 and status < 300 then
outcome = "executed"
elseif status >= 500 then
outcome = "downstream_error"
end
local detail_code = status == 202 and "http_202_accepted" or "http_" .. tostring(status)
local scheduled, err = ngx.timer.at(0, report, conf, decision, outcome, detail_code)
if not scheduled then
kong.log.err("reportExecutionOutcome scheduling failed for decision ", decision.decisionId, ": ", err)
end
end
return AcrHandler6. Enable it on a route
A declarative snippet that governs one route. Add one action_map entry per governed endpoint.
# kong.yml (declarative) — enable on the route that agents call
_format_version: "3.0"
services:
- name: payments
url: http://payments.internal:8080
routes:
- name: transfers
paths: ["/payments/transfers"]
plugins:
- name: acr
config:
gateway_url: https://<workspace>.agent-cr.com/api/public/v1/gateway
api_key: "{vault://env/acr-api-key}"
action_map:
"POST /payments/transfers": payments.transfer.createWhat it does not do
- It does not send request bodies to Agent Control Room; only a fingerprint.
- It never grants on its own. Only Agent Control Room's rules decide.
- It does not replace Kong's own authentication, rate limiting or routing.
- It does not wait in a loop on holds, and refuses when Agent Control Room cannot be reached.
- It does not deduplicate upstream transactions. The upstream must enforce its own Idempotency-Key or business-operation reference, stable across retries and approval resumption even when the ACR decision changes. Track operation, decision/approval and request-attempt ids separately; a decision id alone is not a business-operation key.
- It does not guarantee outcome delivery, exactly-once execution or business success from an HTTP status. After a timeout, reconcile the operation upstream before retrying: the side effect may already have occurred.
TypeScript MCP server interceptor
Use this when your agents reach business systems through MCP tools that you host. The interceptor sits inside your MCP server, between the incoming tools/call and your existing tool handler.
Recommended
Supported companion: @complyee/mcp-guard
The recommended way to govern MCP tools. Install the package and wrap each governed tool when you register it; ungoverned tools stay as they are.
npm install @complyee/mcp-guard
import { createMcpGuard } from "@complyee/mcp-guard";
const guard = createMcpGuard({
workspaceUrl: "https://<workspace>.agent-cr.com", // your workspace address, also the grant token's audience
apiKey: process.env.ACR_API_KEY!, // scopes: policy.decide, policy.read
agent: process.env.ACR_AGENT!,
});
server.registerTool(
"transfer_funds",
{
description: "Transfer money between two accounts",
inputSchema: { transferRequestId: z.string(), fromAccount: z.string(), toAccount: z.string(), amount: z.number() },
},
guard.tool("transfer_funds", {
context: (args) => ({ amount: args.amount }), // facts your rules read
execute: async ({ transferRequestId, fromAccount, toAccount, amount }, grant) => {
// Runs only on a verified grant for exactly these arguments. The idempotency key
// is your stable business reference, never grant.decisionId: a retry is a new
// decision with a new id. decisionId is kept as the audit reference.
await bank.transfer(fromAccount, toAccount, amount, {
idempotencyKey: transferRequestId,
metadata: { acrDecisionId: grant.decisionId },
});
return { content: [{ type: "text", text: "Transfer completed." }] };
},
}),
);What it takes care of
- Fingerprints the tool name and arguments in your server and calls decideAction with only the hash — the arguments never leave your server.
- Checks the grant token (EdDSA) against the published key set at https://agent-cr.com/.well-known/jwks.json: issuer, your workspace address, agent, action, payload fingerprint and expiry. Any failed check means the tool does not run.
- When a person must decide, waits a short while (configurable) or returns at once with the approval id; calling the tool again with the same arguments claims the grant.
- Retries a lost connection with the same idempotency key and reports executed or downstream_error afterwards.
Or build it by hand
Prefer no dependency, or a runtime the package does not cover? The steps below build the same gate by hand. They use decideToolCall, which sends the arguments for fingerprinting; the package hashes them locally instead.
Before you start
- Your workspace address: https://<workspace>.agent-cr.com/api/public/v1/gateway
- An API key with the policy.decide scope, stored as a server-side secret
- The agent registered in your workspace
- Rules for the tool names you govern (the tool name is used as the action unless you pass one)
1. Configuration from the environment
The key is read from the server's environment. It never appears in source code or in anything sent to a browser.
// acr.ts — server-side only. Never import this into browser code. const ACR_GATEWAY_URL = process.env.ACR_GATEWAY_URL!; // https://<workspace>.agent-cr.com/api/public/v1/gateway const ACR_API_KEY = process.env.ACR_API_KEY!; // kept in your secret store const ACR_AGENT = process.env.ACR_AGENT!; // the registered agent this server acts for
2. One helper for the gateway
Every operation goes through the same gateway address. A short timeout keeps a slow answer from stalling the agent.
type AcrResponse = Record<string, any> & { statusCode: number };
async function acrCall(
operation: string,
parameters: Record<string, unknown>,
idempotencyKey?: string,
): Promise<AcrResponse> {
const res = await fetch(ACR_GATEWAY_URL, {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": ACR_API_KEY,
...(idempotencyKey ? { "idempotency-key": idempotencyKey } : {}),
},
body: JSON.stringify({ operation, parameters }),
signal: AbortSignal.timeout(5000),
});
const body = (await res.json()) as AcrResponse;
if (!res.ok) throw new Error(`ACR ${operation} failed: ${body.error?.code ?? res.status}`);
return body;
}3. Wrap the tool handler
Ask before running. A grant runs the handler; a refusal returns an error result to the agent; a hold returns once with its holdToken. If Agent Control Room cannot be reached, the tool does not run.
type ToolResult = { content: { type: "text"; text: string }[]; isError?: boolean };
type Handler<A> = (args: A) => Promise<ToolResult>;
const blocked = (text: string): ToolResult => ({ content: [{ type: "text", text }], isError: true });
export function governTool<A extends Record<string, unknown>>(
toolName: string,
handler: Handler<A>,
options: { context?: Record<string, unknown> } = {},
): Handler<A> {
return async (args) => {
let answer: AcrResponse;
try {
answer = await acrCall("decideToolCall", {
agent: ACR_AGENT,
toolName,
toolArguments: args,
...(options.context ? { context: options.context } : {}),
}, crypto.randomUUID());
} catch {
// Fail closed: no answer means no execution.
return blocked("Agent Control Room could not be reached, so the tool did not run.");
}
const d = answer.decision;
if (answer.mcp?.holdToken) {
// Held for a person. Return once; do not retry in a loop.
return blocked(`Held for human review. holdToken: ${answer.mcp.holdToken}`);
}
if (!answer.mcp?.allowExecution || d?.effect !== "grant") {
return blocked(`Refused by policy: ${d?.rationale ?? "not allowed"}`);
}
let result: ToolResult;
try {
result = await handler(args);
} catch (err) {
void reportOutcome(d, "downstream_error", "tool_handler_error");
throw err;
}
void reportOutcome(d, result.isError ? "downstream_error" : "executed");
return result;
};
}4. Report what happened
After the handler runs, report executed, aborted or downstream_error. The report is evidence only and never delays or changes the tool's result.
async function reportOutcome(
decision: { decisionId: string; payloadHash: string },
outcome: "executed" | "aborted" | "downstream_error",
detailCode?: string,
) {
try {
await acrCall("reportExecutionOutcome", {
decisionId: decision.decisionId,
payloadHash: decision.payloadHash,
outcome,
...(detailCode ? { detailCode } : {}),
}, `outcome-${decision.decisionId}`);
} catch (err) {
// Evidence only: a failed report never changes the tool's result.
console.error("reportExecutionOutcome failed", err);
}
}5. Resume after a person decides (optional)
Check a hold with getApprovalStatus when it suits your flow. Do not poll in a tight loop.
// Later — for example when the agent or a person asks again — check the hold.
export async function approvalStatus(holdToken: string) {
const answer = await acrCall("getApprovalStatus", { approvalId: holdToken });
return answer.approval?.status as
"pending" | "granted" | "refused" | "expired" | "consumed";
}
// When it is "granted", repeat the identical tool call once:
// that decideToolCall claims the approval and returns the signed grant.6. Register the wrapped tool
Wrap each governed tool with governTool when you register it with the official MCP TypeScript SDK. Ungoverned tools stay as they are.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { governTool } from "./acr";
const server = new McpServer({ name: "payments", version: "1.0.0" });
server.tool(
"transfer_funds",
{ fromAccount: z.string(), toAccount: z.string(), amount: z.number() },
governTool("transfer_funds", async ({ fromAccount, toAccount, amount }) => {
await bank.transfer(fromAccount, toAccount, amount); // your existing code
return { content: [{ type: "text", text: "Transfer completed." }] };
}),
);Optional: to bind the call you forward to the grant, recompute the sha256-canonical-json-v1 fingerprint of { tool, arguments } and check it equals decision.payloadHash, then verify publicSignature offline with the key from getGrantVerificationKey, using your agent key and decision.action (both are signed). The API reference has the full recipe. API reference →
What it does not do
- It does not scan or store tool arguments; Agent Control Room only uses them to compute a fingerprint.
- It never grants on its own. Only Agent Control Room's rules decide.
- It does not retry held calls in a loop.
- It fails closed: no answer means the tool does not run.
Python / LangGraph tool node interceptor
Use this when your agents run as LangGraph graphs and call tools through a ToolNode. Each governed tool asks Agent Control Room before its body runs.
Recommended
Supported companion: complyee-agent-guard
The recommended way to govern Python agent tools. Add the decorator under @tool; ungoverned tools stay as they are. It works the same for LangChain tools and plain functions; CrewAI and LlamaIndex have their own wrappers, shown next.
pip install complyee-agent-guard
import os
from langchain_core.tools import tool
from complyee_agent_guard import create_guard
guard = create_guard(
workspace_url="https://<workspace>.agent-cr.com", # your workspace address, also the grant token's audience
api_key=os.environ["ACR_API_KEY"], # scopes: policy.decide, policy.read
agent=os.environ["ACR_AGENT"],
approvals={"mode": "raise"}, # hand holds to LangGraph to checkpoint and resume
)
@tool
@guard.tool(action="transfer_funds", context=lambda a: {"amount": a["amount"]})
def transfer_funds(from_account: str, to_account: str, amount: float) -> str:
"""Transfer money between two accounts."""
bank.transfer(from_account, to_account, amount) # runs only on a verified grant
return "Transfer completed."
# Put transfer_funds in your ToolNode as usual. An async def tool is awaited the same way.What it takes care of
- Fingerprints the tool name and arguments in your process and calls decideAction with only the hash — the arguments never leave your process.
- Checks the grant token (EdDSA) against the published key set at https://agent-cr.com/.well-known/jwks.json: issuer, your workspace address, agent, action, payload fingerprint and expiry. Any failed check raises an error and the tool body never runs.
- Supports async def and plain def tools. When a person must decide it either waits a short while or raises ApprovalPending with a checkpoint your graph can save and resume later.
- Retries a lost connection with the same idempotency key and reports executed or downstream_error afterwards.
complyee-agent-guard on PyPI →complyee-agent-guard on GitHub →
Recommended · complyee-agent-guard
Using CrewAI? Wrap the tool instead
The same package includes a wrapper for CrewAI. Wrap any CrewAI tool — one you wrote with @tool, a BaseTool class or a tool from crewai_tools — and give the wrapped tool to your agent. Ungoverned tools stay as they are.
pip install "complyee-agent-guard[crewai]"
import os
from crewai import Agent
from crewai.tools import tool
from complyee_agent_guard import create_guard
from complyee_agent_guard.crewai import GuardedCrewAITool, current_grant
guard = create_guard(
workspace_url="https://<workspace>.agent-cr.com", # your workspace address, also the grant token's audience
api_key=os.environ["ACR_API_KEY"], # scopes: policy.decide, policy.read
agent=os.environ["ACR_AGENT"],
)
@tool("issue_refund")
def issue_refund(refund_request_id: str, payment_id: str, amount: float) -> str:
"""Refund a payment."""
grant = current_grant() # the verified grant for exactly these arguments
# Business reference as the idempotency key; decision_id only as audit metadata.
payments.refund(payment_id, amount, idempotency_key=refund_request_id,
metadata={"acr_decision_id": grant.decision_id})
return "Refund issued."
refund = GuardedCrewAITool(
tool=issue_refund,
guard=guard,
action="refund.issue",
context=lambda a: {"amount": a["amount"]}, # facts your rules read
)
agent = Agent(role="Support lead", goal="...", backstory="...", tools=[refund])What it takes care of
- The agent sees the tool's own name, description and inputs. The inputs are fingerprinted in your process and never sent to Agent Control Room.
- When the step does not run, the tool tells the agent why in plain words instead of crashing the crew, with a stable code: acr_refused, acr_approval_pending, acr_grant_invalid or acr_unavailable. Your CrewAI tool_failure_policy decides what happens next — "warn" lets the agent carry on and explain, "raise" stops the crew.
- If a person has not approved yet and the agent asks again with exactly the same input, the same approval request continues; no second request is opened.
- CrewAI never reuses a saved result for a wrapped tool, so every call gets its own decision.
Recommended · complyee-agent-guard
Using LlamaIndex? Wrap the tool instead
The same package includes a wrapper for LlamaIndex. It governs both kinds of tool an agent uses: looking things up in your documents (a QueryEngineTool or RetrieverTool) and taking actions (a FunctionTool or your own BaseTool). Wrap the tools you want governed and give them to your agent; the others stay as they are.
pip install "complyee-agent-guard[llama-index]"
import os
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.core.tools import FunctionTool, QueryEngineTool
from complyee_agent_guard import create_guard
from complyee_agent_guard.llama_index import GuardedLlamaTool, current_grant
guard = create_guard(
workspace_url="https://<workspace>.agent-cr.com", # your workspace address, also the grant token's audience
api_key=os.environ["ACR_API_KEY"], # scopes: policy.decide, policy.read
agent=os.environ["ACR_AGENT"],
)
# A knowledge lookup: the question, the documents found and the answer stay here.
finance_docs = GuardedLlamaTool(
tool=QueryEngineTool.from_defaults(
query_engine=finance_index.as_query_engine(),
name="finance_docs",
description="Answer questions from the finance knowledge base.",
),
guard=guard,
action="knowledge.query",
resource_ref=lambda a: "kb:finance", # which collection, never its contents
context=lambda a: {"classification": "confidential"},
)
# An action: runs only on a verified grant for exactly these arguments.
def issue_refund(refund_request_id: str, payment_id: str, amount: float) -> str:
"""Refund a payment."""
grant = current_grant()
# Business reference as the idempotency key; decision_id only as audit metadata.
payments.refund(payment_id, amount, idempotency_key=refund_request_id,
metadata={"acr_decision_id": grant.decision_id})
return "Refund issued."
refund = GuardedLlamaTool(
tool=FunctionTool.from_defaults(fn=issue_refund),
guard=guard,
action="refund.issue",
context=lambda a: {"amount": a["amount"]}, # facts your rules read
)
agent = FunctionAgent(tools=[finance_docs, refund], llm=llm)What it takes care of
- For a document lookup, the question, the documents found and the answer stay in your process. Agent Control Room sees only a fingerprint of the question, the collection you name and the facts you declare.
- The agent sees the tool's own name, description and inputs. When the step does not run, the agent gets an error result that says why in plain words — it never contains the inputs — with a stable code: acr_refused, acr_approval_pending, acr_grant_invalid or acr_unavailable. The agent carries on instead of crashing.
- If a person has not approved yet and the agent asks again with exactly the same input, the same approval request continues; no second request is opened. If the wrapped tool itself fails, Agent Control Room records a downstream error.
- Needs LlamaIndex core 0.14.22 or later. Tools that take LlamaIndex's workflow Context as an input cannot be wrapped; the wrapper says so when you create it.
Recommended · @complyee/mcp-guard
Using Abundly? Connect it to a governed MCP endpoint
Abundly runs your agents' planning and conversations in its own cloud, so you cannot add a wrapper inside it. Instead, the agent reaches your business systems through an MCP server that you host, with @complyee/mcp-guard in front of each consequential tool. The TypeScript MCP recipe shows how to build that server for any caller; this block covers the Abundly side: checking that the caller really is your Abundly agent, answering within a chat turn when a person must decide, and connecting the server in Abundly. In Abundly, open the agent's tool settings, add your server's public HTTPS address as an MCP server, and choose a signed token for authentication if your workspace offers one. Then switch off any general-purpose web or database tools that could reach the same systems, so governed writes can only go through your server.
Confirm with Abundly before you connect
- Can an MCP connection send a signed token? <abundly:can-send-signed-token> — until this is confirmed, the steps below assume it can.
- Token issuer and key-set address: <abundly:issuer> and <abundly:jwks-url> — set them as ABUNDLY_ISSUER and ABUNDLY_JWKS_URL.
- The token field that holds the agent's id: <abundly:agent-id-claim> — set it as ABUNDLY_AGENT_CLAIM.
npm install @complyee/mcp-guard jose
// server.ts — your MCP server, reachable by Abundly over HTTPS.
import { createRemoteJWKSet, jwtVerify } from "jose";
import { createMcpGuard } from "@complyee/mcp-guard";
// 1. Check who is calling before any tool runs. The three values below are
// placeholders until Abundly confirms them for your workspace:
// ABUNDLY_JWKS_URL the key-set address Abundly publishes
// ABUNDLY_ISSUER the token's issuer
// ABUNDLY_AGENT_CLAIM the token field that holds the agent id
const ABUNDLY_KEYS = createRemoteJWKSet(new URL(process.env.ABUNDLY_JWKS_URL!));
async function abundlyCaller(authorization: string | undefined): Promise<string> {
if (!authorization?.startsWith("Bearer ")) throw new Error("Not an Abundly call");
const { payload } = await jwtVerify(authorization.slice(7), ABUNDLY_KEYS, {
issuer: process.env.ABUNDLY_ISSUER!,
audience: process.env.MCP_PUBLIC_URL!,
});
return String(payload[process.env.ABUNDLY_AGENT_CLAIM!]); // the Abundly agent id
}
// 2. One guard per Abundly agent you allow, each bound to its registered agent
// in Agent Control Room. Unknown agents get no tools at all.
const AGENTS: Record<string, string> = { "<abundly-agent-id>": "support-refund-agent" };
function guardFor(abundlyAgentId: string) {
const agent = AGENTS[abundlyAgentId];
if (!agent) throw new Error("Agent not allowed");
return createMcpGuard({
workspaceUrl: "https://<workspace>.agent-cr.com", // your workspace address
apiKey: process.env.ACR_API_KEY!, // scopes: policy.decide, policy.read
agent,
approvals: { mode: "immediate_return" }, // answer within the chat turn
});
}
// 3. Register the governed tool on the MCP session you open for this caller.
export function registerTools(server: McpServer, abundlyAgentId: string) {
const guard = guardFor(abundlyAgentId);
server.registerTool(
"issue_refund",
{
description: "Issue a customer refund. Checked against independent policy before it runs.",
inputSchema: { refundRequestId: z.string(), paymentId: z.string(), amount: z.number() },
},
guard.tool("refund.issue", {
context: (args) => ({ amount: args.amount }), // facts your rules read
execute: async ({ refundRequestId, paymentId, amount }, grant) => {
// Runs only on a verified grant for exactly these arguments.
await payments.refund(paymentId, amount, {
idempotencyKey: refundRequestId, // your business reference
metadata: { acrDecisionId: grant.decisionId }, // audit reference only
});
return { content: [{ type: "text", text: "Refund issued." }] };
},
}),
);
}What it takes care of
- The caller is identified from a token your server verifies, never from a name in the tool's inputs, so a prompt cannot make one agent act as another.
- Abundly never holds the keys to your payment, customer or database systems; only your server does.
- When a person must decide, the tool returns at once with the approval reference and the step has not run. The agent can tell the user it is waiting; calling the tool again with the same inputs after approval carries it out. Changed inputs need a new decision.
- It governs the external actions your server exposes. It does not govern Abundly's own built-in features, such as its browser or knowledge lookups, and it does not replace your existing network or API protection.
Or build it by hand
Prefer no dependency, or a framework the package does not cover? The steps below build the same gate by hand. They use decideToolCall, which sends the arguments for fingerprinting; the package hashes them locally instead.
Before you start
- Your workspace address: https://<workspace>.agent-cr.com/api/public/v1/gateway
- An API key with the policy.decide scope, stored as a server-side secret
- The agent registered in your workspace
- Rules for the tool names you govern
- Python packages: pip install langgraph httpx
1. Configuration from the environment
The key is read from the server's environment. It never appears in source code.
# acr.py — server-side only. Requires: pip install langgraph httpx import os, uuid import httpx ACR_GATEWAY_URL = os.environ["ACR_GATEWAY_URL"] # https://<workspace>.agent-cr.com/api/public/v1/gateway ACR_API_KEY = os.environ["ACR_API_KEY"] # kept in your secret store ACR_AGENT = os.environ["ACR_AGENT"] # the registered agent this graph acts for
2. One helper for the gateway
Every operation goes through the same gateway address, with a five-second timeout.
_client = httpx.Client(timeout=5.0)
def acr_call(operation: str, parameters: dict, idempotency_key: str | None = None) -> dict:
headers = {"content-type": "application/json", "x-api-key": ACR_API_KEY}
if idempotency_key:
headers["idempotency-key"] = idempotency_key
res = _client.post(ACR_GATEWAY_URL, headers=headers,
json={"operation": operation, "parameters": parameters})
body = res.json()
if res.is_error:
raise RuntimeError(f"ACR {operation} failed: {body.get('error', {}).get('code', res.status_code)}")
return body3. Wrap the tool
A grant runs the tool. A refusal or a hold becomes a tool error the agent can read; a hold carries its holdToken. If Agent Control Room cannot be reached, the tool does not run.
import functools
from langchain_core.tools import ToolException
def govern_tool(tool_name: str, context_fn=None):
"""Decorator: ask Agent Control Room before the tool body runs."""
def wrap(fn):
@functools.wraps(fn)
def governed(**args):
params = {"agent": ACR_AGENT, "toolName": tool_name, "toolArguments": args}
if context_fn:
params["context"] = context_fn()
try:
answer = acr_call("decideToolCall", params, str(uuid.uuid4()))
except Exception:
# Fail closed: no answer means no execution.
raise ToolException("Agent Control Room could not be reached, so the tool did not run.")
d = answer.get("decision") or {}
mcp = answer.get("mcp") or {}
if mcp.get("holdToken"):
# Held for a person. Return once; do not retry in a loop.
raise ToolException(f"Held for human review. holdToken: {mcp['holdToken']}")
if not mcp.get("allowExecution") or d.get("effect") != "grant":
raise ToolException(f"Refused by policy: {d.get('rationale', 'not allowed')}")
try:
result = fn(**args)
except Exception:
report_outcome(d, "downstream_error", "tool_handler_error")
raise
report_outcome(d, "executed")
return result
return governed
return wrap4. Report what happened
After the tool runs, report executed or downstream_error. The report is evidence only.
def report_outcome(decision: dict, outcome: str, detail_code: str | None = None) -> None:
params = {"decisionId": decision["decisionId"], "payloadHash": decision["payloadHash"], "outcome": outcome}
if detail_code:
params["detailCode"] = detail_code
try:
acr_call("reportExecutionOutcome", params, f"outcome-{decision['decisionId']}")
except Exception as err:
# Evidence only: a failed report never changes the tool's result.
print("reportExecutionOutcome failed", err)5. Put the governed tools in a ToolNode
Decorate each governed tool and wire them into your graph as usual. Ungoverned tools stay as they are.
from langchain_core.tools import tool
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.prebuilt import ToolNode, tools_condition
@tool
@govern_tool("transfer_funds")
def transfer_funds(from_account: str, to_account: str, amount: float) -> str:
"""Transfer money between two accounts."""
bank.transfer(from_account, to_account, amount) # your existing code
return "Transfer completed."
tools = [transfer_funds]
graph = StateGraph(MessagesState)
graph.add_node("agent", call_model) # your existing model node, bound to tools
graph.add_node("tools", ToolNode(tools, handle_tool_errors=True))
graph.add_edge(START, "agent")
graph.add_conditional_edges("agent", tools_condition)
graph.add_edge("tools", "agent")
app = graph.compile(checkpointer=checkpointer)6. Resume after a person decides (optional)
LangGraph's interrupt pauses the graph instead of polling. When someone resumes it, check the hold once.
from langgraph.types import interrupt
def wait_for_person(hold_token: str) -> str:
"""Pause the graph until someone resumes it, then check the hold once."""
interrupt({"holdToken": hold_token}) # the graph stops here; resume with Command(resume=...)
answer = acr_call("getApprovalStatus", {"approvalId": hold_token})
return answer["approval"]["status"] # pending | granted | refused | expired | consumed
# When it is "granted", repeat the identical tool call once:
# that decideToolCall claims the approval and returns the signed grant.What it does not do
- It does not scan or store tool arguments; Agent Control Room only uses them to compute a fingerprint.
- It never grants on its own. Only Agent Control Room's rules decide.
- It does not retry held calls in a loop.
- It fails closed: no answer means the tool does not run.
Python scanner recipe: Presidio, with optional Lakera Guard
Use this when you already scan content before an agent exports or publishes it. Your scanner runs in your system; its findings travel to Agent Control Room as standard security facts, and your rules decide.
Before you start
- Your workspace address: https://<workspace>.agent-cr.com/api/public/v1/gateway
- An API key with the policy.decide scope, stored as a server-side secret
- The agent registered in your workspace, and rules for data.export
- Python packages: pip install presidio-analyzer httpx (plus a spaCy language model)
1. Configuration from the environment
Keys are read from the server's environment, never from source code.
# acr_scan.py — server-side only. # Requires: pip install presidio-analyzer httpx && python -m spacy download en_core_web_lg import os, json, hashlib, uuid from datetime import datetime, timezone import httpx ACR_GATEWAY_URL = os.environ["ACR_GATEWAY_URL"] # https://<workspace>.agent-cr.com/api/public/v1/gateway ACR_API_KEY = os.environ["ACR_API_KEY"] # kept in your secret store ACR_AGENT = os.environ["ACR_AGENT"] # the registered agent this service acts for
2. One helper for the gateway
The same helper as the LangGraph recipe, with a five-second timeout.
_client = httpx.Client(timeout=5.0)
def acr_call(operation: str, parameters: dict, idempotency_key: str | None = None) -> dict:
headers = {"content-type": "application/json", "x-api-key": ACR_API_KEY}
if idempotency_key:
headers["idempotency-key"] = idempotency_key
res = _client.post(ACR_GATEWAY_URL, headers=headers,
json={"operation": operation, "parameters": parameters})
body = res.json()
if res.is_error:
raise RuntimeError(f"ACR {operation} failed: {body.get('error', {}).get('code', res.status_code)}")
return body3. Scan locally and map findings to facts
Presidio runs in your system. Its findings become sec.pii_detected, sec.pii_categories_band and sec.dlp_verdict, each with its own source and time. A failed scan sends not_scanned, never clean.
from presidio_analyzer import AnalyzerEngine
_analyzer = AnalyzerEngine()
FINANCIAL = {"CREDIT_CARD", "IBAN_CODE", "US_BANK_NUMBER"}
CONTACT = {"PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "LOCATION"}
SPECIAL = {"MEDICAL_LICENSE"} # extend with your own recognizers
def fact(value, asserted_by: str) -> dict:
"""Each fact names its own source and time."""
return {"value": value, "assertedBy": asserted_by,
"observedAt": datetime.now(timezone.utc).isoformat()}
def presidio_facts(text: str) -> dict:
try:
found = {r.entity_type for r in _analyzer.analyze(text=text, language="en") if r.score >= 0.6}
except Exception:
# A failed scan is unknown, never clean.
return {"sec.dlp_verdict": fact("not_scanned", "presidio-analyzer")}
band = ("special_category" if found & SPECIAL else "financial" if found & FINANCIAL
else "contact" if found & CONTACT else "none")
return {
"sec.pii_detected": fact("true" if found else "false", "presidio-analyzer"),
"sec.pii_categories_band": fact(band, "presidio-analyzer"),
"sec.dlp_verdict": fact("flagged" if found else "clean", "presidio-analyzer"),
}4. Ask before the export
Only a one-way fingerprint of the content and the facts are sent. Anything other than a grant — a refusal, a hold for a person, or no answer — means the export does not run.
def ask_before_export(text: str, destination: str, context: dict) -> dict | None:
payload_hash = hashlib.sha256(text.encode("utf-8")).hexdigest() # content never leaves you
body = {"agent": ACR_AGENT, "action": "data.export", "resourceRef": destination,
"payloadHash": payload_hash, "context": context}
key = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
try:
answer = acr_call("decideAction", body, key)
except Exception:
return None # Fail closed: no answer means no export.
d = answer.get("decision") or {}
if d.get("effect") != "grant":
return None # pending or reject: do not export
return {**d, "payloadHash": payload_hash} # keep your own hash for the outcome report5. Export on a grant and report what happened
The report is evidence only and never changes the result.
def export_with_scan(text: str, destination: str) -> str:
decision = ask_before_export(text, destination, presidio_facts(text))
if decision is None:
return "Not exported: refused, held for a person, or no answer."
try:
storage.export(destination, text) # your existing code
outcome = "executed"
except Exception:
outcome = "downstream_error"
try:
acr_call("reportExecutionOutcome", {"decisionId": decision["decisionId"],
"payloadHash": decision["payloadHash"], "outcome": outcome},
f"outcome-{decision['decisionId']}")
except Exception as err:
print("reportExecutionOutcome failed", err) # evidence only
return outcome6. Write rules that use the facts
Rules live in your workspace. These examples refuse special-category data and unscanned content, and ask a person when something is flagged.
# Example rules you write in your workspace for data.export (not in code): # 1. Refuse when sec.pii_categories_band is special_category. # 2. Refuse when sec.dlp_verdict is not_scanned. # 3. Ask a person first when sec.dlp_verdict is flagged. # 4. Otherwise allow.
What it does not do
- It does not send content to Agent Control Room; only verdicts and a fingerprint.
- It never lets a scanner grant. Only Agent Control Room's rules decide.
- It never treats a missing or failed scan as clean.
- It does not retry in a loop, and fails closed when there is no answer.
Identity token verification (TypeScript)
Use this when people or services sign in through Microsoft Entra ID, Okta or another OpenID Connect provider, and your rules should depend on who is asking — their role, or whether a person or a service started the step. It runs in your backend, in front of any of the four recipes above, and turns a verified token into context facts.
Before you start
- Your identity provider's issuer, its public key (JWKS) address, and the audience your API's tokens are issued for
- Tokens issued for your own API — not for Microsoft Graph or another provider's API, which your backend cannot validate
- The same workspace address, server-side API key and registered agent as the other recipes
- Node.js 18 or later with the jose package: npm install jose
1. Configuration from the environment
Checking a token needs only your provider's public keys, so there is no client secret here. The comments show the Entra ID and Okta forms.
// identity.ts — server-side only. Requires: npm install jose
// Checking a token needs only your provider's public keys: no client secret here.
const IDP_ISSUER = process.env.IDP_ISSUER!; // Entra ID: https://login.microsoftonline.com/<tenant-id>/v2.0
// Okta: https://<your-org>.okta.com/oauth2/default
const IDP_JWKS_URL = process.env.IDP_JWKS_URL!; // Entra ID: https://login.microsoftonline.com/<tenant-id>/discovery/v2.0/keys
// Okta: https://<your-org>.okta.com/oauth2/default/v1/keys
const IDP_AUDIENCE = process.env.IDP_AUDIENCE!; // your own API's client ID or application ID URI
const IDP_ROLE_CLAIM = process.env.IDP_ROLE_CLAIM ?? "roles"; // Entra app roles: "roles"; Okta: usually "groups"
const FINANCE_ROLE = process.env.FINANCE_ROLE!; // for example Finance.Approver
const ASSERTER = "identity-verifier"; // the asserter name your context contract accepts2. Verify the token
jose checks the signature against the provider's published keys, plus issuer, audience and expiry. Keys are cached and rotation is followed automatically. Anything wrong throws.
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose";
// Fetches and caches the provider's public keys and follows key rotation.
const jwks = createRemoteJWKSet(new URL(IDP_JWKS_URL));
export async function verifyToken(authorization: string | null): Promise<JWTPayload> {
const token = authorization?.match(/^Bearer (.+)$/i)?.[1];
if (!token) throw new Error("no_token");
const { payload } = await jwtVerify(token, jwks, {
issuer: IDP_ISSUER,
audience: IDP_AUDIENCE,
algorithms: ["RS256"],
requiredClaims: ["iat", "exp"],
clockTolerance: 60,
});
return payload; // signature, issuer, audience and expiry all checked — or it threw
}3. Turn verified claims into facts
Only the facts your rules need, each with who asserted it and when. The time comes from the token itself, so a context contract can turn away old sign-ins.
type Fact = { value: string | boolean; assertedBy: string; observedAt: string };
export function identityFacts(payload: JWTPayload): Record<string, Fact> {
// When the provider issued these claims, so a contract can turn away old sign-ins.
const observedAt = new Date(payload.iat! * 1000).toISOString();
const fact = (value: string | boolean): Fact => ({ value, assertedBy: ASSERTER, observedAt });
const roles = payload[IDP_ROLE_CLAIM];
// Entra ID delegated tokens carry scp; Okta user tokens carry uid. Check your own provider's tokens.
const isPerson = typeof payload.scp === "string" || typeof payload.uid === "string";
return {
"requester.kind": fact(isPerson ? "person" : "service"),
"requester.finance_role": fact(Array.isArray(roles) && roles.includes(FINANCE_ROLE)),
};
// Send what the rules need — not names, email addresses or the token itself.
}4. Ask with the facts
The token arrives with the request from your sign-in, never through the model. A bad token stops here. Otherwise the facts go with decideAction — or as context on decideToolCall in the MCP and LangGraph recipes.
import { createHash, randomUUID } from "node:crypto";
// acrCall and ACR_AGENT: the same configuration and gateway helper as the MCP recipe, steps 1–2.
export async function commitTransaction(req: Request): Promise<Response> {
let context: Record<string, unknown>;
try {
context = identityFacts(await verifyToken(req.headers.get("authorization")));
} catch {
// Fail closed: a missing, invalid or expired token means no request and no work.
return new Response("Sign-in could not be verified.", { status: 401 });
}
const body = await req.json(); // the step the agent proposed
context["effect.amount_band"] = amountBand(body.amount); // your own thresholds
let answer;
try {
answer = await acrCall("decideAction", {
agent: ACR_AGENT,
action: "transaction.commit",
payloadHash: createHash("sha256").update(JSON.stringify(body)).digest("hex"),
context, // verified facts only
}, randomUUID());
} catch {
return new Response("No decision, so nothing ran.", { status: 503 }); // fail closed
}
const effect = answer.decision?.effect;
if (effect === "pending") return new Response("Held for a person.", { status: 202 });
if (effect !== "grant") return new Response("Refused by policy.", { status: 403 });
// ...run the transaction and report the outcome as in the other recipes
}5. Declare the facts and write rules
In your workspace, an enforced context contract makes the facts required and accepts them only from your verifier and only while fresh. Rules then use them like any other fact.
# Context contract for transaction.commit, set in your workspace (not in code): # requester.kind agreed list: person, service required, provenance from identity-verifier, at most 5400 s old # requester.finance_role yes/no required, provenance from identity-verifier, at most 5400 s old # Mode: enforced — a request without valid facts is undecidable: neither allowed nor refused. # # Example rules for transaction.commit: # 1. Refuse when requester.kind is service. # 2. Ask a person first when effect.amount_band is high. # 3. Allow when requester.finance_role is true and effect.amount_band is low or medium. # 4. Otherwise refuse (the default).
What it does not do
- It does not connect Agent Control Room to your identity provider. Your backend verifies the token; Agent Control Room never sees it or calls your directory.
- It does not send the token, names or email addresses — only the facts your rules use.
- It does not replace sign-in, multi-factor authentication or your provider's own access policies.
- It never grants on its own: a valid token only supplies facts, and a missing or invalid token stops the step before anything is asked.