Python SDK
Install and use the agentlock-sdk Python package to send signed AgentLock requests from Python agents.
Python SDK for AgentLock. It signs every request with the agent's Ed25519 key, submits actions to the AgentLock gateway, waits for approvals and returns the results. The agent never receives the credentials AgentLock uses on its behalf.
Full API reference: https://app.agentlock.net/docs/api
Installation
pip install "agentlock-sdk[nacl]"Requires Python 3.9 or later. Signing needs one Ed25519 backend:
| Extra | Backend |
|---|---|
nacl | PyNaCl |
cryptography | cryptography |
all | Both |
Without either backend, generate_keypair() and every signed request raise ImportError.
Setup
Create a key pair once, register the public key when you create the agent in the AgentLock dashboard, and keep the private key in the agent's environment:
from agentlock import generate_keypair
keypair = generate_keypair()
print(keypair.public_key) # register in the dashboard
print(keypair.private_key) # store as a secretBoth keys are base64 encoded. The dashboard shows the agent ID after registration.
import os
from agentlock import AgentLockClient
client = AgentLockClient(
base_url="https://app.agentlock.net",
agent_id=os.environ["AGENT_ID"],
private_key=os.environ["AGENT_PRIVATE_KEY"],
)| Argument | Default | Description |
|---|---|---|
base_url | https://app.agentlock.net. Must be HTTPS; http://localhost is accepted for local development. | |
agent_id | The agent's UUID. | |
private_key | The agent's base64 Ed25519 private key. | |
timeout | 30.0 | Timeout of each HTTP call in seconds. |
The client holds an HTTP connection pool. Use it as a context manager (with AgentLockClient(...) as client:) or call client.close() when done. create_client(...) takes the same arguments.
Submitting actions
submitted = client.request_action(
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",
)
if submitted.status == "BLOCKED":
raise RuntimeError(f"Blocked: {submitted.message}")
final = client.await_result(submitted.request_id)
if final.status != "SUCCEEDED":
raise RuntimeError(f"Action ended with {final.status}: {final.error}")
print(final.result)request_action(action_type, tool, payload, cost_estimate=None, idempotency_key=None)returns aGatewayResultwithrequest_id,decision,status,messageandexpires_at.statusisALLOWED,PENDINGorBLOCKED. An error status from the gateway raiseshttpx.HTTPStatusErrorwith the gateway's reason in the message.await_result(request_id, poll_interval=2.0, timeout=300.0)polls until the status isSUCCEEDED,FAILED,DENIED,EXPIRED,BLOCKEDorUNDONEand returns anExecutionResultwithstatus,resultanderror. It raisesTimeoutErroraftertimeoutseconds.- Call
await_resultforALLOWEDas well asPENDING: an allowed action runs asynchronously, and its output is only available from the result endpoint.
Tools, payloads and policy behavior are described in the API reference.
Wrapping a function
tool_wrapper(fn, *, action_type, tool, cost_estimate=None, idempotency_key=None) returns a function that takes a payload, submits it, waits for the result and calls fn with the result. Every call is submitted with its own idempotency key. Pass idempotency_key, a function of the payload, to derive the key instead: calls that return the same key share one action, because the gateway answers a repeated key with the first request. A key has at most 128 characters. Only a SUCCEEDED action reaches fn. A denial raises ApprovalDeniedError, an expiry ApprovalTimeoutError, and a blocked, failed or undone action AgentLockError.
create_order = client.tool_wrapper(
lambda result: result.get("body"),
action_type="write",
tool="http",
)
order = create_order({
"method": "POST",
"url": "https://api.example.com/orders",
"body": {"item": "widget"},
"credential_name": "example-api",
})HTTP requests
res = client.http_request(method="GET", url="https://api.example.com/items")
# {"status": 200, "headers": {...}, "body": {...}, "duration_ms": 182}http_request(*, method, url, headers=None, body=None, credential_id=None, approval_timeout=300.0) declares read for GET, HEAD and OPTIONS and write otherwise. It raises ApprovalDeniedError, ApprovalTimeoutError or RuntimeError when the action does not succeed. duration_ms is 0 when the execution did not report it. The gateway executes GET, POST, PUT, PATCH and DELETE.
The credential_id argument has no effect: the gateway selects HTTP credentials by name. To send a vault credential, use request_action with payload["credential_name"] as shown above.
Browser sessions
A browser session runs on AgentLock's servers. Opening one always needs approval; actions inside an open session run immediately when the policy allows them.
session = client.browser_open(
"https://shop.example.com/login",
allowed_domains=["accounts.example.com"],
)
client.browser_fill_credentials(
session.session_id,
"shop-login",
{"#email": "username", "#password": "password"},
)
client.browser_action(session.session_id, "click", {"selector": "text=Sign in"})
snap = client.browser_snapshot(session.session_id)
# {"html": ..., "url": ..., "title": ..., "screenshot": ... (optional)}
client.browser_close(session.session_id)| Method | Description |
|---|---|
browser_open(url, *, allowed_domains=None) | Requests browser.open, waits for approval and returns a BrowserActionResult. |
browser_action(session_id, tool, params=None) | Runs browser.<tool> in the session, for example click, type, navigate, select, press_key, scroll, snapshot or screenshot. Returns a BrowserActionResult with session_id, snapshot, page_url, page_title, action_performed and screenshot. |
browser_fill_credentials(session_id, credential_name, field_mapping) | Fills a login credential. field_mapping maps CSS selectors to username, password or totp. |
browser_snapshot(session_id) | Returns a dict with html (the accessibility snapshot), url, title and optionally screenshot. |
browser_close(session_id) | Closes the session. |
selector takes a Playwright selector. Under the default policy only snapshot, screenshot, scroll and close are allowed inside a session; an action the policy would send for approval is refused. Add ALLOW rules for the browser tools the agent should use. Browser methods raise RuntimeError when an action is blocked, refused or fails.
SSH sessions
with client.ssh.open(credential_id="<ssh credential UUID>") as session:
r = session.run("uname -a")
print(r.exit_code, r.stdout)
# closed on exitclient.ssh.open(*, credential_id, ttl_ms=None, approval_timeout=300.0)requestsssh.open, waits for approval and returns anSshSession. Host, user and port always come from the credential.ttl_msis capped at the plan maximum (20 minutes on Pro, 60 minutes on Team; Free has no persistent sessions), which is also the default.session.run(command)returns anSshRunResultwithstdout,stderr,exit_code,signal,truncatedandduration_ms. Every command is checked against the policy and waits for approval when the policy requires it; a denial raisesApprovalDeniedError. It raisesSshSessionClosedErrorafterclose()andSshSessionExpiredErroronce the session has expired.session.close()is idempotent. A session is also a context manager.session.is_expired()checks the expiry locally.client.ssh.list()returns the agent's open sessions, including those opened by another process.client.ssh.adopt(session_id)returns a handle for a known session ID without a network call.
sessions = client.ssh.list()
build = next((s for s in sessions if s.host == "build-01.example.com"), None)
if build:
print(build.run("tail -n 50 /var/log/nginx/access.log").stdout)client.ssh_run(credential_id, host, user, command, *, port=None, poll_interval=2.0, timeout=300.0) runs a single command without a persistent session and returns the result as a dict. It is available on every plan. host, user and port must match the credential.
Messages
for m in client.get_messages():
client.send_message(m.thread_id, f"Received: {m.content}")
client.create_thread("Deploy finished.", subject="Deploy")
stop = client.on_message(lambda m: print(m.content), poll_interval=5.0)
# later: stop()get_messages(*, since=None, limit=20, include_read=False, thread_id=None)returns a list ofAgentMessage(id,thread_id,sender_type,sender_id,content,metadata,read_at,created_at). By default it returns unread messages from people and marks them as read.send_message(thread_id, content, metadata=None)replies in a thread and returns theAgentMessage.create_thread(content, *, subject=None, metadata=None)starts a thread and returns aNewThreadResultwiththread_id,subjectandmessage.on_message(callback, *, poll_interval=5.0, max_backoff=60.0, on_error=None)polls in a background thread and returns a function that stops it.
MCP servers
listing = client.mcp_list_tools("github-mcp")
print([t.name for t in listing.tools])
res = client.mcp_call_tool("github-mcp", "create_issue", {"title": "Bug"})
print(res.is_error, res.text)mcp_list_tools(server)returns anMcpListToolsResultwithserverandtools(McpToolInfo:name,description,input_schema).serveris the name of anmcpcredential.mcp_call_tool(server, method, args=None, action_type="write")returns anMcpCallToolResultwithserver,method,content(McpContentItem:type,text,data,mime_type),textandis_error.
Both methods raise RuntimeError when the action does not succeed.
Errors
| Class | Raised when |
|---|---|
AgentLockError | Base class of the errors below; also raised when listing SSH sessions fails or a wrapped action is blocked, fails or is undone. |
ApprovalDeniedError | An approver denied the request (request_id, denial_reason). |
ApprovalTimeoutError | The approval expired (request_id, waited_ms: how long the client waited). |
SshSessionExpiredError | run on an expired session. |
SshSessionClosedError | run on a closed session. |
Retries
Every call, including each poll of await_result, retries HTTP 429, 502, 503 and 504 up to three times, with these exceptions. An action sent by request_action or a method built on it without idempotency_key gets a random one that stays the same for every attempt, and the gateway answers a repeated key with the first request (idempotent: true), so a retry cannot create a second action. browser_action and other browser tools inside a session, send_message and create_thread cannot be deduplicated and retry only HTTP 429, which the gateway sends before it processes a request. Each retry is signed anew with a fresh nonce.
License
MIT