SDKs & Integration
Integrate AI agents with AgentLock: the Node.js SDK, the Python SDK, the MCP server, bearer tokens, the gateway request format and webhooks.
SDK overview — three ways to integrate
AgentLock provides three official integration methods:
1. Node.js SDK (agentlock-sdk-node)
TypeScript/JavaScript client for Node.js agents. Handles Ed25519 request signing, result polling, browser sessions, messaging, and MCP calls.
2. Python SDK (agentlock-sdk)
Python client for agents built with LangChain, CrewAI, AutoGen, etc.
3. MCP Server (agentlock-mcp-server)
Model Context Protocol server that exposes AgentLock as MCP tools. Any MCP-compatible client (Claude Code, Cursor, Windsurf) can use AgentLock without code. Handles all auth and signing internally.
All three connect to the same gateway API. The agent never receives raw secrets.
Gateway request format — headers, body, response shapes
If you're implementing your own client (not using the official SDKs), this is the wire format for POST /api/gateway/request. The SDKs do all of this for you. The API reference in the documentation lists every endpoint, error and limit and has a complete signing example.
Request body (application/json):
{
action_type: 'read' | 'write' | 'financial' | 'admin';
tool: string; // e.g. "http", "browser.open", "mcp.call_tool"
payload: Record<string, unknown>; // tool-specific, max 64 KB serialized
idempotency_key?: string; // max 128 chars, optional
cost_estimate?: number; // non-negative, optional
webhook_url?: string; // HTTPS URL for terminal-state callback, optional
}Credential selection lives inside payload, not at the top level — unknown top-level fields are stripped by the schema. HTTP requests select an API key with credential_name or credential_id. When both are sent, the ID decides and both must refer to the same credential, otherwise the request is refused with HTTP 400. The SSH tools take credential_id.
Authentication — option 1: Ed25519 headers (recommended)
x-agent-id— UUID of the agent (from the dashboard)x-timestamp— Unix milliseconds (Date.now()). Rejected if more than 5 minutes off server time.x-nonce— Base64-encoded 16 random bytes. Unique per request; a nonce repeated within 10 minutes is refused.x-signature-version—2x-signature— Base64-encoded Ed25519 signature over the signature input.
Signature input (version 2): six lines joined with a line feed and encoded as UTF-8:
2
<METHOD>
<path without query string>
<x-timestamp>
<x-nonce>
<canonical JSON of the signed body>Canonical JSON sorts object keys at every level and has no whitespace, so two logically identical bodies always produce the same signature. Because the method and path are signed, a signature made for one endpoint is not valid on another. Signature version 1 and requests without a version header are still accepted, but they do not bind the method and path; use version 2. The agentlock-shared package on npm, which the Node.js SDK uses, exports signRequest and canonicalStringify.
Authentication — option 2: Bearer token
Authorization: Bearer <token>— replaces all signing headers.- Bearer tokens still pass through the full policy engine, rate limits, plan checks, and audit log.
- Simpler to integrate, but without per-request replay protection. Recommended for MCP clients, hooks and curl scripts, not for high-trust production agents.
Response shapes:
- Auto-allowed:
200 { request_id, decision: "ALLOW", status: "ALLOWED" }— the action runs asynchronously; poll for its output - Needs approval:
202 { request_id, decision: "REQUIRE_APPROVAL", status: "PENDING", expires_at } - Blocked by policy or Safe Mode:
200 { request_id, decision: "BLOCK", status: "BLOCKED", message }— final, not stored, cannot be polled - Rate limited:
429 { error, retry_after }plusRetry-Afterheader - Bad request:
400 { error } - Auth failure:
401 { error } - Replay:
409 { error: "Replay detected" }
Polling for results: GET /api/gateway/result/{request_id} (signed the same way; the signed body is {"requestId":"<id>"}) returns the current status. Poll ALLOWED and PENDING requests alike. Final statuses are SUCCEEDED, FAILED, DENIED, EXPIRED and UNDONE.
Node.js SDK setup
Installation:
npm install agentlock-sdk-nodeCreate a client:
import { createClient, generateKeypair } from 'agentlock-sdk-node';
// Generate a keypair (do this once)
const { publicKey, privateKey } = generateKeypair();
// Register publicKey in the dashboard, keep privateKey secret
const client = createClient({
baseUrl: 'https://app.agentlock.net',
agentId: 'your-agent-uuid',
privateKey: privateKey,
timeout: 30000, // optional, default 30s
});Configuration options:
baseUrl(required) — Must use HTTPS (orhttp://localhostfor dev). Throws if non-HTTPS.agentId(required) — UUID from the dashboard.privateKey(required) — Base64-encoded Ed25519 private key.timeout(optional) — Request timeout in ms. Default: 30000.
Security: The SDK prevents serialization of the private key. JSON.stringify(client) only returns { baseUrl, agentId }. Auto-retries on 429/502/503/504 with exponential backoff. From version 0.6.0 every retry is signed anew, and requestAction sends an idempotency_key (yours, or a random one that stays the same for every attempt of the call), so a retry after a 5xx cannot create a second action. Message posts and browser actions inside a session are retried only after 429. Older versions resend the same signed request and get HTTP 409 "Replay detected"; call the method again.
Node.js SDK — requestAction and awaitResult
requestAction sends an action through the gateway:
const res = await client.requestAction({
action_type: 'write',
tool: 'http',
payload: {
method: 'POST',
url: 'https://api.example.com/data',
body: { key: 'value' },
credential_name: 'my-api-key',
},
idempotency_key: 'unique-op-123', // optional
});
// res = { request_id, decision, status, message?, expires_at? }
// status is ALLOWED, PENDING or BLOCKEDawaitResult polls until the action completes. Call it for ALLOWED as well as PENDING: an allowed action runs asynchronously, and its output only comes from the result endpoint. BLOCKED is final and cannot be polled:
const outcome = await client.awaitResult(res.request_id, {
pollIntervalMs: 2000, // default 2s
timeoutMs: 300000, // default 5min
});
switch (outcome.status) {
case 'SUCCEEDED': console.log(outcome.result); break;
case 'FAILED': console.log(outcome.error); break;
case 'DENIED':
const { messages } = await client.getMessages();
break; // check for denial reason
case 'EXPIRED': break; // approval timed out
}Final statuses: SUCCEEDED, FAILED, DENIED, EXPIRED and UNDONE. If none is reached before timeoutMs (default 5 minutes), awaitResult throws.
Node.js SDK — Browser methods
Open a session (requires approval):
const session = await client.browserOpen(
'https://dashboard.example.com',
{ allowedDomains: ['dashboard.example.com', 'auth.example.com'] }
);
// session = { session_id, snapshot, page_url, page_title }Perform actions (each runs immediately when the policy allows it; an action the policy would send for approval is refused and browserAction throws. The default policy allows only snapshot, screenshot, scroll and close, so add Allow rules for the tools the agent uses. selector takes a Playwright selector):
await client.browserAction(session.session_id, 'click', { selector: 'button[name="Submit"]' });
await client.browserAction(session.session_id, 'type', { selector: '#search', text: 'query' });
await client.browserAction(session.session_id, 'navigate', { url: 'https://dashboard.example.com/settings' });
await client.browserAction(session.session_id, 'press_key', { key: 'Enter' });
const snap = await client.browserAction(session.session_id, 'snapshot');Fill login credentials (agent never sees password):
await client.browserFillCredentials(session.session_id, 'my-login', {
'#email': 'username',
'#password': 'password',
'#totp-code': 'totp', // auto-generated TOTP if secret stored
});Snapshot shortcut (convenience wrapper over browserAction(_, 'snapshot')):
const snap = await client.browserSnapshot(session.session_id);
// { html, url, title, screenshot? }Close: await client.browserClose(session.session_id);
Node.js SDK — SSH methods
Two modes: one-shot sshRun and a session-handle pattern via client.ssh. SSH commands are admin-class actions: each one needs approval unless an SSH command rule in the policy allows it and admin auto-approval is switched on in the policy's Danger Zone.
One-shot (available on every plan; host, user and port must match the credential):
const result = await client.sshRun({
credentialId: 'cred-uuid',
host: 'build-01.example.com',
user: 'deploy',
command: 'systemctl status nginx',
});
// { stdout, stderr, exit_code, signal, truncated, duration_ms, host, user, port, via_vpn }Persistent session (Pro/Team — open once, run many, close; opening always needs approval, and every session.run is checked against the policy and waits for approval when it requires one):
import { SshSessionExpiredError } from 'agentlock-sdk-node';
const session = await client.ssh.open({ credentialId: 'cred-uuid' });
// session = SshSession with .id, .host, .user, .port, .viaVpn, .expiresAt, .lastActivityAt?, .actionCount?
try {
await session.run('uname -a');
await session.run('uptime');
await session.run('systemctl status nginx');
} finally {
await session.close(); // idempotent — safe to call from finally
}Local expiry check (avoids a network round-trip when you know the session is dead):
if (session.isExpired()) { /* re-open */ }
// session.run() throws SshSessionExpiredError without hitting the network if expiresAt is in the pastDiscovery and re-attach across processes:
const sessions = await client.ssh.list(); // hits /api/gateway/ssh-sessions
const ops = sessions.find(s => s.host === 'build-01.example.com');
if (ops) await ops.run('tail -n 50 /var/log/nginx/access.log');
const known = client.ssh.adopt('ss_xx'); // lazy; no network callError classes thrown by the handle: SshSessionExpiredError, SshSessionClosedError, ApprovalDeniedError, ApprovalTimeoutError — all extend AgentLockError. Use instanceof to branch.
Node.js SDK — HTTP convenience wrapper
client.httpRequest() wraps requestAction({tool: 'http', ...}) + awaitResult so you can issue one-call HTTP requests through the policy + redaction + SSRF layer:
const res = await client.httpRequest({
method: 'POST',
url: 'https://api.example.com/items',
headers: { 'X-Custom': 'value' },
body: { name: 'x' },
});
// { status, headers, body, durationMs }Methods: the gateway executes GET (classified as read) and POST, PUT, PATCH and DELETE (classified as write). The policy's allowed methods decide which of them the agent may use; every other method is blocked. durationMs is the time the request took.
Credentials: credentialId selects a vault API key by ID and sends it as Authorization: Bearer <key>. The gateway checks it exactly like a key selected by name: it must belong to the workspace, be assigned to this agent or to no agent, and be an API key. To select a key by name, call requestAction with tool: 'http' and payload.credential_name, then awaitResult.
Behavior with approval: if the policy decides REQUIRE_APPROVAL, the call blocks until approved + executed (or throws ApprovalDeniedError / ApprovalTimeoutError). For long-running approvals pass approvalTimeoutMs to widen the wait.
Node.js SDK — Messaging
Poll for messages:
const { messages } = await client.getMessages();
for (const msg of messages) {
console.log(msg.thread_id, msg.content, msg.created_at);
}Options: since (ISO datetime), limit (max 50), includeRead (boolean), threadId (UUID).
Reply in a thread:
await client.sendMessage(msg.thread_id, 'Task completed. Report at /reports/latest.');Listen continuously:
const unsub = client.onMessage((msg) => {
console.log('New:', msg.content);
client.sendMessage(msg.thread_id, 'Acknowledged.');
}, { pollIntervalMs: 5000 });
// Later: unsub();Bearer token authentication
An alternative to Ed25519 signing. Simpler setup, recommended for MCP clients.
Create a token: Go to Agents → [agent] → Tokens → Create Token and pick a lifetime of 7, 30 or 90 days. The plaintext is shown once — only a SHA-256 hash is stored. An agent can have up to 10 active tokens.
Use with the MCP server (the token is read from the environment only; a --token flag is rejected):
export AGENTLOCK_TOKEN=YOUR_API_TOKEN
agentlock-mcpUse with HTTP calls:
curl -X POST https://app.agentlock.net/api/gateway/request \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"action_type":"read","tool":"http","payload":{"method":"GET","url":"https://api.example.com"}}'Bearer tokens skip Ed25519 signature verification and nonce/replay protection. All other gateway behavior (policy, rate limits, plan limits) is identical. Tokens can be revoked instantly from the dashboard.
MCP Server setup
The MCP server exposes 9 AgentLock tools to any MCP-compatible AI client.
No-install alternative: AgentLock also hosts a Streamable-HTTP MCP endpoint at https://app.agentlock.net/api/mcp (authenticate with Authorization: Bearer <token>). It exposes a reduced 2-tool surface — request_action and get_result — enough for basic tool-calling without installing anything. The agent's setup guide in the dashboard shows the exact client config under "Use the hosted MCP endpoint".
Install (full local server): npm install -g agentlock-mcp-server (installs the agentlock-mcp command)
The server reads its settings from environment variables only: AGENTLOCK_TOKEN for token auth (or AGENT_ID and AGENT_PRIVATE_KEY for signing) and optionally AGENTLOCK_URL. Flags that carry secrets, such as --token, are rejected.
Configure for Claude Code / Cursor / Windsurf:
{
"mcpServers": {
"agentlock": {
"command": "npx",
"args": ["-y", "agentlock-mcp-server"],
"env": { "AGENTLOCK_TOKEN": "YOUR_TOKEN" }
}
}
}Available tools:
request_action— Send any action through AgentLockget_result— Poll for request resultbrowser_open— Open a browser sessionbrowser_action— Perform browser actionsbrowser_login— Fill stored credentialslist_credentials— List available credentialsget_messages— Check for user messagessend_message— Reply in a threadstart_thread— Start a new conversation
The server includes built-in instructions that teach the AI client when to check messages and how to handle approvals.
Python SDK
Install: pip install "agentlock-sdk[nacl]" (the nacl extra provides Ed25519 signing)
from agentlock import AgentLockClient
client = AgentLockClient(
base_url="https://app.agentlock.net",
agent_id="your-agent-uuid",
private_key="base64-ed25519-private-key",
)Generic action + polling (low-level path, parity with the Node SDK):
result = client.request_action(
action_type="write", tool="http",
payload={"method": "POST", "url": "https://api.example.com/data", "body": {"k": "v"}, "credential_name": "example-api"},
)
if result.status != "BLOCKED": # poll ALLOWED and PENDING alike
outcome = client.await_result(result.request_id) # SUCCEEDED / FAILED / DENIED / EXPIRED / UNDONEConnector wrappers (high-level, mirror the Node SDK):
# HTTP — one call, returns {status, headers, body, duration_ms}
# credential_id selects a vault API key by ID; to select one by name, use request_action with payload["credential_name"]
res = client.http_request(
method="POST", url="https://api.example.com/x",
body={"a": 1},
)
# Browser — open always needs approval; actions in the session run only when the policy allows them
session = client.browser_open("https://dashboard.example.com")
client.browser_action(session.session_id, "click", {"selector": 'button[name="Submit"]'})
snap = client.browser_snapshot(session.session_id) # {html, url, title, screenshot?}
client.browser_close(session.session_id)
# SSH stateful — open returns a context-managed handle
with client.ssh.open(credential_id="cred-uuid") as session:
print(session.run("uname -a").stdout)
print(session.run("uptime").stdout)
# auto-closes on normal exit AND on exception
# SSH discovery / re-attach
for s in client.ssh.list():
print(s.id, s.host, s.last_activity_at)
adopted = client.ssh.adopt("ss_xx") # lazy stub
# MCP tools
tools = client.mcp_list_tools(server="github-mcp")
result = client.mcp_call_tool(server="github-mcp", method="search_code", args={"query": "agentlock"})Error classes (agentlock.errors): AgentLockError, ApprovalDeniedError, ApprovalTimeoutError, SshSessionExpiredError, SshSessionClosedError. All inherit from AgentLockError.
The Python SDK handles Ed25519 signing, nonce generation, and timestamp management like the Node.js SDK. It retries HTTP 429, 502, 503 and 504 up to three times. From version 0.5.0 every retry is signed anew, and request_action sends an idempotency_key that stays the same for every attempt, so a retry after a 5xx cannot create a second action. Message posts and browser actions inside a session are retried only after 429. Older versions resend the same signed request and get HTTP 409 "Replay detected"; call the method again.
Webhooks
Include a webhook_url in your action request. AgentLock POSTs a notification when the action succeeds, fails, is denied by an approver or expires without a decision. Blocked requests send no webhook; the gateway's answer is already final.
Payload:
{
"request_id": "uuid",
"status": "SUCCEEDED",
"result": { "status": 200, "body": { ... } },
"timestamp": "2026-04-08T12:00:00.000Z"
}A failed action carries error instead of result; a denied or expired one carries neither. AgentLock marks due approvals as expired every 5 minutes, so an EXPIRED webhook can arrive up to 5 minutes after the approval ran out.
Get the signing secret: every workspace has its own webhook signing secret, which starts with whsec_. Owners and admins find it under Settings > Webhook Signing Secret: Reveal secret shows it, Copy copies it and Rotate secret replaces it after a confirmation. Store it with your receiver, for example in an environment variable. After a rotation every delivery is signed with the new secret and the old one no longer matches, so update the receiver right away.
Verify a delivery: every delivery has the headers X-AgentLock-Timestamp and X-AgentLock-Signature. Compute HMAC-SHA256 over the timestamp header, a period and the raw request body exactly as received, with the whole secret, whsec_ included, as the key. The signature header must equal sha256= followed by the hex digest. Compare in constant time, reject timestamps older than 5 minutes, and parse the JSON only after the check:
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';
const app = express();
app.post('/agentlock-webhook', express.raw({ type: 'application/json' }), (req, res) => {
const timestamp = req.get('X-AgentLock-Timestamp') ?? '';
const received = 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 || received.length !== expected.length || !timingSafeEqual(received, expected)) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body.toString('utf8'));
console.log(event.request_id, event.status);
res.sendStatus(204);
});The API reference has the same check in Python.
Requirements:
- URL must use HTTPS
- SSRF protection blocks private IPs (127.x, 10.x, 192.168.x, etc.)
- 5-second timeout per delivery
- No retries — use polling (
awaitResult) as primary, webhooks as supplementary - Redirects followed (max 5 hops), each SSRF-validated