Python SDK
The agentshield_sdk client. Install it, sign requests, call tools, handle decisions and errors, execute approvals, and use the framework-neutral tools layer.
agentshield_sdk is the reference client. It signs the exact bytes it sends, executes only after an allow, and has no way to run a tool locally. Python 3.11 or newer; the only dependency is cryptography.
Install
python -m pip install ./sdk/python # from a clone of the repositoryCreate a client
from pathlib import Path
from agentshield_sdk import Client
client = Client(
gateway="http://127.0.0.1:8081",
agent_id="3f2b8c1e-6a4d-4f7e-9b21-5c8d0e7a4b13",
organization_id="9a7e5d2c-1b3f-4c6a-8e0d-2f4b6a8c0e1d",
seed=Path("/run/secrets/agentshield-seed").read_bytes(),
)Prop
Type
Call a tool
call_tool authorizes and, only when the outcome is allow, executes with the same arguments:
from agentshield_sdk import ApprovalRequired, Denied, GatewayError
try:
executed = client.call_tool(
tool_name="http.request",
operation="http.get",
resource="https://api.github.com/repos/octo/hello",
arguments={"query": {"per_page": "5"}, "headers": {"Accept": "application/json"}},
)
except Denied as exc:
print("denied:", exc.decision.explanation.get("reason"))
except ApprovalRequired as exc:
print("held:", exc.decision.approval_id, "until", exc.decision.approval_expires_at)
except GatewayError as exc:
print(exc.status, exc.code, exc.message) # e.g. 429 rate_limited
else:
print(executed.adapter, executed.result["status"])
if executed.flagged:
print(executed.warning())Authorize and execute separately
Use the two calls directly when you need the decision before acting, or when executing an approved request:
decision = client.authorize(
tool_name="sample.echo",
operation="sample.echo",
resource="demo",
arguments={},
)
if decision.outcome == "allow":
result = client.execute(decision.decision_id, decision.idempotency_key)
elif decision.outcome == "require_approval":
# After a person approves in the console:
result = client.execute(
decision.decision_id,
decision.idempotency_key,
approval_id=decision.approval_id,
)authorize accepts optional execution_id and idempotency_key keyword arguments. Pass both when you retry after a network failure so the gateway returns the stored decision.
For adapters that use arguments, such as http.request, pass the same arguments to execute that you authorized. The gateway compares their canonical hash and returns 409 conflict on a mismatch.
Return types
| Type | Fields |
|---|---|
Decision | decision_id, outcome, explanation, idempotency_key, approval_id, approval_expires_at; as_dict() |
ExecuteResult | decision_id, outcome ("allow"), adapter, result, analysis; flagged, warning(), as_dict() |
Errors
| Exception | Raised when |
|---|---|
Denied | call_tool received deny. .decision holds the recorded decision |
ApprovalRequired | call_tool received require_approval |
GatewayError | Any gateway error response, a non-JSON response, a decision with an unexpected status, or a redirect. Has status, code, message |
ValueError | The seed is not 32 bytes, or a nonce does not match the pattern |
None of these is an allow. A gateway decision is accepted only with HTTP 200 or 403.
Low-level signing
from agentshield_sdk import public_key, sign, signing_input
public_key(seed) # 43-char base64url, for registration
signing_input(timestamp, nonce, body) # "<ts>.<nonce>.<sha256 hex>"
sign(seed, timestamp, nonce, body) # unpadded base64url signatureSee Request signing.
Framework-neutral tools
agentshield_sdk.tools is the layer the LangChain and CrewAI integrations share. Use it directly to plug AgentShield into any framework that calls a Python function with keyword arguments:
from agentshield_sdk.tools import ToolSpec, invoke
spec = ToolSpec(
name="get_repo",
description="Read public metadata for the octo/hello repository.",
tool_name="http.request",
operation="http.get",
resource="https://api.github.com/repos/octo/hello", # fixed: the model cannot change it
)
content = invoke(client, spec, {}) # always a JSON string for the modelinvoke never raises for policy outcomes. It returns a JSON string whose outcome is allow (with the adapter result), deny, require_approval, rejected, or error, plus a message the model can relay to the user. See LangChain for every shape.
Argument values
The SDK serializes with sorted keys and compact separators, byte-for-byte identical to the TypeScript client. Argument values may be objects, arrays, strings, integers, booleans, and null. Floating-point numbers are rejected with ValueError so that the canonical hash is unambiguous across languages. Send decimals as strings, or as integers in minor units (for example cents).
Security notes
- Load the seed from a secret store or a file readable only by the agent's account. Never log it.
- Do not wrap
call_toolin code that runs a local fallback on deny. That reintroduces the bypass AgentShield removes. - Keep the client clock synchronized; requests more than 60 seconds off are rejected.
Implementation references
Was this page helpful?