Connect an agent
An agent is connected when it asks the engine before each action. There are eight ways to do that.
| Way | For |
|---|---|
| A hook | Coding agents: Claude Code, Codex, Gemini CLI, Cursor, Grok CLI, Copilot CLI. Personal agents: Hermes Agent, and OpenClaw through a small plugin that runs the hook |
| The MCP gateway | Any MCP server that runs over stdio |
| The remote MCP gateway | Any MCP server reached over HTTP, for agent platforms that take MCP tools. Grok Bot, Dots and Muse are among them |
| A verdict endpoint | An agent on a vendor's computers, where the vendor asks an address of yours before a tool runs: Grok Bot on an xAI Enterprise team |
| A framework adapter | Agents built on the Vercel AI SDK, the OpenAI Agents SDK, LangChain or the Claude Agent SDK |
| A guard on your own endpoint | Agents run by a vendor, such as a support bot, that act by calling an endpoint of yours |
| The Node or Python SDK | Agents you write yourself |
| The HTTP API | Any other language |
See what is connected
The console has an Integrations page, also reachable from Settings. It lists every way on this page, with the agent platforms that use them, and shows which are connected in your workspace.
An integration shows as connected when an action from one of your agents has arrived through it in the last 7 days. It is read from the ledger, not from a saved setting. Each ask says what sent it in its app fact: the hook, the adapter or the gateway. An ask can also name the agent platform on the other side in its platform fact, for example intercom-fin. The setup steps on the Integrations page always include that name, so the platform shows up by name.
| Where | How to name the platform |
|---|---|
| Remote MCP gateway, MCP gateway | --platform intercom-fin |
| Verdict endpoint | --platform grok-bot, which is what it uses when you give none |
| Adapters and endpoint guards, Node | the option platform: 'intercom-fin' |
| Adapters and endpoint guards, Python | the keyword platform="intercom-fin" |
A name is lower-case letters, digits and hyphens. A name the page has no entry for is listed under Other, as it was sent.
The quick way: one prompt or one command
Open Integrations in the console, pick what you want to connect, and choose Paste into your agent or Run in a terminal. You name the agent, say which tools it may use, and sign. The console then shows one line, like this:
curl -fsSL https://app.trycountersign.ai/install.sh | sh -s -- connect codex --token TOKEN
Paste into your agent wraps that line in a short prompt for Claude Code, Codex, Cursor, Gemini CLI, Grok CLI or Copilot CLI. The agent is told to run that one line and nothing else. Run in a terminal gives you the line itself.
Paste the prompt into a session that runs shell commands on the machine you want covered. That means the agent's CLI in a terminal, or a local session in its desktop app (for Claude, the Code tab). It does not mean a chat (the Chat tab of the Claude app, ChatGPT, the Gemini app, Copilot chat), Cowork, or a cloud or background session. Those have no shell on your machine, or run the line on another one: the token would be spent and your machine would have no hook. The prompt tells the agent to check this first and to stop if it is in the wrong place. If you are not sure, use Run in a terminal.
The line does three things on the machine where it runs:
- Installs the CLI to
~/.countersign/bin, after checking the download against its published checksum. - Makes the agent's key there and issues its passport, with exactly the terms you signed. The credential is written to
~/.countersign/agents/NAME.json, readable only by you. - Adds the hook to the agent's own settings file. Hooks that other tools put there are kept. The file as it was is saved beside it as
<file>.before-countersign. An older Countersign hook in that file is replaced.
Then it sends one test action, so there is a receipt to look at. Restart the agent, because an open session does not have the hook. The Integrations page shows Connected at the first tool call.
What to know about the token in that line:
- It works once. A second use is refused.
- It stops working 15 minutes after you sign it, used or not.
- It can only issue a passport with the terms you signed. It cannot read the ledger, approve anything or change a rule.
- The agent's private key is never in it. The key is made on the machine that runs the line. It is not in the console, not on the server and not in the prompt. So a prompt that has been used holds nothing worth stealing.
- Until it is used, treat it like a password.
How a coding agent starts is your choice too, made in the same place. Start by recording is on by default: every action is decided and recorded and no rule stops anything, so you see what your rules would stop before they stop anything. Revoking the passport still stops the agent. When the rules look right, run countersign guard on on that machine. Switch it off before you sign and a rule that says no stops the agent from its first call. connect says which is in force. See Guard.
What the hook does when Countersign cannot be reached is your choice, made in the console before you sign. By default the agent carries on, and what it did is recorded when Countersign answers again, marked as having run while it was unreachable. If you tick "Stop the agent when Countersign cannot be reached", every tool call is blocked until it answers. connect says which is in force, and --fail open or --fail closed on the command line overrides it. See Guard.
For an agent you build (the SDKs, the framework adapters, the endpoint guard), the line ends in connect sdk --token TOKEN --out ./NAME.json. It issues the passport and writes the credential into the project, with no hook. The prompt for these also asks your coding agent to add that file to .gitignore, download the SDK files and put the guard on your tools, and to show you the diff before anything runs. For the MCP gateways there is a command and no prompt, because a gateway is set up by a person on a server.
Not checked yet: the prompt has been run as a command in a clean home folder, not pasted into a live session of each agent. A sandboxed agent may ask you to approve the command, or refuse to reach the network. The terminal line is the way round that.
countersign doctor checks the result at any time. See the CLI reference.
The rest of this page is the same setup by hand.
Before you start
You need two things on the machine where the agent runs.
1. The agent's credential. This is a small JSON file. It holds the engine's address, the workspace id, the passport id and the agent's private key. It lets the holder ask under that passport and nothing else.
- From the console: issue a passport on the Agents page and download
NAME.jsonwhen it is offered. The key is made in your browser and is not kept on the server. If you lose the file, issue a new passport. - From the command line:
countersign agent add --name NAME --tools 'Read,mcp__*'writes~/.countersign/agents/NAME.json.
Keep credentials in ~/.countersign/agents/. A command that takes --agent accepts a bare name, which it looks up in that folder, or a path to the file.
2. The CLI, for hooks and the MCP gateway.
curl -fsSL https://app.trycountersign.ai/install.sh | sh
This installs ~/.countersign/bin/countersign after checking the download against its published checksum. An engine you run yourself serves the same script at its own address.
countersign start does both steps on your own machine for each of Claude Code, Codex, Gemini CLI, Cursor, Grok CLI, Hermes Agent and OpenClaw that it finds. See the Quickstart. The rest of this page is for setting things up by hand.
Hooks
Coding agents can run a command before and after each tool call. countersign hook is that command. It reads the tool call from standard input.
- Before the call it asks the engine. If the answer is allow, the agent carries on with its own permission flow. If the action is blocked, held for a human or refused, the hook stops the tool and gives the agent the reason.
- After the call it reports the outcome for the allowed action, with a hash of the tool's response. The hook always reports
ok. It does not read whether the tool failed.
The hook command is the same for every agent apart from --format:
~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format claude
| Flag | Default | Meaning |
|---|---|---|
--agent | device | The agent's name or the path to its credential file. |
--format | detected | The hook dialect: claude, codex, gemini, cursor, grok, hermes, openclaw or copilot. |
--event | pre or post, for dialects whose payload does not say which. Used for Copilot CLI. | |
--fail | closed | What to do when the engine cannot be reached. closed blocks the tool. open lets it run. |
--mode | the credential's setting | monitor records, and no rule blocks. A revoked passport still stops the tool. enforce blocks. |
--facts | full | full sends the command, path or URL. minimal sends only the kind of action and the program name. |
A hook set up by hand enforces and fails closed unless you say otherwise. To record without blocking, add --mode monitor. See Guard for the two modes and Security and limits for what --facts sends.
Claude Code
Add this to .claude/settings.json in a project, or to ~/.claude/settings.json for every session.
{
"hooks": {
"PreToolUse": [
{
"matcher": "*",
"hooks": [
{ "type": "command", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json" }
]
}
],
"PostToolUse": [
{
"matcher": "*",
"hooks": [
{ "type": "command", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json" }
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{ "type": "command", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json" }
]
}
]
}
}
countersign claude --agent NAME prints this snippet with the right paths for your machine.
The third entry runs when you send a prompt. It is how a key pasted into the conversation is seen. See Secret exposure alerts. Leave it out and tool calls are still decided and recorded.
Codex
countersign start writes the hook to ~/.codex/hooks.json, which has the same shape as the Claude Code file above. To set it up by hand in the main config file, add this to ~/.codex/config.toml.
[features]
hooks = true
[[hooks.PreToolUse]]
matcher = ".*"
[[hooks.PreToolUse.hooks]]
type = "command"
command = '~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format codex'
timeout = 30
[[hooks.PostToolUse]]
matcher = ".*"
[[hooks.PostToolUse.hooks]]
type = "command"
command = '~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format codex'
timeout = 30
[[hooks.UserPromptSubmit]]
[[hooks.UserPromptSubmit.hooks]]
type = "command"
command = '~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format codex'
timeout = 30
Codex skips a new hook until you trust it. The next time the Codex terminal app opens it says "Hooks need review". Choose "Trust all and continue". Until you do, the hook does not run and nothing Codex does is recorded. codex exec never asks and prints nothing about hooks, so open Codex in a terminal once before you rely on it in a script. Codex asks again when the hook's text or its place in the file changes: after connect is run again, or when another tool adds a hook in front of this one. countersign connect codex and countersign start say this when they add the hook, and countersign doctor says when Codex holds no trust record for it.
Seen in Codex CLI 0.167.0 on 29 November 2026, with the hook in ~/.codex/hooks.json: codex exec ran its commands and the hook did not run, and after "Trust all and continue" in the terminal app codex exec ran the hook. An earlier run, on 24 November 2026 with a hooks.json in a project's .codex folder, saw the hook run in codex exec with no trust step. Why that run needed none is not known, and it has not been run again.
countersign doctor reads that record for each of the hook's three events (before a tool call, after it, and when you send a prompt), from [hooks.state."FILE:EVENT:GROUP:HANDLER"] in Codex's config.toml. It fails when Codex holds none for an event and the hook has never asked, because Codex is then skipping it. It notes when the record is of another form of the hook, which is what a changed text or place looks like, and when the hook has asked before with no record, which means something runs Codex with --dangerously-bypass-hook-trust. It fails when the hook is switched off in Codex's /hooks list. It does not trust the hook for you, and doctor --fix does not either: Codex takes this from inside Codex only.
On 30 November 2026 Codex's own answer was put beside doctor's, with no model: its hooks/list request said "untrusted" for a hook just connected, "trusted" once the record held the hash Codex gave for it, and "modified" after the command changed, and doctor failed, passed and noted in the same three places (qa/hooklive/trust-live.sh). The hash doctor compares is computed the way Codex computes it, and was the same as Codex's for each hook.
Gemini CLI
Add this to ~/.gemini/settings.json.
{
"hooks": {
"BeforeTool": [
{
"matcher": ".*",
"hooks": [
{ "type": "command", "name": "countersign", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format gemini" }
]
}
],
"AfterTool": [
{
"matcher": ".*",
"hooks": [
{ "type": "command", "name": "countersign", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format gemini" }
]
}
],
"BeforeAgent": [
{
"hooks": [
{ "type": "command", "name": "countersign", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format gemini" }
]
}
]
}
}
All three entries were run in a live session of Gemini CLI 0.71.1.
Cursor
Add this to ~/.cursor/hooks.json.
{
"version": 1,
"hooks": {
"preToolUse": [
{ "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format cursor", "failClosed": true }
],
"postToolUse": [
{ "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format cursor" }
],
"beforeSubmitPrompt": [
{ "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format cursor" }
]
}
}
The two tool entries were run in a live session of the Cursor agent CLI (2026.11.22). In that CLI's print mode the beforeSubmitPrompt entry does not run, so a key typed into a Cursor prompt is not seen there.
Grok CLI
This is xAI's grok program for the terminal. Add this file as ~/.grok/hooks/countersign.json. Grok reads every file in that folder, so the hook has a file of its own and no other settings are edited.
{
"hooks": {
"PreToolUse": [
{ "matcher": "*", "hooks": [
{ "type": "command", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format grok", "timeout": 15, "failClosed": true }
] }
],
"PostToolUse": [
{ "matcher": "*", "hooks": [
{ "type": "command", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format grok", "timeout": 15 }
] }
],
"PostToolUseFailure": [
{ "matcher": "*", "hooks": [
{ "type": "command", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format grok", "timeout": 15 }
] }
],
"UserPromptSubmit": [
{ "hooks": [
{ "type": "command", "command": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format grok", "timeout": 15 }
] }
]
}
}
Four things to know about Grok:
- Folder trust. Grok runs your hooks only in a folder you have trusted. It asks the first time you open one. Until you say yes, nothing done there is recorded and no rule stops anything. A run with
grok -pcounts the folder as trusted for hooks in~/.grok/hooks, and so does a session in your home folder. Grok keeps the folders in~/.grok/trusted_folders.toml.countersign doctor, run in a folder, reads that file and says when the folder is not one Grok trusts;/hooks-trustin Grok, or starting it with--trust, is how you trust it. Countersign does not trust a folder for you: the trust covers everything the folder holds, its own MCP servers and instructions included. failClosed. Grok lets a call through when its hook crashes or runs out of time."failClosed": trueon thePreToolUseentry makes that stop the call instead.countersign connectwrites it when the agent is set to stop in an outage. Leave it out for a hook with--fail open.- MCP tools. Grok names an MCP tool
server__tool. The hook reads that as kindmcpwithmcp_serverset to the server's name. - Hooks in Claude Code's settings. Grok also runs the hooks in
~/.claude/settings.jsonunless its[compat.claude] hookssetting is off. When Grok has a Countersign hook of its own, the Claude Code hook stands down inside Grok, so a call is asked for once and under Grok's passport. When it has none, the Claude Code hook asks for Grok's calls under Claude Code's passport, withappset togrok.
A build older than this one does not know Grok. Its Claude Code hook, started by Grok, records Grok's calls without their kind. If that hook has no --format, which is how countersign start writes it, a call a rule denies is recorded as blocked and still runs, because Grok does not read the refusal. Update with countersign update.
All four entries were run in live sessions of Grok CLI 1.0.92.
Hermes Agent
Hermes Agent, from Nous Research, runs on your own machine and works across your apps: a terminal, a desktop app, and a gateway for chats such as Telegram and Slack. It keeps its hooks in its settings file, ~/.hermes/config.yaml. Add this section to it.
hooks:
pre_tool_call:
- command: "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format hermes"
timeout: 15
fail_closed: true
post_tool_call:
- command: "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format hermes"
timeout: 15
pre_llm_call:
- command: "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format hermes"
timeout: 15
countersign start and countersign connect hermes add it for you. They do not rewrite the file: they add this one section at the end, between two marker lines, and countersign stop takes exactly those lines out. If the file already has a hooks: section of yours, nothing is changed and you are told to add the entries under it yourself. Each profile under ~/.hermes/profiles has a config.yaml of its own and gets the section too.
Five things to know about Hermes:
- Approval. Hermes runs no hook it has not approved, for that exact command and that exact event. Only a
hermesstarted in a terminal ever asks. Its desktop app, its gateway and its scheduled runs do not: they skip the hook and write a warning in~/.hermes/logs/agent.log, and nothing is recorded. Socountersign startandcountersign connect hermesapprove the hook themselves. They add its three entries to~/.hermes/shell-hooks-allowlist.json, the list Hermes keeps its approvals in and documents writing by hand ("Manual allowlisting" in its hooks guide), and then ask Hermes to confirm withhermes hooks list. Nothing else in that file is changed, andcountersign stoptakes the three entries out again. There is nothing to restart: a new session has the hook at once, and a gateway that is running reads the list again within about 30 seconds. If the approval goes missing,countersign doctorfails and says so, andcountersign doctor --fixputs it back. If you connected with a build before 2026.11.29.6, runcountersign updateand thencountersign doctor --fix. An owner who has sethooks_auto_accept: trueneeds no approval, and none is written. fail_closed. Hermes lets a call through when a hook crashes or runs out of time.fail_closed: trueon thepre_tool_callentry makes that stop the call instead.countersign connectwrites it when the agent is set to stop in an outage. Leave it out for a hook with--fail open.- Prompts are recorded, never stopped.
pre_llm_callruns once for each message a person sends. A key or token in the message is recorded by kind. Hermes gives a hook no way to stop the message, so a rule that blocks such a prompt in other agents is recorded here as one that would have. - Held for a human. An action your rules hold for approval is stopped, and approved in Countersign, as with every other agent. Hermes's own approval prompt is not used.
- No place for a hook users cannot remove. Hermes has no managed settings file, so a rollout does not cover it. Someone who can edit
config.yamlcan take the hook out, and Coverage shows an agent that has gone quiet.
Hermes's tools are sorted into the same kinds as every other agent's: terminal is shell, patch is edit, search_files is search, web_extract is web, delegate_task is agent, and an MCP tool it names mcp__server__tool is mcp.
OpenClaw
OpenClaw runs on your own machine and takes requests from your chats: Telegram, WhatsApp, Slack and the rest. It has no command it runs before a tool call. It has plugins, which run inside its gateway and are told of each call. So Countersign connects through a small plugin of its own that runs the hook.
countersign connect openclaw --token TOKEN # or: countersign start --agents openclaw
This writes four files to ~/.countersign/openclaw-plugin and nothing anywhere else:
| File | What it is |
|---|---|
index.js | The plugin: about 160 lines of JavaScript that uses nothing but Node and OpenClaw's own plugin entry. Read it before you load it. |
openclaw.plugin.json, package.json | What OpenClaw needs to recognise a plugin. |
hooks.json | The hook command to run, in the shape every other agent's hook file has. |
OpenClaw loads a plugin from a folder only when it is told to, with this line:
openclaw plugins install --link ~/.countersign/openclaw-plugin --force --accept-capabilities
From build 2026.11.29.6 the command above runs that line for you, when OpenClaw's program openclaw is on the PATH, and says so. --force tells OpenClaw the plugin comes from a folder, and --accept-capabilities that what it may do is accepted: running connect or start is you accepting it, so read index.js first if you want to. It then asks OpenClaw how the plugin stands, with openclaw plugins inspect countersign --runtime, which answers for OpenClaw's own program and for the gateway that is running. A gateway that is running loads the plugin without a restart. A plugin that comes back switched off, which is what OpenClaw does with one that was installed, taken out and installed again, is switched on with openclaw plugins enable countersign.
Where openclaw is not on the PATH the command prints the line for you to run, says "NOT READY", and exits with an error, because nothing OpenClaw does is recorded until it is run. countersign doctor reads OpenClaw's settings (~/.openclaw/openclaw.json) and fails when the plugin is not in them. countersign doctor --fix installs it.
From then on, before each tool call the plugin hands the call to countersign hook, and stops the call with the reason when the answer is no. After the call it hands over the outcome. countersign stop empties hooks.json, and the plugin then does nothing. openclaw plugins disable countersign takes it out of OpenClaw.
Seven things to know about OpenClaw:
- Update first if you connected before build 2026.11.29.5. The plugin written by builds 2026.11.29.3 and 2026.11.29.4 does not load in OpenClaw, and the line they printed lacked
--accept-capabilities. Runcountersign update, thencountersign start --agents openclawor connect again, which writes the plugin afresh and installs it. openclaw agent execis not covered unless you say where the state is. That command keeps its state in a folder of its own for the one turn, and a plugin installed in your ordinary state is not loaded there: the turn is neither recorded nor stopped. With--state-dir ~/.openclawit loads the plugin and is covered.openclaw agent --localuses your ordinary state and is covered. A gateway was not run.- Where the request came from. Each ask carries
channelwhen OpenClaw says where the request came from:telegram,whatsappand so on, as OpenClaw names it. A rule can use it:action.attrs.channel == 'telegram' && action.tool == 'message'. A turn started at a terminal carries none. The fact follows OpenClaw's documentation and has not been seen in a real turn from a chat. - Tool calls only. The plugin reads no message, prompt or reply, and asks OpenClaw for no access to the conversation. A key typed into a chat is not seen. One in a command or a file the agent writes is.
- When the hook cannot answer. If the hook cannot be started or does not answer in time, the call goes ahead and the plugin says so in OpenClaw's log. With
--fail closedthe call is stopped instead. OpenClaw itself stops a call when a plugin fails outright, so the plugin is written never to do that. - Held for a human. An action your rules hold for approval is stopped, and approved in Countersign, as with every other agent. OpenClaw's own approval prompt is not used.
- No place for a hook users cannot remove. Whoever runs the gateway can disable the plugin. Coverage shows an agent that has gone quiet.
OpenClaw's tools are sorted into the same kinds as every other agent's: exec is shell, apply_patch is edit, sessions_spawn and spawn_agent are agent. Its message tool, which sends a message as you, has no kind of its own: name it in a rule with action.tool == 'message'.
Copilot CLI
Add this file to the repository as .github/hooks/countersign.json.
{
"version": 1,
"hooks": {
"preToolUse": [
{ "type": "command", "bash": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format copilot --event pre", "timeoutSec": 30 }
],
"postToolUse": [
{ "type": "command", "bash": "~/.countersign/bin/countersign hook --agent ~/.countersign/agents/NAME.json --format copilot --event post", "timeoutSec": 30 }
]
}
}
What the agent is told
When the hook stops a tool it answers in that agent's own hook format. The messages are:
| Case | Message to the agent |
|---|---|
| Blocked | Countersign denied this action under rule <rule>: <reason>. Recorded as event <n>. Do not attempt to work around this. |
| Held for a human | Countersign: this action needs a human approval (<reason>). Recorded as event <n>. Ask the user to approve request <id> in Countersign, then retry the same action unchanged. With countersign listen set, the agent is told to end its turn and that it will be told when the request is decided. See Approvals. |
| Retried before approval | Countersign: this action is waiting for a human approval (request <id>). It has not been approved yet. Do not retry until the user confirms it is approved. |
| Refused | Countersign refused this ask: <reason>. Recorded as event <n>. |
| Passport run out | Countersign: this agent's passport has run out, so the action was not authorised. Renew it on the Agents page in Countersign, or run countersign agent amend <name> --ttl 8760h where the workspace's signing key is. Recorded as event <n>. |
| Passport revoked | Countersign: this agent's passport has been revoked, so the action was not authorised. Issue a new one on the Agents page in Countersign. Recorded as event <n>. |
| The engine would not record it | Countersign did not record this action, so it was not authorised: <what the engine said>. |
| Engine unreachable, set to stop | Countersign could not be reached (<error>), and this agent is set to stop when that happens, so the action did not run. Run countersign doctor to see what is wrong. To let the agent work in the meantime, countersign stop takes the hook out. |
A hook set to carry on prints nothing to the agent when the engine is unreachable. It writes one line to its error output the first time, lets the call run and keeps it for later.
The hook is added to the event each agent raises before a tool call, the one after it and, where the agent has one (Claude Code, Cursor, Grok CLI, Copilot CLI), the one for a call that failed. Each entry tells the agent to wait at most 15 seconds for the hook.
Cursor also runs the hooks in Claude Code's ~/.claude/settings.json. When Cursor has a Countersign hook of its own, the Claude Code hook stands down inside Cursor, so a call is asked for once and under Cursor's passport. This follows Cursor's documentation and has not been watched in a live Cursor session.
To put a hook on many machines in a place users cannot edit, see Fleet rollout and Coverage.
MCP gateway
The gateway wraps any MCP server that talks over stdio. The agent and the server do not change.
countersign mcp --agent NAME -- npx -y @modelcontextprotocol/server-github
In the agent's MCP configuration, replace the server's command with the gateway:
{
"mcpServers": {
"github": {
"command": "countersign",
"args": ["mcp", "--agent", "~/.countersign/agents/NAME.json", "--", "npx", "-y", "@modelcontextprotocol/server-github"]
}
}
}
The configuration above runs countersign by name, so the CLI must be on the PATH of the agent that starts it. Otherwise give the full path.
How it behaves:
- Every message passes through untouched except
tools/call. - A tool call is asked for first, under the tool name
mcp__<server>__<tool>. - If the engine allows it, the call is forwarded and its result is reported as the outcome.
- If the engine does not allow it, the server never sees the call. The agent gets the reason back as a tool error.
| Flag | Default | Meaning |
|---|---|---|
--agent | required | The agent's name or the path to its credential file. |
--name | from the command | The server name used in tool names. Without it the gateway derives one from the command line. For npx -y @modelcontextprotocol/server-github it is github. |
--fail | closed | What to do when the engine cannot be reached. closed returns an error to the agent. open forwards the call. |
Facts sent to policy: mcp_server, each top-level argument of the call that is text, a number or true/false, as arg.<name>, cut to 500 characters, and what the server says about the tool, as risk. See Tool risk in the MCP gateway. A rule can read them like this:
action.tool == 'mcp__github__create_issue' && action.attrs['arg.repo'] == 'acme/website'
Three things to know:
- The passport must grant the tool names.
mcp__github__*covers every tool of that server. - The gateway always enforces. It has no recording-only mode and no minimal-facts mode.
- Argument values that look like a credential are blanked before the ask is signed and sent. See Security and limits.
Remote MCP gateway
Many agent platforms cannot run a command on a machine you control. They can use tools from an MCP server at a web address. The remote gateway is for those. You run it next to the MCP server, and you give the agent platform the gateway's address instead of the server's.
countersign gateway --agent support-bot --upstream https://tools.acme.example/mcp --name crm
countersign gateway: http://127.0.0.1:8787/mcp -> https://tools.acme.example/mcp
agent support-bot, tools recorded as mcp__crm__<tool>, engine https://app.trycountersign.ai, fails closed
You run the gateway yourself, on your own machine or in your own cloud. It speaks Streamable HTTP, the transport MCP uses over the web. The older SSE-only transport is not supported.
How it behaves:
- Every request passes through untouched except
tools/call. The listening stream and the end of a session pass through too. - A tool call is asked for first, under the tool name
mcp__<server>__<tool>. - The server's answer to
tools/listis read as it passes, to grade each tool. See Tool risk in the MCP gateway. - If the engine allows it, the call is forwarded and its result is reported as the outcome. This works whether the server answers with one JSON document or with an event stream.
- If the engine does not allow it, the server never sees the call. The agent gets the reason back as a tool error.
- A call that needs a human is answered at once. Nothing waits. After the approval the agent sends the same call again and it goes through. See Approvals.
- A request that is not valid JSON is refused. It is not passed on.
- Requests are forwarded in one fixed form: keys sorted and a repeated key resolved once. The server reads exactly the tool name and arguments that were judged.
- A tool call with no
idis not forwarded. - If one request holds several messages and one tool call in it is not allowed, none of it is sent. Each message gets its own answer.
| Flag | Default | Meaning |
|---|---|---|
--agent | required | The agent's name or the path to its credential file. |
--upstream | required | The address of the MCP server the gateway stands in front of. |
--addr | 127.0.0.1:8787 | The address to listen on. |
--path | /mcp | The path agents connect to. |
--name | from the upstream address | The server name used in tool names. For https://mcp.ramp.com/mcp it is ramp. Set it yourself when the guess is not what you want. |
--fail | closed | What to do when the engine cannot be reached. closed returns an error to the agent. open forwards the call. |
--platform | The agent platform that uses this gateway, for example intercom-fin. It is recorded as a fact and shown on the Integrations page. | |
--tls-cert, --tls-key | Serve HTTPS with this certificate and key. Without them the gateway serves plain HTTP and expects HTTPS to end at a load balancer in front of it. |
One gateway is one agent
A platform such as a support bot cannot sign its own asks. The gateway holds the agent's credential and signs for it. Every call that arrives at a gateway is recorded under that gateway's passport. For two agents, run two gateways on two addresses.
Who may call the gateway
Anyone who can reach the gateway's address can ask under its passport. Limit that in two ways.
- Set
COUNTERSIGN_GATEWAY_KEYto a long random value. The gateway then refuses any request without the same value in theX-Countersign-Keyheader. Set that header in the agent platform's connection settings. The header is removed before the request goes to the server. - If the agent platform cannot send a header of your choosing, put the secret in the address. Run the gateway with a long random
--path, such as--path /mcp/k-7f3a9c2e51d84b06. Only that exact path answers. - Keep the address private to the agent platform where your network allows it.
Sign-in to the server behind it
The gateway does not sign in to the MCP server. Whatever the caller sends, such as an Authorization header or an API key header, goes to the server unchanged. The gateway does not store it, log it or send it to the engine. A refusal from the server, such as a 401, goes back to the caller unchanged.
Requests under /.well-known/ are passed to the server's own origin, so a caller can find the server's sign-in details. Whether a given agent platform completes an OAuth sign-in through the gateway has not been tested.
What it does not do
- It has no recording-only mode and no minimal-facts mode.
- It reports the result of an allowed call only when the result comes back on the answer to that same request. A call whose answer never arrives is recorded as an error.
- It reads at most 8 MB of a request and 8 MB of an answer. A larger request is refused. A larger answer is passed on, and its call is recorded as an error because the result could not be read.
- It does not check requests that the server sends to the agent. Only tool calls from the agent to the server are asked for.
Grok Bot, Dots and Muse
These three are assistants that each work on a computer of their own in the vendor's cloud: xAI's Grok Bot, OpenAI's Dots and Meta's Muse. Nothing can be installed on that computer the way a hook is installed on a laptop. Each can use tools from a server you name, and the remote gateway goes in front of that server.
What this covers is the tools on that server and nothing else. What the assistant does in its own browser, its own shell and the apps the vendor connects for it never passes the gateway, so it is not recorded and no rule of yours can stop it. For Grok Bot there is a second way that does see every tool call: the verdict endpoint.
That has two consequences. An app the assistant reaches through its own built-in connector does not pass the gateway, so connect the apps that matter through the gateway and switch their built-in connectors off. And which tools belong behind the gateway depends on what your team uses the assistant for: purchases, the CRM, customer support. So we set these three up with you on one call, and that setup is part of the Team plan. Ask for the call from the assistant's entry on the Integrations page, under Personal assistants. The steps below are for doing it yourself.
Run the gateway with a long random --path, as in Who may call the gateway, and name the assistant:
countersign gateway --agent grok-bot --upstream https://tools.acme.example/mcp --name crm \
--platform grok-bot --path /mcp/k-7f3a9c2e51d84b06 --addr 0.0.0.0:8787
Grok Bot (--platform grok-bot). This is xAI's cloud agent, not Grok CLI, which has a hook of its own. Paste the gateway's address into a chat with Grok Bot and ask it to add that MCP server. It asks you to confirm, connects, and lists the tools. xAI also documents a form for the same thing: in the desktop app, Connect apps, Add a custom connector, Remote HTTPS, with the address as the Server URL. That form takes HTTP headers, so X-Countersign-Key can stand in for a secret path. On a team, an admin can limit which servers members may add: a server the policy blocks cannot be saved.
How Grok Bot behaves through the gateway:
- Grok Bot speaks Streamable HTTP, which is what the gateway speaks, and sent no sign-in of its own. A secret path was the caller check.
- It names itself
Cursorto the server, never Grok or xAI.--platform grok-botis what tells the record it was Grok Bot. - When a rule held a call, Grok Bot told the person which request to approve, and sent the same call again when asked. The gateway does not tell an assistant that a request was approved: it finds out when it asks again.
- When a rule denied a call, Grok Bot named the rule and its reason and did not try again.
- Grok Bot asks the person itself before some actions. That is the person who gave the order saying yes a second time. A rule of yours still applies after it: a person can say yes to a deletion and the rule still stops it.
Dots (--platform dots). In ChatGPT, open Plugins, press the plus button and choose Add custom MCP server. Enter the gateway's address, with its path, as the MCP server URL, set up sign-in if your server needs it, and choose Create as a plugin. OpenAI asks for Streamable HTTP, which is what the gateway speaks. Its pages name OAuth for sign-in and do not describe a header of your own, so use a secret path. OpenAI gives a custom MCP server full use on ChatGPT Business, Enterprise and Edu, and reading only on Pro. On Business an admin or owner creates the plugin, and a dot uses the plugins installed and enabled for your account.
Muse (--platform muse). Muse makes a custom connector itself when you ask it to. Ask Muse to create a custom connector and give it the gateway's address as a remote MCP server that speaks Streamable HTTP. Muse guides you through the rest. Meta does not review custom connectors. What Muse does in its own apps and browser stays with Meta's own Sentinel, which decides what Muse may do there.
Verdict endpoint
Some agents run on a vendor's computers and cannot run a command of yours, but the vendor will call an address of yours before the agent's tools run and wait for a yes or a no. xAI's Grok Bot does this on Enterprise teams and calls it Inference Hooks. xAI describes it as a beta. countersign verdict is the address it calls.
COUNTERSIGN_VERDICT_SECRET=whsec_... countersign verdict --agent grok-bot
countersign verdict: http://127.0.0.1:8788/verdict
agent grok-bot, platform grok-bot, engine https://app.trycountersign.ai, fails closed, a denied call is stopped
the vendor must reach this over HTTPS on port 443, at a public address with no redirect
You run it yourself, on your own machine or in your own cloud, as you run the gateway. It holds the agent's credential and signs for it.
Set it up
- Make an agent with a passport for Grok Bot and put its credential where the endpoint will run.
- A team admin opens Inference Hooks, under Security & Compliance in the team's dashboard, chooses Set Up Endpoint and enters your address, for example
https://verdict.acme.example/verdict. xAI takes anhttpsaddress on port 443, at a public host, that does not redirect. Saving it the first time shows a signing secret that startswhsec_. - Switch on Validate Tool Calls. Without it xAI sends only prompts, and no tool call is ever asked for.
- Start the endpoint with the secret in
COUNTERSIGN_VERDICT_SECRET. It does not start without one. - Press Test Connection. The endpoint answers the test and records nothing for it.
- Choose what xAI does with a no. See Shadow Mode below.
How it behaves
- Every request is checked against the signing secret first, the Standard Webhooks way. A request with no signature, a wrong one, or a time more than five minutes from this machine's clock is answered 401 and nothing is asked for.
- Before the tool calls in one model response run, xAI sends them in one request. Each call is asked for under the agent's passport, the way a hook asks, with the same facts:
kind,command,file_path,url. - A call to a connected app arrives under xAI's own tool name,
CallMcpTool, with the app's server named beside it. It is asked for asmcp__<server>__<tool>, as it would be through the gateway. - xAI takes one answer for the whole request. It is allowed only when every call in it is allowed. One no stops them all, and a call that was allowed is then recorded as not sent.
- xAI has no answer that means "wait for a person", and waits ten seconds at most. A call a rule holds is answered no at once, with the request to approve named in the reason. After the approval, ask Grok Bot for the same thing again and it goes through. See Approvals.
- The reason goes to the member in Grok Bot's own notice, under "Blocked by your organization's policy". xAI shows at most 500 characters of it. The request id goes back too, and xAI keeps it in its audit log as the reference.
- How a call ended is read from the requests that follow. xAI sends the conversation so far with every model request, tool results included, and the first one that carries a call's result is reported as that call's outcome. xAI's page says its error mark is false for most failed calls too, so "ok" here means the call came back, not that it did what was wanted.
- A request sent twice under the same id, which xAI does when its connection fails, is asked for once and answered the same.
- The conversation in a request stays on your machine. Of each tool call, the engine is sent what a hook would send. Keys and tokens are blanked first, as everywhere else.
| Flag | Default | Meaning |
|---|---|---|
--agent | required | The agent's name or the path to its credential file. |
--addr | 127.0.0.1:8788 | The address to listen on. |
--path | /verdict | The path the vendor posts to. |
--fail | closed | What to answer when the engine cannot be reached. closed answers deny. open answers allow. |
--mode | the credential's own | monitor records every call and always answers allow. enforce answers deny for what a rule stops. |
--platform | grok-bot | The agent platform that calls this endpoint. It is recorded as a fact and shown on the Integrations page. |
--timeout | 4s | How long the engine has to answer before --fail applies. Keep it under the vendor's own limit, which is 5 seconds at xAI unless the admin changed it. |
--tls-cert, --tls-key | Serve HTTPS with this certificate and key. Without them the endpoint serves plain HTTP and expects HTTPS to end at a load balancer in front of it. |
GET /healthz answers ok for a load balancer's health check.
Shadow Mode
xAI's setting for a failed check has three values, and it starts on Shadow Mode. In Shadow Mode xAI asks, logs a deny in its own audit log and runs the call all the same. If the endpoint is enforcing while xAI is in Shadow Mode, the record here says a call was stopped when it ran.
So match the two. While xAI is in Shadow Mode, run the endpoint with --mode monitor: every call is decided and recorded, the record says no rule stopped anything, and Activity shows what your rules would have stopped. When you want the rules to stop things, choose Block the Request or Allow the Request at xAI and run the endpoint without --mode monitor. Those two differ only in what xAI does when your endpoint cannot be reached or answers badly: the first stops the call, the second lets it run.
A revoked passport is the one thing that is answered deny in --mode monitor too.
What it does not do
- It does not see what xAI does not send. xAI's page lists Grok Bot's replies to members, memory tools, the skill loader and tool discovery as not sent, and says its cloud agents, its CLI and its Agent SDK are not covered.
- It does not check an action as it runs. xAI's page says so: a command or an app's action is judged before it starts, and its output is seen only in a later request.
- It does not read prompts. A request that carries a prompt and no tool call is answered allow, and a key typed into a prompt is not looked for.
- It cannot stop one call and let another in the same request go ahead.
- It does not wait for a person's decision.
- It remembers which request was already answered in memory only. After a restart, a request xAI sends again is asked for again.
Node SDK
The SDK is one file with no dependencies: sdk/node/countersign.mjs. The engine also serves it:
curl -fsSLO https://app.trycountersign.ai/sdk/countersign.mjs
Wrap the action:
import { loadAgent } from './countersign.mjs'
const agent = loadAgent('./NAME.json')
// Runs only if Countersign allows it. Throws if denied or waiting for a human.
const result = await agent.guard('payments.send', { to, amount },
() => sendPayment(to, amount),
{ target: to, cost: amount, currency: 'USD' })
guard(tool, args, fn, opts) asks before the action runs.
- If the engine allows it,
fnruns and its outcome is reported:okwhen it returns,errorwhen it throws. - If the engine does not allow it,
guard()throwsCountersignBlockedandfnnever runs. - If the engine cannot be reached,
guard()throws andfnnever runs.
args is hashed on your machine and never sent. Only target, attrs and cost reach the engine.
| Export | Use |
|---|---|
loadAgent(path) | Reads a credential file and returns an agent. |
createAgent({ server, tenant, mandate_id, seed, ans_key, ans_key_file, session }) | The same, from values you already hold. |
agent.ask(tool, args, opts) | Asks and returns the engine's answer without running anything. |
agent.guard(tool, args, fn, opts) | Asks, runs fn only on allow, reports the outcome. |
agent.report(requestId, status, result) | Reports an outcome yourself. status is ok or error. |
CountersignBlocked | The error thrown when the answer is not allow. It has result, needsApproval and requestId. |
encodeTicket(ticket) | Turns a ticket into a header-safe string. |
Options for ask and guard:
| Option | Meaning |
|---|---|
target | What the action touches. |
attrs | Facts for policy to read. An object of text values. |
cost | A whole number in minor units. |
currency | Sent when cost is above zero. It must match the passport's currency. |
parent | The request id of the held action this re-attempts. See Approvals. |
requestId | Your own request id. One is made when you leave it out. |
fn receives one argument: a ticket, as a header-safe string. A service you call can demand it. See Receipt checks.
Python SDK
The SDK is one file: sdk/python/countersign.py. It needs the cryptography package.
curl -fsSLO https://app.trycountersign.ai/sdk/countersign.py
pip install cryptography
Wrap the action:
from countersign import load_agent
agent = load_agent("./NAME.json")
# Runs only if Countersign allows it. Raises if denied or waiting for a human.
result = agent.guard("payments.send", {"to": to, "amount": amount},
lambda: send_payment(to, amount),
target=to, cost=amount, currency="USD")
guard(tool, args, fn, **opts) behaves as in Node. It raises Blocked when the answer is not allow. Blocked has result, needs_approval and request_id.
| Name | Use |
|---|---|
load_agent(path) | Reads a credential file and returns an Agent. |
Agent(server, tenant, mandate_id, seed, session, ans_key, ans_key_file) | The same, from values you already hold. |
agent.ask(tool, args, target, attrs, cost, currency, parent, request_id) | Asks and returns the engine's answer without running anything. |
agent.guard(tool, args, fn, **opts) | Asks, runs fn only on allow, reports the outcome. |
agent.report(request_id, status, result) | Reports an outcome yourself. |
encode_ticket(ticket) | Turns a ticket into a header-safe string. |
If fn takes one argument, it receives the ticket. If it takes none, it is called with none.
Framework adapters
If your agent is built on a framework, you do not wrap each action by hand. An adapter puts the ask in front of every tool the framework runs.
The adapters are one file per language. Each sits next to the SDK file and uses the framework you already have installed.
curl -fsSLO https://app.trycountersign.ai/sdk/countersign.mjs
curl -fsSLO https://app.trycountersign.ai/sdk/countersign-adapters.mjs
curl -fsSLO https://app.trycountersign.ai/sdk/countersign.py
curl -fsSLO https://app.trycountersign.ai/sdk/countersign_adapters.py
pip install cryptography
| Framework | Node | Python |
|---|---|---|
| Vercel AI SDK | guardAiSdkTools | not available, the framework is JavaScript only |
| OpenAI Agents SDK | guardOpenAITools | guard_openai_tools |
| LangChain | langchainMiddleware | langchain_middleware |
| Claude Agent SDK | claudeAgentHooks | claude_agent_hooks |
How every adapter behaves:
- Before a tool runs, the adapter asks. The tool's own name is the tool name in the ask.
- If the engine allows it, the tool runs and its outcome is reported:
ok, orerrorwhen the tool fails. - If the engine does not allow it, the tool does not run. The model gets the reason back as the tool's result, so it can tell the person what happened.
- A call that needs a human is answered at once. After the approval, the model calls the tool again with the same arguments and it goes through. The adapter links the second call to the approval for you. See Approvals.
- If the engine cannot be reached, the tool is blocked unless you set
failtoopen.
Vercel AI SDK
import { generateText } from 'ai'
import { loadAgent } from './countersign.mjs'
import { guardAiSdkTools } from './countersign-adapters.mjs'
const agent = loadAgent('./NAME.json')
const result = await generateText({ model, prompt, tools: guardAiSdkTools(agent, tools) })
guardAiSdkTools takes the tools object and returns the same tools with each execute asked for first. It works the same with streamText and with an agent. A tool with no execute, such as one the model provider runs or one your browser code runs, is returned unchanged and is not checked.
OpenAI Agents SDK
import { Agent } from '@openai/agents'
import { guardOpenAITools } from './countersign-adapters.mjs'
const support = new Agent({ name: 'Support', instructions, tools: guardOpenAITools(agent, [lookup, refund]) })
from agents import Agent
from countersign import load_agent
from countersign_adapters import guard_openai_tools
agent = load_agent("./NAME.json")
support = Agent(name="Support", instructions=instructions, tools=guard_openai_tools(agent, [lookup, refund]))
Function tools are checked. Hosted tools, computer use and shell tools are returned unchanged and are not checked.
LangChain
In Node, hand the adapter the two pieces of LangChain it builds on, from your own install:
import { createAgent, createMiddleware, ToolMessage } from 'langchain'
import { langchainMiddleware } from './countersign-adapters.mjs'
const support = createAgent({
model, tools,
middleware: [langchainMiddleware(agent, { createMiddleware, ToolMessage })],
})
from langchain.agents import create_agent
from countersign_adapters import langchain_middleware
support = create_agent(model, tools, middleware=[langchain_middleware(agent)])
The middleware covers every tool the agent runs, for invoke and ainvoke alike. In Node, options go in a third argument: langchainMiddleware(agent, { createMiddleware, ToolMessage }, { fail: 'open' }).
Claude Agent SDK
import { query } from '@anthropic-ai/claude-agent-sdk'
import { claudeAgentHooks } from './countersign-adapters.mjs'
for await (const message of query({ prompt, options: { hooks: claudeAgentHooks(agent) } })) { /* ... */ }
from claude_agent_sdk import ClaudeAgentOptions, query
from countersign_adapters import claude_agent_hooks
options = ClaudeAgentOptions(hooks=claude_agent_hooks(agent))
This does the same job as the hook for Claude Code, inside your own program and without the CLI. It sends the same facts: the kind of action, and the command, file path or address. It never sends the contents of a file. An allowed call still goes through Claude's own permission flow. If that flow then refuses the call, no outcome is reported for it.
Options
Every adapter takes the same options. In Node they are an object in the last argument. In Python they are keyword arguments.
| Option | Default | Meaning |
|---|---|---|
fail | closed | What to do when the engine cannot be reached. closed blocks the tool. open lets it run. |
facts | full | full sends each top-level argument that is text, a number or true/false to policy as arg.<name>, cut to 500 characters. minimal sends none of them. |
prefix | none | Text put in front of every tool name. With billing., the tool refund is asked for as billing.refund. |
describe | none | A function that adds what policy should read for a call: who it touches and what it costs. |
platform | none | The agent platform on the other side, for example intercom-fin. It is recorded as a fact and shown on the Integrations page. |
describe is how money limits reach a framework tool:
guardAiSdkTools(agent, tools, {
describe: (tool, args) => tool === 'pay'
? { target: args.vendor, cost: args.amount_cents, currency: 'USD', attrs: { region: args.region } }
: {},
})
guard_openai_tools(agent, tools, describe=lambda tool, args:
{"target": args["vendor"], "cost": args["amount_cents"], "currency": "USD"} if tool == "pay" else {})
Facts the adapters send: app (the framework), kind, the arg.<name> facts, and anything describe returns. Values that look like a credential are blanked before the ask is signed and sent, in arguments and in what describe returns.
What the adapters do not do
- They do not persist which calls are waiting for a human. That is kept in memory, per guard or middleware. Make the guard once and keep it for the life of the program. If the program restarts while a call is waiting, the next attempt is held again and needs a new approval.
- They have no recording-only mode. A block stops the tool.
- They do not pass the ticket to your tool. To have a service demand a ticket, use
guard()from the SDK inside the tool. See Receipt checks. - They check only tools your program runs. A tool the model provider runs on its own servers never passes through your program.
- In Python the SDK talks to the engine with blocking calls. Inside an event loop the adapters run them on a thread.
Versions they were run with
Run on 24 November 2026: ai 7.0.181, @openai/agents 0.22.0, langchain 1.6.8 (Node), @anthropic-ai/claude-agent-sdk 0.3.331, express 5.3.0, openai-agents 0.26.0, langchain 1.5.2 (Python), claude-agent-sdk 0.2.188, fastapi 0.165.0. Frameworks change their tool interfaces between major versions. If an adapter stops working after an upgrade, the tests in sdk/tests show how each one is wired.
Guard your own endpoint
Some agents are run by a vendor: a support bot, a sales assistant. You cannot put a hook or an adapter inside them. They act by calling an endpoint of yours, for example to issue a refund. Put the guard on that endpoint. Your server holds the agent's credential and asks on the agent's behalf.
Use this when the platform calls plain HTTP endpoints. If the platform can use tools from an MCP server, the remote MCP gateway does the same job with no code.
Express
import express from 'express'
import { loadAgent } from './countersign.mjs'
import { guardRoute } from './countersign-adapters.mjs'
const agent = loadAgent('./support-bot.json')
const app = express()
app.use(express.json())
app.post('/refunds', guardRoute(agent, 'refund'), (req, res) => {
// Runs only if Countersign allowed this refund.
res.json(issueRefund(req.body))
})
The arguments of the action are the fields of the request body together with the query and path parameters. The body must be parsed before the guard runs. A request whose body was not parsed is passed to your error handler and does not reach your handler. guardRoute returns ordinary middleware, so it works in anything that takes Express middleware.
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
from countersign import load_agent
from countersign_adapters import guard_route
agent = load_agent("./support-bot.json")
app = FastAPI()
class Refund(BaseModel):
order: str
amount: int
@app.post("/refunds")
@guard_route(agent, "refund")
def refund(body: Refund):
# Runs only if Countersign allowed this refund.
return issue_refund(body)
Put @guard_route under the route line. The arguments of the action are the fields of the request body together with the path and query parameters. FastAPI checks the request first, so a malformed request is turned away before anything is asked. It works for def and async def functions.
What the caller gets
If the action is allowed, your handler runs and its result is reported as the outcome: ok for a response below 400, error otherwise.
If it is not allowed, your handler does not run. The caller gets a status of 403 and a body it can read:
{
"error": "Countersign denied this call under rule no-delete: customers are never deleted by an agent. Recorded as event 26.",
"countersign": { "status": "denied", "rule": "no-delete" }
}
status | Meaning | HTTP status |
|---|---|---|
denied | A rule or the passport refused it. | 403 |
held | A human must approve it. request_id names the request. | 403 |
waiting | It was held before and is not approved yet. | 403 |
refused | The ask itself was not valid, for example the passport has expired. | 403 |
unreachable | The engine could not be reached and the guard fails closed. | 503 |
Some bot platforms only read the body of a 200 and show a generic failure for anything else. For those, change the status and tell the bot to read error:
guardRoute(agent, 'refund', { status: { denied: 200, held: 200, waiting: 200 } })
@guard_route(agent, "refund", status={"denied": 200, "held": 200, "waiting": 200})
Take care with this. A bot that treats every 200 as success would tell a customer the refund went through. Set it only after you have seen the bot read the error text.
After a human approves
An approval covers one action, once. To carry it out, send the same request again. The guard links the second request to the approval in one of two ways.
- It remembers. The same process that answered
heldlinks the next identical request by itself. - The caller says which. Send the request id back in the
Countersign-Parentheader. This works after a restart and from another server.
curl -X POST https://api.acme.example/refunds \
-H 'content-type: application/json' -H 'Countersign-Parent: rq_5f0c...' \
-d '{"order":"A1","amount":120}'
The header gives a caller nothing it should not have. The engine accepts the link only if that request was approved, has not been used, and is for exactly this action. A wrong or reused id gets waiting.
A vendor's bot has usually ended the conversation by the time a person approves. The simple pattern is: when the guard answers held, your server keeps the request and its request_id. When the request leaves the list at GET /v1/pending, your server sends it again with the header. The bot only has to tell the customer the request has gone for approval.
Options
guardRoute and guard_route take the options every adapter takes: fail, facts, prefix and describe. On top of those:
| Option | Meaning |
|---|---|
status | The HTTP status for each answer, as above. |
args | Node only. A function of the request that returns the arguments, in place of the default. Use it to leave a field out or to add one from a header. |
The tool name can be a function, to name the action from the request: guardRoute(agent, (req) => ...) in Node, guard_route(agent, lambda args: ...) in Python.
In the handler, the ticket for the allowed action is req.countersign.ticket in Node and current_ticket() in Python. Send it on as the Countersign-Receipt header if a service behind this one checks receipts. See Receipt checks.
Recipes for vendor platforms
None of these was run with the vendor's product. The vendor facts were read from each vendor's own documentation on 24 November 2026. Check them again before you rely on them.
Intercom Fin. A data connector calls your endpoint with GET, POST, PUT, DELETE or PATCH, and you can add your own HTTP headers and tokens. It allows 3 seconds to connect and 30 seconds for the whole response. Guard the endpoint the connector calls. A held action answers at once, well inside that limit. Fin can also use a custom MCP server, signed in with OAuth or an access token. For that, use the remote gateway with a secret --path, because Intercom's page does not say a custom header can be set. Its example address ends in /sse. The gateway speaks Streamable HTTP only, so whether Fin can connect to it is the first thing to check. Intercom's page says data returned to Fin may be shared with the customer, so keep what your endpoint returns fit for the customer to read.
Ada. An API tool calls your endpoint with GET, POST, PUT, PATCH or DELETE, with your own headers and a static token. An agent has at most five active API tools unless Ada raises the limit. Guard the endpoint each tool calls. Ada can also use tools from an MCP server your company runs, and gives each tool call about 30 seconds. For that, use the remote gateway.
A platform with its own integration code, such as Sierra. Where the vendor's integration calls an API of yours, guard that endpoint as above. No public documentation was found on attaching your own MCP server.
For all three, what the bot does with a response that is not a 200 is not written down in the pages read. Try a denied action with the default 403 first. If the bot cannot tell the customer why, use the status option.
What the guard does not do
- It covers only the endpoints you put it on. An action the vendor's platform carries out by itself, such as closing a conversation or editing a record in its own system, never reaches your server. Coverage is the check on those.
- It does not know who the bot is talking to unless your endpoint is told. Put what matters in the request, and name it in
describe. - It does not prove the caller is the bot. Protect the endpoint as you would any other, for example with the token the platform sends.
- Which requests are waiting for a human is remembered in memory only. After a restart, use the
Countersign-Parentheader.
What the SDKs do not do
- They have no recording-only mode. A block stops the action.
- They do not blank credentials. Do not put secrets in
targetorattrs. - They do not set the
kindfact. Send it inattrsif your rules read it. The framework adapters do set it. - They do not wait for approvals unless you pass
wait. See Approvals.
Any other language
An ask is one HTTP POST to /v1/asks with a JSON body. No API key is sent. The agent's signature is the credential. The signature is Ed25519 over a length-prefixed list of fields, so it needs no special library. The Node and Python files are short enough to read as the reference. See the API reference.
Try one ask by hand
countersign ask --agent NAME --tool Read --target src/app.ts
ALLOW policy.default seq 12 request rq_8a41...
ask exits with status 3 when the answer is anything other than allow.