Python SDK
The package is preworld-guard-sdk, imported as preworld_guard. It runs on Python 3.11 and 3.12. The base package depends only on httpx, pydantic and PyYAML. Frameworks come with extras. import preworld_guard never imports a framework.
Current hosted production offers preworld-guard-sdk==0.10.0. Version 0.11.0 will use yi-guard-sdk; use that name only after it is released and appears on your private index. The preworld_guard import and CLI names stay unchanged.
Install
Install only from the private SDK source specified by your console, with its pinned version and hash. Do not install from public PyPI.
- Hosted control plane: your private SDK index, reached with an SDK download token. Use the install command the console gives you. It pins the wheel's address and sha256. See Quickstart.
- Self-hosted control plane: the wheel or private index we provide. Pin the version and its hash.
| Extra | Installs |
|---|---|
mcp | The MCP proxy |
identity | JWT checks (RS256, issuer, audience, scope) for the broker and the MCP proxy |
oauth | Per-user OAuth to MCP upstreams, with the encrypted vault |
gateway | The HTTP broker |
langchain, langgraph, claude, openai-agents, pydantic-ai, google-adk, agent-framework, llama-index, agno, dspy, crewai | One framework adapter each; see Framework adapters |
Some combinations can't be installed together. See Extras that conflict.
GuardClient
GuardClient(endpoint, token, project_id, *, agent_id="python-agent", cache_path=None, timeout=5.0,
refresh_interval=60.0, max_stale_age=300.0, background_events=False, event_batch_size=50,
event_flush_interval=1.0, max_outbox_bytes=8_000_000, proxy=None, ca_bundle=None)| Parameter | Default | Meaning |
|---|---|---|
endpoint | The control plane's address | |
token | The executor credential (PREWORLD_GUARD_TOKEN in guard.env) | |
project_id | The project | |
agent_id | python-agent | The agent this credential belongs to |
cache_path | .preworld-guard/policy.json | Where the verified policy is cached; PREWORLD_GUARD_CACHE sets it too. The event queue and approval snapshots live next to it |
timeout | 5 s | Timeout for each control-plane request |
refresh_interval | 60 s | How often the policy is refreshed when it's used |
max_stale_age | 300 s | How long the cached policy may be used without reaching the control plane. After that every protected action is blocked |
background_events | False | Send events from a background thread instead of inline. Use it for agents with many calls |
max_outbox_bytes | 8,000,000 | Size of the local event queue. When it is full, new actions are blocked |
proxy, ca_bundle | An HTTP(S) proxy and a CA bundle for control-plane traffic; also PREWORLD_GUARD_PROXY and PREWORLD_GUARD_CA_BUNDLE |
The SDK ignores HTTPS_PROXY and SSL_CERT_FILE. The proxy and CA settings cover only control-plane traffic: policy, heartbeats, events, approvals, connection-check, trial-check, siem-export and onboard. Guarded HTTP, the broker, MCP upstreams, OAuth and JWKS traffic never use the proxy, because it would bypass the address checks.
Lifecycle
| Method | What it does |
|---|---|
start(*, name="python-sdk", version=..., heartbeat_interval=15.0) | Registers the executor, declares the agent as an asset, sends a heartbeat, then keeps syncing policy and sending heartbeats every 15 seconds in a background thread. Returns the client |
lifecycle_status | Executor ID, status, last error, loaded policy version and hash, and whether the policy came from the control plane or the cache |
close() | Sends a last stopped heartbeat, stops the background threads and sends queued events if it can. Call it on shutdown |
Protecting calls
| Method | What it does |
|---|---|
@guard.tool(resource=None, *, action_type="tool.call", pending=False) | Wraps a sync or async function. Decides before each call, records started and completed, runs a registered fallback for degrade rules. pending=True keeps an argument snapshot for approval resume |
authorize(resource, arguments=None, *, action_type="tool.call", destination=None, data_labels=(), subject_id=None, ...) | Decides one action and returns (action, decision), or raises. Use it when you run the side effect yourself |
register_fallback(resource, function, *, map_arguments) | Registers the fallback a degrade rule names. It can't be replaced while running |
approval_status(ticket_id), cancel_approval(ticket_id) | Read or withdraw an approval ticket this executor filed |
pending.status(ticket_id), pending.resume(ticket_id), pending.resume_async(ticket_id), pending.cancel(ticket_id), pending.list() | Approval snapshots for tools wrapped with pending=True |
Context
| Function | What it does |
|---|---|
guard_run(*, session_id=None, subject_id=None, run_id=None, trace_id=None) | Context manager. Sets the trusted subject and correlation IDs for every Guard call inside it. The subject must come from your application, never from the model |
guard_approval(ticket_id) | Context manager. The next matching call consumes this approved ticket; any later use fails |
guard_resume(*ticket_ids) | Context manager for adapters. An approved ticket is consumed when the same action is proposed again; other calls are decided normally |
current_run() | The active guard_run context, if any |
The decision
GuardDenied.decision and the decision returned by authorize have:
| Field | Meaning |
|---|---|
effect | allow, deny, allow_with_warning, require_approval or degrade |
would_effect | What an enforcing policy would decide |
rule_id | The rule that decided, or default-allow, default-deny, policy-expired |
reason_code | ALLOWED, RULE_DENIED, DEFAULT_DENY, APPROVAL_REQUIRED, DEGRADED, POLICY_EXPIRED, SUBJECT_REQUIRED, APPROVED… |
message | The rule's message |
policy_version, policy_hash | The policy that decided |
fallback_resource | For degrade |
Exceptions
| Exception | Raised when |
|---|---|
GuardError | Base class. Also raised when there is no valid policy, or the cached policy is older than max_stale_age |
GuardTransportError | The control plane can't be reached. A verified cache may still be used |
GuardRequestRejected | The control plane refused a request with a 4xx other than 401/403; status_code says which |
GuardAuthError | The credential is invalid. Never falls back to the cache; create a new client with a new credential |
GuardDenied | The decision is deny; decision holds it |
GuardApprovalRequired | A subclass of GuardDenied: a ticket was filed. ticket_id, expires_at, status |
GuardDegradeRequired | A subclass of GuardDenied: a degrade rule applies and no fallback ran on this path |
GuardSubjectRequired | An approval rule matched a call without a trusted subject |
GuardFallbackUnavailable | The fallback a degrade rule names isn't registered, or can't run on this path |
GuardUnavailable | In adapters (preworld_guard._adapter): Guard couldn't decide. Its payload is safe to show the model |
In every case the tool must not run.
Control-plane retries
From 0.9.0, a control-plane request that fails at the connection level is sent once more, immediately, but only when that can't repeat a side effect. A request that never left the client is always retried. One that may have been sent is retried only if it is a read, an event upload or an approval request, which the control plane deduplicates. Consuming a ticket, registering and heartbeats are never repeated. A request can therefore take up to twice timeout.
Other modules
| Module | For |
|---|---|
preworld_guard.egress | GuardedHTTPClient, GuardedAsyncHTTPClient; see HTTP egress |
preworld_guard.gateway | The HTTP broker (python -m preworld_guard.gateway --config ...) |
preworld_guard.policy_dsl | parse_policy_document, load_policy_yaml, compile_policy, policy_json_schema |
preworld_guard.langgraph, .pydantic_ai, .google_adk, .agent_framework, .llama_index, .agno, .dspy, .crewai | Framework adapters. GuardMiddleware, GuardHooks and protect_function_tool are importable from preworld_guard directly |