API reference
AgentLock REST API reference: Ed25519 request signing, bearer tokens, the gateway endpoints for actions, results, credentials and messages, error codes and rate limits.
AgentLock sits between an AI agent and the systems it acts on. The agent submits every action to the AgentLock gateway. AgentLock checks the action against the workspace policy, asks a person to approve it when the policy requires that, runs it with credentials from the encrypted vault and returns the result. The agent never receives the secrets.
This reference covers the endpoints that agents, the SDKs, the hook adapters and MCP clients call. Agents, tokens, credentials, policies and approvals are managed in the AgentLock dashboard and the mobile app.
Overview
- Base URL:
https://app.agentlock.net - Format: JSON request and response bodies, UTF-8.
- Authentication: Ed25519 request signing or an agent token. See Authentication.
- OpenAPI 3.1 specification: https://app.agentlock.net/docs/openapi.json
Every action follows the same lifecycle:
- The agent sends
POST /api/gateway/requestwith a tool name, a declared action type and a payload. - The gateway authenticates the agent, applies rate limits and evaluates the policy. The response carries one of three decisions:
ALLOW: the action runs without a person. StatusALLOWED.REQUIRE_APPROVAL: the action waits for a person in the dashboard or the mobile app. StatusPENDING, HTTP 202.BLOCK: nothing runs. StatusBLOCKED.
- For
ALLOWEDandPENDING, the agent pollsGET /api/gateway/result/{requestId}until the status is final, or receives a webhook.
Browser actions inside an open browser session are the exception: they run immediately and return their result in the response to POST /api/gateway/request.
Client packages:
- Node.js SDK: agentlock-sdk-node
- Python SDK: agentlock-sdk
- MCP server for stdio clients such as Claude Desktop and Cursor: agentlock-mcp-server
- Hook adapters for Claude Code, Codex, Gemini CLI and OpenCode: see permission routing.
Authentication
Every endpoint in this reference acts on behalf of one agent. An agent authenticates in one of two ways.
| Method | Headers | Accepted by |
|---|---|---|
| Request signing | x-agent-id, x-timestamp, x-nonce, x-signature, x-signature-version | All /api/gateway/* endpoints except permission routing |
| Agent token | Authorization: Bearer <token> | All endpoints in this reference |
When a request carries an Authorization: Bearer header, the gateway uses token authentication and ignores the signing headers.
Agent tokens
- An agent token is created in the dashboard: Agents, then the agent, then the Tokens tab. Tokens start with
alt_. - The token is shown once. AgentLock stores only a SHA-256 hash of it.
- A token expires after 30 days by default and after at most 90 days. An agent can have up to 10 active tokens.
- A token can be revoked at any time. Engaging the workspace kill switch suspends all agents and revokes all tokens.
- Token requests skip the signature and nonce checks. Policy evaluation, rate limits and idempotency work exactly as with signed requests.
- Use a token for the hook adapters, the MCP endpoint, hosted MCP clients and any client that cannot keep an Ed25519 key.
Request signing
Each agent has an Ed25519 key pair. The public key is registered in the dashboard when the agent is created; the private key stays with the agent. generateKeypair() (Node.js) and generate_keypair() (Python) create one.
Both keys are base64 encoded. The public key has 32 bytes. The private key is the 64-byte Ed25519 secret key (the 32-byte seed followed by the public key) as produced by tweetnacl and libsodium.
| Header | Value |
|---|---|
x-agent-id | The agent's UUID. |
x-timestamp | Current time in Unix milliseconds as a decimal string. It must be within 5 minutes of the server time. |
x-nonce | Base64 of 16 random bytes. A new value for every request. |
x-signature-version | 2 |
x-signature | Base64 Ed25519 detached signature over the pre-image below. |
The version 2 pre-image is six fields joined with a line feed (\n) and encoded as UTF-8:
2
<METHOD>
<path>
<x-timestamp>
<x-nonce>
<canonical body>METHODis the HTTP method in upper case.pathis the URL path without host and query string, for example/api/gateway/result/7d9f3c2e-1a4b-4c8d-9e6f-0a1b2c3d4e5f.canonical bodyis the canonical JSON of the signed body.
Canonical JSON:
- Object keys are sorted at every level in UTF-16 code unit order (the default JavaScript sort).
- No whitespace between tokens.
- Object members whose value is
undefinedare left out.undefinedarray elements becomenull. NaNand infinite numbers becomenull.- Strings and numbers are encoded as
JSON.stringifyencodes them.
The signed body depends on the endpoint:
| Request | Signed body |
|---|---|
POST /api/gateway/request | The JSON request body |
POST /api/gateway/messages | The JSON request body |
GET /api/gateway/result/{requestId} | {"requestId":"<requestId>"} |
GET /api/gateway/messages | {"_poll":"messages"} |
GET /api/gateway/credentials | {} |
GET /api/gateway/ssh-sessions | {} |
Query string parameters are not signed.
Replay protection. The gateway stores every nonce for 10 minutes and answers a repeated nonce with HTTP 409 Replay detected. A retry, including a retry after HTTP 429 or 5xx, therefore needs new headers: a new timestamp, a new nonce and a new signature.
Retries in the client packages. agentlock-sdk-node 0.6.0, agentlock-sdk (Python) 0.5.0 and agentlock-mcp-server 0.5.0 retry HTTP 429, 502, 503 and 504 and sign every attempt anew. An action request always carries an idempotency_key: the caller's, or a random one the client creates once and sends with every attempt of the same call, so a retry after a 5xx returns the first request instead of creating a second action. Browser actions inside a session and message posts are not stored under a key, so they are retried only after HTTP 429, which the gateway sends before it processes a request. Older versions resend the same signed request after 429 or 5xx and get HTTP 409 Replay detected; call the method again.
Older schemes. x-signature-version: 1 selects the version 1 pre-image <canonical body>:<timestamp>:<nonce>:1. A request without x-signature-version is checked against the version 1 pre-image and then against <canonical body>:<timestamp>:<nonce>. Neither binds the method and the path. Use version 2.
Signing without an SDK, in Node.js with tweetnacl:
import nacl from 'tweetnacl';
import { randomBytes } from 'node:crypto';
function canonical(value) {
if (typeof value === 'number' && !Number.isFinite(value)) return 'null';
if (value === null || typeof value !== 'object') return JSON.stringify(value);
if (Array.isArray(value)) {
return `[${value.map((v) => (v === undefined ? 'null' : canonical(v))).join(',')}]`;
}
const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
}
export function signHeaders({ agentId, privateKey, method, path, body }) {
const timestamp = Date.now().toString();
const nonce = randomBytes(16).toString('base64');
const preimage = ['2', method.toUpperCase(), path, timestamp, nonce, canonical(body)].join('\n');
const signature = nacl.sign.detached(
new TextEncoder().encode(preimage),
new Uint8Array(Buffer.from(privateKey, 'base64')),
);
return {
'x-agent-id': agentId,
'x-timestamp': timestamp,
'x-nonce': nonce,
'x-signature-version': '2',
'x-signature': Buffer.from(signature).toString('base64'),
};
}Authentication errors
| Status | error | Cause |
|---|---|---|
| 400 | Invalid agent ID format | x-agent-id is not a UUID. |
| 401 | Unauthorized | Unknown agent, missing nonce, invalid signature, timestamp outside the 5-minute window or unsupported signature version. |
| 401 | Invalid or expired token | The token is unknown, expired or revoked. |
| 401 | Missing x-agent-id header or Authorization token | The request carries neither. |
| 403 | Agent inactive | The agent is suspended or revoked. |
| 409 | Replay detected | The nonce was used before. |
Some endpoints word these errors differently; each endpoint section lists its own.
Quick start
Node.js:
import { AgentLockClient } from 'agentlock-sdk-node';
const client = new AgentLockClient({
baseUrl: 'https://app.agentlock.net',
agentId: process.env.AGENT_ID!,
privateKey: process.env.AGENT_PRIVATE_KEY!,
});
const submitted = await client.requestAction({
action_type: 'read',
tool: 'http',
payload: {
method: 'GET',
url: 'https://api.example.com/items',
credential_name: 'example-api',
},
});
if (submitted.status === 'BLOCKED') {
console.error('Blocked:', submitted.message);
} else {
const final = await client.awaitResult(submitted.request_id);
console.log(final.status, final.result ?? final.error);
}Python:
import os
from agentlock import AgentLockClient
with AgentLockClient(
base_url="https://app.agentlock.net",
agent_id=os.environ["AGENT_ID"],
private_key=os.environ["AGENT_PRIVATE_KEY"],
) as client:
submitted = client.request_action(
action_type="read",
tool="http",
payload={
"method": "GET",
"url": "https://api.example.com/items",
"credential_name": "example-api",
},
)
if submitted.status == "BLOCKED":
print("Blocked:", submitted.message)
else:
final = client.await_result(submitted.request_id)
print(final.status, final.result or final.error)curl with an agent token:
curl -sS -X POST https://app.agentlock.net/api/gateway/request \
-H "Authorization: Bearer $AGENTLOCK_TOKEN" \
-H "Content-Type: application/json" \
-d '{"action_type":"read","tool":"http","payload":{"method":"GET","url":"https://api.example.com/items"}}'
curl -sS https://app.agentlock.net/api/gateway/result/<request_id> \
-H "Authorization: Bearer $AGENTLOCK_TOKEN"Gateway endpoints
Responses from POST /api/gateway/request carry an x-request-id header that identifies the HTTP request. Quote it when you contact support.
POST /api/gateway/request
Submits an action for policy evaluation and execution.
Authentication: request signing (signed body: the request body) or agent token.
Request body:
| Field | Type | Required | Description |
|---|---|---|---|
action_type | read, write, financial or admin | Yes | The declared risk class. The server raises it when the tool or payload warrants a higher class and never lowers it. |
tool | string, 1 to 100 characters of A-Z a-z 0-9 . _ - : | Yes | The tool to run. See Tools and payloads. |
payload | object, at most 64 KB as JSON | Yes | The tool's parameters. |
idempotency_key | string, at most 128 characters | No | A repeated request from the same agent with the same key returns the first request instead of creating a new one. Blocked requests and browser actions inside a session are not stored, so a repeat of them is evaluated and run again. |
cost_estimate | number, at least 0 | No | Compared with the policy's limits.maxCostPerAction. |
webhook_url | HTTPS URL, at most 2048 characters | No | Receives the outcome. See Webhooks. Private and internal hosts are rejected. |
{
"action_type": "write",
"tool": "http",
"payload": {
"method": "POST",
"url": "https://api.example.com/orders",
"body": { "item": "widget", "quantity": 10 },
"credential_name": "example-api"
},
"idempotency_key": "order-2026-12-02-001"
}Do not put secrets in a payload. The payload is redacted before it is stored and executed, so a secret in a header or field arrives at the target as [REDACTED]. Reference vault credentials by name instead.
Response 200, ALLOW. The action has been accepted and execution has started. Poll the result endpoint for its output.
{
"request_id": "7d9f3c2e-1a4b-4c8d-9e6f-0a1b2c3d4e5f",
"decision": "ALLOW",
"status": "ALLOWED"
}Response 202, REQUIRE_APPROVAL. The action waits for a person until expires_at. The approval window is set per workspace and defaults to 5 minutes.
{
"request_id": "7d9f3c2e-1a4b-4c8d-9e6f-0a1b2c3d4e5f",
"decision": "REQUIRE_APPROVAL",
"status": "PENDING",
"expires_at": "2026-12-02T10:05:00.000Z"
}Response 200, BLOCK. Nothing runs. The request_id of a blocked request is not stored and cannot be polled.
{
"request_id": "0b6e4f1d-2c3a-4e5f-8a9b-1c2d3e4f5a6b",
"decision": "BLOCK",
"status": "BLOCKED",
"message": "Admin actions are not permitted by policy"
}Response 200, in-session browser action. A browser action with a session_id runs immediately and returns its result. The request_id cannot be polled.
{
"request_id": "0b6e4f1d-2c3a-4e5f-8a9b-1c2d3e4f5a6b",
"decision": "ALLOW",
"status": "ALLOWED",
"result": {
"session_id": "bs_5e1c2d3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f",
"snapshot": "- heading \"Orders\" [level=1]\n- button \"New order\"",
"page_url": "https://shop.example.com/orders",
"page_title": "Orders",
"action_performed": "Clicked \"text=New order\""
}
}Response 200, idempotent repeat. A request with an idempotency_key this agent used before returns the first request. status is the first request's current approval status, with APPROVED reported as ALLOWED.
{
"request_id": "7d9f3c2e-1a4b-4c8d-9e6f-0a1b2c3d4e5f",
"decision": "REQUIRE_APPROVAL",
"status": "PENDING",
"idempotent": true,
"expires_at": "2026-12-02T10:05:00.000Z"
}Errors:
| Status | error | Cause |
|---|---|---|
| 400 | Invalid JSON body | The body is not valid JSON. |
| 400 | Invalid request body | The body does not match the schema. |
| 400 | Validation message | webhook_url is not an allowed HTTPS URL, or a permission.claude_code payload does not match its tool input. |
| 400 | credential_id must be a UUID | Also credential_id and credential_name refer to different credentials. See HTTP. |
| 400 | ssh.open requires credential_id in payload | Also Sessioned SSH actions require session_id in payload and Browser actions require session_id in payload. |
| 400 | This SSH credential has no stored host and user, so no session can be opened with it. Add the server again under Credentials in the dashboard, then use the new credential. | The SSH credential was stored before host and user were kept with it. Editing it does not add them. |
| 401, 400, 409 | See Authentication errors | |
| 403 | Agent inactive | The agent is suspended or revoked. |
| 403 | Tool '<tool>' not permitted for this agent | The agent's tool allowlist does not contain the tool. The body also carries request_id, decision: "BLOCK" and status: "BLOCKED". |
| 403 | Credential assignment refusal | The named credential is assigned to other agents only. |
| 403 | Browser sessions are not available on your plan. Upgrade to Pro or Team. | Also the matching message for persistent SSH sessions. |
| 403 | The policy's reason | An in-session browser action the policy blocks (status: "BLOCKED") or would send for approval (status: "DENIED"), or safe mode is on (Safe mode active: all agent activity is blocked). The body also carries request_id, decision and the same text in message. |
| 403 | SSH session does not belong to this agent | Also Session does not belong to this agent for browser sessions. |
| 404 | Credential "<name>" not found in this workspace | Also Credential <id> not found in this workspace, SSH credential not found, SSH session not found and Browser session not found. |
| 410 | SSH session is not active | Also SSH session has expired, Browser session is not active and Browser session has expired. |
| 423 | Workspace kill-switch is engaged. Contact a workspace admin to release it. | The body also carries request_id, decision: "BLOCK" and status: "BLOCKED". |
| 429 | Rate limit exceeded | See Rate limits and quotas. |
| 429 | Hourly action limit exceeded | The policy's limits.maxActionsPerHour is reached. |
| 429 | Action limit reached | The plan's monthly action quota is used up. |
| 429 | Concurrent browser session limit reached (...) | Also the SSH equivalent. |
| 500 | Browser action failed or a specific browser error | An in-session browser action failed. |
| 503 | Unable to schedule action. Please retry. | A temporary failure. Also returned when a credential assignment cannot be verified. |
GET /api/gateway/result/{requestId}
Returns the status and, once available, the result of a request.
Authentication: request signing (signed body: {"requestId":"<requestId>"}) or agent token.
Path parameter: requestId, the UUID returned by POST /api/gateway/request. Only requests of the calling agent are visible.
Response 200:
{
"status": "SUCCEEDED",
"result": {
"status": 201,
"ok": true,
"headers": { "content-type": "application/json" },
"body": { "id": "ord_123", "created": true }
},
"error": null
}| Field | Description |
|---|---|
status | See Statuses. |
result | The redacted tool output, present once the action has run. The shape depends on the tool. |
error | For FAILED, why the action failed, for example the target's or the policy's refusal. Paths, URLs, stack frames and secrets are removed, and the text is at most 500 characters. Otherwise null or absent. |
Poll until the status is final: SUCCEEDED, FAILED, DENIED, EXPIRED or UNDONE. An interval of 2 to 5 seconds stays well inside the rate limit.
Errors:
| Status | error | Cause |
|---|---|---|
| 400 | Invalid request ID | The path parameter is not a UUID. |
| 400 | Invalid agent ID format | x-agent-id is not a UUID. |
| 401 | Unauthorized | Unknown or inactive agent, missing nonce or invalid signature. |
| 401 | Invalid or expired token | The token is unknown, expired or revoked. |
| 404 | Request not found | No such request for this agent. Blocked requests are never stored. |
| 409 | Replay detected | The nonce was used before. |
| 429 | Rate limit exceeded | More than 60 polls per minute for this agent. |
| 503 | Execution status is temporarily unavailable. Please retry. | A temporary failure. |
GET /api/gateway/credentials
Lists the vault credentials this agent may use: those assigned to the agent and those assigned to no agent. Secret values are never returned.
Authentication: request signing (signed body: {}) or agent token.
Response 200:
{
"credentials": [
{ "name": "example-api", "type": "api_key" },
{ "name": "shop-login", "type": "login" }
]
}type is one of the credential types.
Errors:
| Status | error | Cause |
|---|---|---|
| 401 | Missing Authorization header or x-agent-id | The request carries neither. |
| 401 | Invalid agent id | x-agent-id is not a UUID. |
| 401 | Unauthorized | Unknown agent, missing nonce or invalid signature. |
| 401 | Invalid or expired token | The token is unknown, expired or revoked. |
| 403 | Agent not found or inactive | Also Agent inactive. |
| 409 | Replay detected | The nonce was used before. |
| 429 | Rate limit exceeded | More than 60 requests per minute for this agent. |
GET /api/gateway/messages
Returns messages from the workspace members to this agent: replies to approvals, denial reasons and direct messages from the dashboard or the mobile app.
Authentication: request signing (signed body: {"_poll":"messages"}) or agent token.
Query parameters:
| Parameter | Default | Description |
|---|---|---|
since | ISO 8601 time. Only messages created after it. An unparsable value is ignored. | |
limit | 20 | 1 to 50. |
include_read | false | true also returns read messages and the agent's own messages. |
thread_id | A thread UUID. Only messages of that thread. Any other value returns HTTP 400 thread_id must be a UUID. |
By default the endpoint returns unread messages from people and marks them as read, so each message is delivered once. Messages are ordered oldest first. Expired messages are not returned.
A lost response. The messages are marked as read while the response is sent. If the response does not arrive, for example because of a 502 or 504 on the way, the next default call does not return them again. Call again with include_read=true and since set to the time of the last response you received: the answer then holds every message since that time, read or unread, including the agent's own, so keep those with sender_type: "user" that you have not handled yet. Set since, because without it the oldest messages come first. If the answer holds limit messages, call again with since set to the created_at of the last one.
Response 200:
{
"messages": [
{
"id": "3c4d5e6f-7a8b-4c9d-8e0f-1a2b3c4d5e6f",
"thread_id": "9a8b7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d",
"sender_type": "user",
"sender_id": "5f6e7d8c-9b0a-4b1c-8d2e-3f4a5b6c7d8e",
"content": "Approved. Use the staging endpoint next time.",
"metadata": {},
"expires_at": "2027-01-01T10:00:00.000Z",
"read_at": null,
"created_at": "2026-12-02T10:00:00.000Z"
}
]
}Errors: the authentication errors; 400 thread_id must be a UUID; 429 Rate limit exceeded above 60 requests per minute for this agent; 500 Failed to fetch messages.
POST /api/gateway/messages
Sends a message from the agent to the workspace members, either as a reply in an existing thread or as the first message of a new thread.
Authentication: request signing (signed body: the request body) or agent token.
Request body, reply:
| Field | Type | Required | Description |
|---|---|---|---|
thread_id | UUID | Yes | The thread to reply in, taken from a received message. |
content | string, 1 to 4096 characters | Yes | The message text. |
metadata | object, at most 8 KB as JSON | No | Free-form data stored with the message. |
Request body, new thread:
| Field | Type | Required | Description |
|---|---|---|---|
create_thread | true | Yes | Starts a new thread. |
content | string, 1 to 4096 characters | Yes | The first message. |
subject | string, at most 200 characters | No | The thread title shown in notifications. |
metadata | object, at most 8 KB as JSON | No | Free-form data stored with the message. |
Response 201, reply:
{
"message": {
"id": "4d5e6f7a-8b9c-4d0e-9f1a-2b3c4d5e6f7a",
"thread_id": "9a8b7c6d-5e4f-4a3b-9c2d-1e0f9a8b7c6d",
"sender_type": "agent",
"sender_id": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"content": "Done. The report is ready.",
"metadata": {},
"expires_at": null,
"created_at": "2026-12-02T10:01:00.000Z"
}
}Response 201, new thread: { "thread": { "id": "<uuid>", "subject": "Deploy finished" }, "message": { ... } }. subject is null when none was sent.
Errors:
| Status | error | Cause |
|---|---|---|
| 400 | Invalid JSON body | The body is not valid JSON. |
| 400 | Invalid request body | The body does not match either schema. details lists the failing fields. |
| 401, 400, 409 | See Authentication errors | |
| 403 | Monthly message limit reached (...) | Also Thread limit per agent reached (...). See Rate limits and quotas. |
| 404 | Conversation not found. | The thread does not exist or belongs to another agent. |
| 429 | Rate limit exceeded | More than 60 requests per minute for this agent. |
| 503 | Messaging is temporarily unavailable. Please try again. | A temporary failure. |
GET /api/gateway/ssh-sessions
Lists the agent's open SSH sessions, most recently used first. An agent uses it to find a session it opened in another process.
Authentication: request signing (signed body: {}) or agent token.
Response 200:
{
"sessions": [
{
"session_id": "ss_2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e",
"host": "build-01.example.com",
"port": 22,
"user": "deploy",
"via_vpn": false,
"expires_at": "2026-12-02T10:20:00.000Z",
"last_activity_at": "2026-12-02T10:04:12.000Z",
"action_count": 3
}
]
}Only active sessions that have not expired are listed.
Errors:
| Status | error | Cause |
|---|---|---|
| 400 | Invalid agent ID format | x-agent-id is not a UUID. |
| 401 | Missing x-agent-id | The request carries neither signing headers nor a token. |
| 401 | Unauthorized | Unknown or inactive agent, missing nonce or invalid signature. |
| 401 | Invalid or expired token | The token is unknown, expired or revoked. |
| 409 | Replay detected | The nonce was used before. |
| 429 | Rate limit exceeded | More than 60 requests per minute for this agent. |
POST /api/gateway/permission-routing
Decides a tool call of a coding agent (Claude Code, Codex, Gemini CLI, OpenCode) before it runs. The AgentLock hook adapters call this endpoint from the agent's pre-tool hook. A custom adapter follows the same protocol.
Authentication: agent token only.
The agent's routing mode is set in the dashboard under Tool permission routing:
bypass(default): AgentLock stays out of the way. Every call returnsask_localand nothing is recorded.gateway: AgentLock decides. Calls without a matching rule go to the approval inbox.terminal: AgentLock classifies, applies the rules and records every call, and hands calls without a matching rule to the agent's own terminal prompt. Calls that need two approvers still go to the approval inbox.
Request body: the hook input of the coding agent.
| Field | Type | Required | Description |
|---|---|---|---|
tool_name | string, 1 to 100 characters | Yes | For example Bash, Edit, Write, MultiEdit, NotebookEdit. |
tool_input | object | No | The tool's arguments, for example { "command": "git push" }. |
hook_event_name | string, at most 100 characters | No | For example PreToolUse. |
session_id | string, at most 200 characters | No | The coding agent's session. |
transcript_path | string, at most 1000 characters | No | |
cwd | string, at most 1000 characters | No | Working directory. |
permission_mode | string, at most 100 characters | No | |
permission_suggestions | array | No |
AgentLock classifies Bash, Edit, MultiEdit, NotebookEdit and Write. A Bash command is read when it looks read-only, admin when it matches a high-impact pattern and write otherwise, including every compound command; file edits are write. The policy's claudeBash rules match Bash commands. See Policies. Other tool names are decided like an unmatched call, so in gateway mode they go to the approval inbox; register the hook only for the tools AgentLock should decide.
Response 200: one of four decisions.
decision | Meaning | What the adapter does |
|---|---|---|
allow | A policy rule allows the call. | Lets the call run. |
deny | A policy rule blocks the call, the kill switch or safe mode is on, or the call cannot be shown to an approver in full. | Blocks the call and shows reason. |
ask_local | Bypass or terminal mode. | Falls back to the agent's own permission prompt. |
forward | An approver must decide. | Submits action to POST /api/gateway/request with the same token, polls the result and allows the call only on SUCCEEDED. |
{
"decision": "forward",
"mode": "gateway",
"reason": "Shell command may mutate local or external state — no matching claudeBash rule, gateway default is approval",
"action": {
"action_type": "write",
"tool": "permission.claude_code",
"payload": {
"source": "claude_code",
"hook_event_name": "PreToolUse",
"session_id": "a1b2c3",
"cwd": "/home/dev/project",
"permission_mode": "default",
"tool_name": "Bash",
"action_type_hint": "write",
"classification_reason": "Shell command may mutate local or external state",
"tool_input": { "command": "git push origin main" },
"input_sha256": "<hex SHA-256 of the canonical JSON of tool_input>",
"command": "git push origin main"
}
}
}allow and deny decisions that come from a rule also carry matched_pattern. Submit action unchanged: the gateway refuses a permission.claude_code payload whose fields or input_sha256 do not match its tool_input (HTTP 400).
Errors:
| Status | error | Cause |
|---|---|---|
| 400 | Invalid hook input | The body is not valid JSON or does not match the schema. |
| 401 | Authorization: Bearer <agent token> is required | No token. |
| 401 | Invalid or expired token | The token is unknown, expired or revoked. |
| 403 | Agent inactive or not found | |
| 429 | Rate limit exceeded | More than 120 decisions per minute for this agent. Bypass mode is not limited. |
Hook adapters. Ready-made adapters are published at https://app.agentlock.net/hooks/: claude-code-agentlock-hook.mjs, codex-agentlock-hook.mjs, gemini-agentlock-hook.mjs and opencode-agentlock-plugin.mjs. Each imports hooks/core.mjs from the same location; keep both files in the same layout. The agent's detail page in the dashboard shows the setup for each tool. The adapters read these environment variables:
| Variable | Default | Description |
|---|---|---|
AGENTLOCK_URL | https://app.agentlock.net | Base URL. |
AGENTLOCK_TOKEN | Agent token. Without it the adapter defers to the local prompt. | |
AGENTLOCK_HOOK_TIMEOUT_MS | 300000 | How long to wait for an approval. |
AGENTLOCK_HOOK_POLL_MS | 2000 | Result polling interval. |
AGENTLOCK_HOOK_FALLBACK | deny | ask falls back to the local prompt when AgentLock cannot be reached; deny blocks the call. |
MCP endpoint
POST /api/mcp
An MCP server over Streamable HTTP for remote MCP clients that cannot start a local process. It speaks JSON-RPC 2.0 over HTTP POST with protocol version 2025-03-26 and returns one JSON response per request. For local clients, the agentlock-mcp-server package offers more tools over stdio.
Authentication: agent token, required for every method except initialize, ping and notifications.
| Method | Token | Result |
|---|---|---|
initialize | No | protocolVersion, capabilities and serverInfo. |
ping | No | {} |
notifications/* | No | HTTP 202 with an empty body. |
tools/list | Yes | The two tools below. |
tools/call | Yes | The tool's result as MCP content. |
Tools:
| Tool | Arguments | Description |
|---|---|---|
request_action | action_type, tool, payload, optional idempotency_key | Calls POST /api/gateway/request and returns its JSON response as text. A refusal by the gateway returns isError with http_status and the gateway's body. A final status other than SUCCEEDED is an error as well, for example BLOCKED, which arrives with HTTP 200. ALLOWED and PENDING are not errors; poll them with get_result. |
get_result | request_id, optional timeout_ms | Polls the result every 2 seconds for up to timeout_ms (1000 to 30000, default 30000) and returns the result JSON as text once the status is final: SUCCEEDED, FAILED, DENIED, EXPIRED or UNDONE. Every final status except SUCCEEDED returns isError. A refusal such as 404 for an unknown request ends polling at once and returns isError with http_status; 429 and 5xx are retried within timeout_ms. Without a final status in time it returns isError with Timeout: result not ready after <n>ms; call it again. |
isError follows the rule of agentlock-mcp-server: only SUCCEEDED counts as success.
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "request_action",
"arguments": {
"action_type": "read",
"tool": "http",
"payload": { "method": "GET", "url": "https://api.example.com/items" }
}
}
}Client configuration:
{
"mcpServers": {
"agentlock": {
"type": "streamable-http",
"url": "https://app.agentlock.net/api/mcp",
"headers": { "Authorization": "Bearer <agent token>" }
}
}
}Errors:
| HTTP | JSON-RPC code | Cause |
|---|---|---|
| 400 | -32700 | The body is not valid JSON. |
| 400 | -32600 | The body is not a JSON-RPC 2.0 request. |
| 401 | -32001 | Missing or invalid token. |
| 403 | -32001 | The agent is not active. |
| 404 | -32601 | Unknown method. |
| 429 | -32000 | More than 60 calls per minute for this agent. Retry-After: 60. |
| 200 | -32602 | tools/call without a known tool name. |
GET /api/mcp returns 405; this endpoint does not stream. DELETE /api/mcp ends nothing and returns an empty result, since the endpoint keeps no session.
Tools and payloads
The tool field selects what AgentLock runs. Use the tool names exactly as listed here.
HTTP
Tool http (also http.request). Sends an HTTP request from AgentLock's servers.
| Payload field | Description |
|---|---|
method | GET, POST, PUT, PATCH or DELETE. Default GET. The policy's http.allowedMethods applies. Every other method, HEAD and OPTIONS included, is blocked with HTTP method <METHOD> is not supported; use GET, POST, PUT, PATCH, DELETE. |
url | http or https URL. Private, loopback and cloud metadata addresses are refused. |
headers | Object of request headers. Authorization, Cookie, Host, Proxy-Authorization, the X-Forwarded-* headers and hop-by-hop headers are dropped. |
body | Any JSON value, sent JSON encoded. |
credential_id | ID of an API key credential to send as Authorization: Bearer <key>. It takes precedence over credential_name: when both are sent, they must refer to the same credential, otherwise the request is refused with HTTP 400. |
credential_name | Name of an API key credential to send as Authorization: Bearer <key>. Without credential_id and credential_name, a credential of the legacy type http is used if the workspace has one. |
Result:
{
"status": 200,
"ok": true,
"headers": { "content-type": "application/json" },
"body": { "items": [] },
"duration_ms": 182
}headersare redacted.bodyis parsed JSON when the response is JSON, otherwise text. Bodies above 1 MB are cut off.duration_msis the time the request took, in milliseconds.- Credentials are sent only over HTTPS.
- Redirects are followed up to 5 times as
GETwithout the original headers and body. Every hop is checked against the policy again. A hop the policy blocks fails the action, and so does a hop that would need an approval the original request did not get: another origin, a higher risk or other approvers.
Credential rules for HTTP:
- Only
api_keycredentials can be sent. Selecting another type, by ID or by name, blocks the request. - A credential with allowed hosts is sent only to those hosts. Any other host blocks the request, whatever the policy says.
- A credential without allowed hosts needs a person's approval for every request that sends it: an
ALLOWbecomesREQUIRE_APPROVAL. - The same checks apply whether the credential is selected by
credential_idor bycredential_name: it must belong to the workspace, be assigned to this agent or to no agent, and be anapi_key. - A credential that does not exist returns HTTP 404; one assigned only to other agents returns HTTP 403. A
credential_idthat is not a UUID returns HTTP 400credential_id must be a UUID.
Browser
A browser session is a real browser on AgentLock's servers. The agent receives accessibility snapshots, never the cookies or passwords.
| Tool | Payload | Notes |
|---|---|---|
browser.open | url, optional allowed_domains (array of hostnames) | Always needs approval. The result carries the session_id. The session may navigate to the opened URL's host and the listed domains. |
browser.navigate | session_id, url | |
browser.click | session_id, selector | A Playwright selector such as #submit, text=Sign in or role=button[name="Save"], at most 500 characters. ref is accepted as an alias of selector. |
browser.type | session_id, selector, text | |
browser.select | session_id, selector, value | |
browser.press_key | session_id, key | Enter, Tab, Escape, Backspace, Delete, Space, arrow keys, Home, End, PageUp, PageDown, Insert, modifier keys and F1 to F12. |
browser.scroll | session_id, optional direction (up, down), optional amount (pixels, 1 to 10000, default 500) | |
browser.snapshot | session_id | |
browser.screenshot | session_id, optional full_page | The result adds screenshot, a base64 PNG. |
browser.fill_credentials | session_id, credential_name, field_mapping | Fills a login credential. field_mapping maps CSS selectors to username, password or totp. The snapshot is suppressed in the result. |
browser.close | session_id |
Result of every browser tool: session_id, snapshot (the page's accessibility tree in Playwright's ARIA snapshot format), page_url, page_title, action_performed and, for screenshots, screenshot.
- Sessions expire 30 minutes after they are opened.
- Actions inside a session run only when the policy allows them. An action the policy would send for approval is refused with HTTP 403 (
status: "DENIED", the reason inerror), because an approval cannot pause a running session. Under the built-in default policy onlybrowser.snapshot,browser.screenshot,browser.scrollandbrowser.closeare allowed; addALLOWrules for the tools the agent should use inside approved sessions. - Concurrent sessions per workspace: Free 0, Pro 2, Team 5.
SSH
| Tool | Payload | Notes |
|---|---|---|
ssh.open | credential_id, optional ttl_ms | Opens a persistent session. Always needs approval. Host, user and port come from the ssh credential. ttl_ms is capped at the plan maximum (20 minutes on Pro, 60 minutes on Team; Free has no persistent sessions), which is also the default. |
ssh.run | session_id, command | Runs a command in an open session. |
ssh.run | credential_id, host, user, command, optional port | One-shot: connects, runs one command and disconnects. host, user and port must match the credential. Available on every plan. |
ssh.close | session_id | Closes a session. Allowed by default. |
Results:
ssh.open:session_id,host,user,port,via_vpn,expires_at.ssh.run:stdout,stderr,exit_code,signal,truncated,duration_ms,host,user,port,via_vpnand, in a session,session_id.stdoutandstderrare capped at 64 KB each;truncatedis thentrue.ssh.close:closed,session_id.
SSH actions are classed admin (ssh.close as write). Without an ssh section in the policy, every ssh.open and ssh.run needs approval. With one, the host and user must be on its allowlists and the first matching command rule decides ssh.run. An ALLOW command rule still needs approval unless allowHighRiskAutoApproval.admin is set, and a command with shell control characters (;, |, &, $, backticks, redirects, line breaks) matched by a glob pattern always needs approval. Concurrent sessions per workspace: Free 0, Pro 2, Team 5.
MCP servers
| Tool | Payload | Result |
|---|---|---|
mcp.list_tools | server: name of an mcp credential | server, tools (each with name, description, input_schema) |
mcp.call_tool | server, method (the remote tool name), arguments (object, at most 1 MB) | server, method, content (MCP content items), text (all text items joined), is_error |
mcp.list_tools is allowed by the default policy; mcp.call_tool needs approval.
Coding agent permissions
Tool permission.claude_code. Created by permission routing for tool calls that need an approver. Send the action from a forward decision unchanged.
Policies
Each agent is evaluated against its assigned policy, otherwise the workspace's default policy, otherwise the built-in default. Policies are edited in the dashboard. A policy has these fields:
| Field | Description |
|---|---|
defaultMode | allow, require_approval or block. Applies when no rule matches. |
rules | Up to 100 rules. Each names a tool, an action_type or both, optionally a domain, and a decision (ALLOW, REQUIRE_APPROVAL, BLOCK). Optional require_two_approvals and allowed_approvers (member UUIDs). |
http | allowedDomains, allowedMethods, blockList and optional allowAllDomains. |
ssh | allowedHosts, allowedUsers, commandRules (glob or regex pattern with a decision) and defaultDecision. |
claudeBash | rules (command pattern with a decision) and optional defaultDecision, for permission routing. |
limits | maxCostPerAction (compared with cost_estimate) and maxActionsPerHour (per agent). |
allowHighRiskAutoApproval | financial and admin flags. Without them an ALLOW for those classes still needs approval. |
vpnRoutes | Routes traffic for matching domains through a WireGuard credential. |
Evaluation:
- The effective action type is the higher of the declared
action_typeand the class the server derives from the tool and payload. For HTTP,GETisreadand other methodswrite; URLs that look like payment or administration endpoints are raised further. Unknown tools arewrite. - A rule matches when every selector it names matches:
tool(thehttptool is matched ashttp.request),action_typeagainst the effective type, anddomainagainst the host of an HTTP request (subdomains included;*.example.commatches subdomains only). Rules that name a tool are checked first, then the others; the first match wins. - HTTP requests to a domain on
blockList, to a domain outside a non-emptyallowedDomains, with a method outsideallowedMethodsor without a valid URL are blocked. So is every method other thanGET,POST,PUT,PATCHandDELETE: a policy saved earlier may still listHEADorOPTIONSinallowedMethodsand stays valid, but those methods are never run. With an emptyallowedDomainsevery HTTP request needs approval unlessallowAllDomainsis set. - An action whose
cost_estimateexceedsmaxCostPerActionis blocked. - An
ALLOWbecomesREQUIRE_APPROVALforfinancialandadminactions unlessallowHighRiskAutoApprovalopts in, and for awriteaction that was declared asread. browser.openandssh.openalways need approval unless a rule blocks them.- Safe mode blocks every action of the workspace.
The built-in default policy allows read, sends write and financial for approval and blocks admin. It allows mcp.list_tools, ssh.close and the read-only browser tools, sends http.request, mcp.call_tool, ssh.open, ssh.run, permission.claude_code and the other browser tools for approval, allows the HTTP methods GET, POST, PUT, PATCH and DELETE, and limits each agent to 100 actions per hour.
The agent itself can be restricted further in the dashboard with a tool allowlist. More detail: Policies.
Credentials
Credentials are stored encrypted in the workspace vault and created in the dashboard. Agents reference them by name (credential_name) or, for HTTP and SSH, by ID (credential_id); the SSH tools take only the ID. No API returns a secret or any part of it; GET /api/gateway/credentials lists the names and types.
| Type | Used by | Notes |
|---|---|---|
api_key | http | Sent as Authorization: Bearer <key>. Can be bound to up to 20 allowed hosts: hostnames, *.example.com wildcards for subdomains, or IPv4 addresses. |
login | browser.fill_credentials | Username, password and an optional TOTP secret. |
mcp | mcp.list_tools, mcp.call_tool | Server URL and optional key, sent only to that server. |
ssh | ssh.* | Host, port, user, private key or password, optional host key fingerprint. |
wireguard | VPN routing | Routes other credentials' traffic through a WireGuard tunnel. |
A credential can be assigned to specific agents. A credential without assignments can be used by every agent of the workspace. More detail: Credentials.
Statuses
Statuses returned by POST /api/gateway/request:
| Status | Meaning |
|---|---|
ALLOWED | Accepted without approval. Poll the result. |
PENDING | Waiting for approval. Poll the result. |
BLOCKED | Refused by policy, tool allowlist, kill switch or safe mode. Final. |
DENIED | An in-session browser action the policy would send for approval. Final. |
Statuses returned by GET /api/gateway/result/{requestId}:
| Status | Final | Meaning |
|---|---|---|
PENDING | No | Waiting for approval. |
NEEDS_SECOND_APPROVAL | No | One of two required approvals is given. |
QUEUED | No | Allowed or approved, waiting to run. |
RUNNING | No | Running. |
SUCCEEDED | Yes | Finished. result holds the output. |
FAILED | Yes | Failed. error holds the reason. |
DENIED | Yes | An approver denied the request. The reason, if given, arrives as a message. |
EXPIRED | Yes | Nobody decided before expires_at. |
UNDOING | No | Succeeded and is being reversed from the timeline. |
UNDONE | Yes | Succeeded and was later reversed from the timeline. |
BLOCKED is never returned by this endpoint; blocked requests are not stored. For FAILED, error says why. When no cause was recorded, it is Action execution could not be completed. Check the timeline before retrying.
Webhooks
A request with webhook_url triggers a POST to that URL when it ends:
| Event | Body |
|---|---|
| Succeeded | { "request_id", "status": "SUCCEEDED", "result", "timestamp" } |
| Failed | { "request_id", "status": "FAILED", "error", "timestamp" } |
| Denied by an approver | { "request_id", "status": "DENIED", "timestamp" } |
| Approval expired | { "request_id", "status": "EXPIRED", "timestamp" } |
- Blocked requests send no webhook; the response to
POST /api/gateway/requestis already final. - AgentLock marks due approvals as expired every 5 minutes, so the
EXPIREDwebhook can arrive up to 5 minutes afterexpires_at. resultis redacted like the result endpoint's.errorhas paths, URLs and secrets removed.- Headers:
Content-Type: application/json,User-Agent: AgentLock-Webhook/1.0,X-AgentLock-Timestamp(ISO 8601) andX-AgentLock-Signature(sha256=<hex HMAC>over<timestamp>.<body>). - Delivery is attempted once with a 5-second timeout and no retries. Redirects are followed up to 5 times, HTTPS only.
Verifying a webhook
Every delivery is signed with the webhook signing secret of the agent's workspace. Each workspace has its own secret. It starts with whsec_ and is created the first time it is needed.
- In the dashboard, open Settings and go to Webhook Signing Secret. Owners and admins can reveal, copy and rotate the secret there; other roles do not see it.
- Store the secret with the receiver, for example in an environment variable.
- For each delivery, compute HMAC-SHA256 over the value of
X-AgentLock-Timestamp, a period and the raw request body exactly as received. The key is the whole secret,whsec_included. Comparesha256=followed by the hex digest withX-AgentLock-Signaturein constant time. - Reject a delivery whose timestamp is more than 5 minutes old, so that a recorded delivery cannot be replayed.
Rotating replaces the secret at once: every later delivery is signed with the new secret, and the old one no longer matches. Update the receiver right after rotating.
Node.js with Express:
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';
const app = express();
app.post('/agentlock-webhook', express.raw({ type: 'application/json' }), (req, res) => {
const timestamp = req.get('X-AgentLock-Timestamp') ?? '';
const signature = Buffer.from(req.get('X-AgentLock-Signature') ?? '');
const expected = Buffer.from('sha256=' + createHmac('sha256', process.env.AGENTLOCK_WEBHOOK_SECRET)
.update(`${timestamp}.`)
.update(req.body)
.digest('hex'));
const fresh = Math.abs(Date.now() - Date.parse(timestamp)) < 5 * 60 * 1000;
if (!fresh || signature.length !== expected.length || !timingSafeEqual(signature, expected)) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body.toString('utf8'));
console.log(event.request_id, event.status);
res.sendStatus(204);
});Python:
import hashlib
import hmac
import os
from datetime import datetime, timezone
def is_valid_agentlock_webhook(headers, raw_body: bytes) -> bool:
timestamp = headers.get("X-AgentLock-Timestamp", "")
signature = headers.get("X-AgentLock-Signature", "")
key = os.environ["AGENTLOCK_WEBHOOK_SECRET"].encode()
digest = hmac.new(key, timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
try:
sent = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
except ValueError:
return False
fresh = abs((datetime.now(timezone.utc) - sent).total_seconds()) < 300
return fresh and hmac.compare_digest(signature, "sha256=" + digest)Errors
Errors are JSON objects with an error message:
{ "error": "Rate limit exceeded", "retry_after": 60 }| Status | Meaning |
|---|---|
| 400 | Invalid body, parameter or header. POST /api/gateway/messages adds details with the failing fields. |
| 401 | Missing or invalid authentication. |
| 403 | Authenticated but not permitted: inactive agent, tool not on the allowlist, credential assigned to other agents, plan without the feature, or an in-session browser action the policy does not allow. |
| 404 | Not found, or owned by another agent. |
| 409 | Replayed nonce. Sign again with a new nonce. |
| 410 | The browser or SSH session is closed or expired. |
| 423 | The workspace kill switch is engaged. |
| 429 | A rate limit or quota is reached. |
| 500 | Unexpected error. |
| 503 | Temporary failure. Retry with new signing headers. |
Rate limits and quotas
Rate limits per minute:
| Scope | Limit |
|---|---|
Source IP, POST /api/gateway/request | 60 |
Agent, POST /api/gateway/request | 60 |
Workspace, POST /api/gateway/request | Free 120, Pro 600, Team 2,400 |
Agent, GET /api/gateway/result/{requestId} | 60 |
Agent, GET /api/gateway/credentials | 60 |
Agent, /api/gateway/messages (both methods) | 60 |
Agent, GET /api/gateway/ssh-sessions | 60 |
Agent, POST /api/gateway/permission-routing | 120 |
Agent, POST /api/mcp | 60 |
A rate-limited request returns HTTP 429 with a Retry-After header:
{ "error": "Rate limit exceeded", "retry_after": 60 }The policy's limits.maxActionsPerHour caps actions per agent per hour and returns:
{ "error": "Hourly action limit exceeded", "limit": 100, "retry_after": 3600 }Plan quotas:
| Quota | Free | Pro | Team |
|---|---|---|---|
| Actions per month | 100 | 2,000 | 10,000 |
| Concurrent browser sessions | 0 | 2 | 5 |
| Concurrent SSH sessions | 0 | 2 | 5 |
| SSH session lifetime | 20 min | 20 min | 60 min |
| Messages per month | 100 | 5,000 | Unlimited |
| Threads per agent | 5 | 50 | Unlimited |
An exhausted action quota returns HTTP 429 Action limit reached; an exhausted message quota returns HTTP 403.
Data redaction
AgentLock redacts secrets before it stores or returns data:
- The request payload is redacted before it is stored. Actions that run after approval or from the queue run with the stored, redacted payload. Browser actions inside an open session run with the payload as sent.
- Results, HTTP response headers and webhook bodies are redacted before they are stored or sent.
Redaction replaces a value with [REDACTED] when:
- its field name is a secret name such as
authorization,api_key,token,secret,password,private_key,access_token,refresh_token,client_secret,cookieorset-cookie, or contains a fragment such assecret,password,token,credential,jwtoroauth. Field names that end in_idor_name, such ascredential_idandcredential_name, are kept; - the whole value looks like a secret: provider API keys (for example Stripe, GitHub, AWS, Slack, Google, OpenAI, Anthropic), JWTs, bearer tokens, PEM private keys, SSH and WireGuard keys, and strings of 43 or more base64 characters.
Inside longer text, provider keys, JWTs, assignments such as PASSWORD=... or api_key: ... and URL query parameters such as token, api_key, secret, sig or key have their value replaced.
A secret placed in a payload therefore reaches the target as [REDACTED]. Keep secrets in the vault and reference them by credential name.