Skip to main content

kollguard (Python)

Authorize every tool call your Python agent makes before it runs. Each call is checked against your KollGuard Agent Watch policy and answers allow, deny, or pending (a named human approves it in KollGuard).

  • Adapters for LangGraph and the OpenAI Agents SDK, both optional extras.
  • Zero runtime dependencies (stdlib only). Sync and async. Python 3.9+.
  • Argument values never leave your host. KollGuard sees the tool name, the argument names, and the optional resource string you choose to pass. The kgw_ token goes only in the x-agent-token header and is never logged or included in an exception message.
  • Fail modes per tool. If KollGuard cannot answer (network, timeout, 5xx, 429, bad token), a tool marked fail: "closed" is blocked and a tool marked fail: "open" runs. The default is closed.

Enforcement is cooperative: this SDK gates the calls that go through it. It is not a sandbox, and code that bypasses the wrapper is not gated. Agent Watch labels it that way on the agent's passport.

Get an agent token in KollGuard under Agent Control, then:

export KOLLGUARD_AGENT_TOKEN=kgw_...

LangGraph in 3 steps

pip install "kollguard[langgraph]"
  1. Swap ToolNode for the gated one.
  2. Compile with a checkpointer (needed for approvals that pause the graph).
  3. Resume with Command(resume=...) after the human decides in KollGuard.
from kollguard import KollGuard
from kollguard.langgraph import kollguard_tool_node
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command

kg = KollGuard(policy={"tools": {"send_email": {"class": "external_comm"},
                                 "lookup":     {"class": "read", "fail": "open"}}})

graph.add_node("tools", kollguard_tool_node([send_email, lookup], kg))      # step 1
app = graph.compile(checkpointer=InMemorySaver())                           # step 2

out = app.invoke({"messages": [("user", "email the customer")]}, {"configurable": {"thread_id": "t1"}})
if "__interrupt__" in out:                                                  # pending approval
    print(out["__interrupt__"][0].value)   # {"kind": "kollguard_approval", "kollguard_request_id": ..., ...}
    # ...the approver clicks Approve in KollGuard...
    out = app.invoke(Command(resume=True), {"configurable": {"thread_id": "t1"}})   # step 3

What happens: allow runs the tool; deny returns a ToolMessage(status="error") to the model and the tool never runs; pending calls interrupt(). LangGraph re-executes the node on resume, and the idempotency key (thread_id + tool_call_id) makes the second check a replay of the same request, never a duplicate. The resume value is never treated as approval: KollGuard is asked again, and if it is still pending the graph interrupts again.

ToolNode(..., **kollguard_wrappers(kg)) and kollguard.langgraph.check(kg, name, args, ...) (for your own nodes) are also available. The wrapper has the (request, handler) shape of AgentMiddleware.wrap_tool_call.

OpenAI Agents SDK in 3 steps

pip install "kollguard[openai-agents]"
  1. Wrap your tools with guard_tool.
  2. Run the agent; a call that needs a human stops the run with an interruption.
  3. After the human decides in KollGuard, call resolve_interruptions and run again from the state.
from agents import Agent, Runner, function_tool
from kollguard import KollGuard
from kollguard.openai_agents import guard_tool, aresolve_interruptions

kg = KollGuard(policy={"tools": {"refund": {"class": "money_auth"}}})

@function_tool
def refund(order_id: str) -> str: ...

agent = Agent(name="support", tools=[guard_tool(refund, kg)])                # step 1
result = await Runner.run(agent, "refund order 42")                          # step 2
while result.interruptions:
    # ...wait for the approver in KollGuard...
    state = result.to_state()
    await aresolve_interruptions(state, kg)      # approves/rejects each call from KollGuard's answer   (step 3)
    result = await Runner.run(agent, state)

guard_tool attaches two things: a ToolInputGuardrail that is the real gate (runs just before the tool, after any approval, so a local state.approve() can never bypass KollGuard) and a needs_approval that returns True only while KollGuard has the call pending. Both use the model's call_id as the idempotency key. Use kollguard_tool_guardrail(kg) / kollguard_needs_approval(kg, "tool_name") separately if you prefer.

Resumable approvals (hours or days)

A pending request normally expires after 15 minutes, which only suits a process that waits. With a server that reports resumable in GET /v2/policy (hosted KollGuard does, with v2, webhooks and quorum), the request waits up to 72 hours (7 days on Enterprise) and the run can suspend and exit:

kg = KollGuard(contract="auto")          # probes GET /v2/policy once; "v2" assumes it, the default "v1" never uses it
kg.capabilities()                        # ["v2", "resumable", "webhooks", "quorum"]

d = kg.decide("refund", args, action_class="money_auth", ids=(run_id, tool_call_id), wait="resumable")
if d.pending:                            # d.resumable is True; returned at once, nothing is polling
    suspend(d.request_id, d.expires_at)
# ...when the run resumes (any process), call decide() again with the SAME ids:
d = kg.decide("refund", args, action_class="money_auth", ids=(run_id, tool_call_id), wait="resumable")
  • Resume = re-decide with the same ids. The ids make a stable key with no time component, so the server replays the stored request. Once a human approved it, the first re-decide returns allow, and the allow counts 15 minutes from that first use, not from the approval. A deny or an expiry replays as deny. A resumable wait with no stable ids raises KollGuardConfigError (a time-based key would file a second request on resume).
  • Without the capability, the same call is an inline wait (15-minute request); nothing else changes.
  • kg.choose_wait(ids) returns "resumable" or "inline" for adapters. The LangGraph and OpenAI Agents adapters use it: resumable when the server reports it, an inline-window request otherwise.
  • An agent may hold 500 open resumable requests; beyond that the server answers deny (HTTP 429).

Decision webhooks

Register a webhook (owner or admin: POST /api/agent-watch/authorizations/webhooks with {"url": "https://..."}; the answer carries webhook.webhookId and a whsec_... secret, shown once), then name it per request and verify the callbacks:

d = kg.decide("refund", args, ids=(run_id, call_id), wait="resumable", callback=WEBHOOK_ID)   # lowercase uuid; needs 'webhooks'

# in your https endpoint (Flask shown); use the RAW body
@app.post("/kollguard")
def kollguard_hook():
    try:
        p = verify_webhook(request.headers, request.get_data(), WEBHOOK_SECRET)   # or kg.verify_webhook(...)
    except WebhookError:
        return "", 400
    resume_run(p["requestId"], p.get("runRef"))      # then re-decide with the same ids: that answer is the truth
    return "", 204

Payload: {"requestId", "decision": "allow" | "deny" | "expired", "idempotencyKey"?, "runRef"?, "framework"?}; no action text or approver identity. Headers: webhook-id (the same on every retry: dedupe on it), webhook-timestamp (unix seconds, fresh per attempt; more than 300 s off is rejected) and webhook-signature (v1,<base64 HMAC-SHA256> over <id>.<timestamp>.<body>; several space-separated signatures are accepted). Failures are retried after 30 s, 2 min, 10 min, 30 min, 1 h, 2 h and 6 h (8 attempts in all). Callbacks are advisory: a lost or forged one can only delay a run, never allow one. verify_webhook is byte-compatible with @kollguard/core; both are tested against signatures from the live signer.

Any other agent

d = kg.gate("send_email", {"to": to, "body": body}, framework="my-agent", resource="mail:outbound")
if not d.allowed:            # d.decision is "deny" or "pending"; d.reason says why
    raise PermissionError(d.reason)

kg.decide() asks once; kg.gate() also waits inline (default 120 s) for a human; kg.wait_for_decision(request_id) polls. Async twins: adecide, agate, await_decision, apoll. None of them raise for an answer or a network problem (only a call that can never work, such as a malformed callback, raises KollGuardConfigError).

Policy file

A compatible subset (tools, default) of the JSON kollguard-claude-hook reads (mcp and mcpServers are ignored):

{
  "tools": {
    "send_email": {"class": "external_comm", "fail": "closed"},
    "lookup_order": {"class": "read", "fail": "open"},
    "get_time": {"gate": false},
    "stripe_*": {"class": "money_auth"}
  },
  "default": {"class": "unclassified", "fail": "closed"}
}

KollGuard(policy="kollguard.policy.json"). Classes: read, propose, write, external_comm, money_auth, phi_access, patient_facing, unclassified. "gate": false makes no network call (zero added latency).

What is sent

Sent Never sent
tool name, framework label, argument names, action class, your optional resource and summary text, an HMAC idempotency key argument values, prompts, completions, tool results, the token in any body or log

resource is sent exactly as you give it (the server redacts it before storage): pass a template such as stripe:refund, not a value.

Limits in this release

  • Python: the core client runs on 3.9+. The LangGraph and OpenAI Agents extras need 3.10+ (their own floor). Using LangGraph with async graphs and approvals (interrupt()) needs Python 3.11+ (LangGraph relies on contextvars there; verified failing on 3.10). Sync graphs work on 3.10.
  • OpenAI Agents: do not enable RunConfig.tool_execution.pre_approval_tool_input_guardrails together with guard_tool. The guardrail would then run before the pause and turn a pending call into a refusal instead of an interruption.
  • If one tool_call_id is asked again after its request has expired twice, the deterministic retry key replays the expired row and the call is denied (fail-safe) rather than re-filed.
  • The default contract="v1" (works with every deployed server): pending requests expire after 15 minutes and an allow is valid for 15 minutes. Use contract="auto" for resumable approvals (72 h, 7 days on Enterprise) and webhooks.
  • If a resumable request expires unanswered, the re-decide is treated like any expired replay: one deterministic retry key files a new request.
  • Not included yet: the OpenTelemetry span processor.

Develop

uv venv && uv pip install -e ".[langgraph,openai-agents,test]"
pytest

The tests run a fake gate that enforces the route's exact validation, and the adapter tests run against the real frameworks when installed (mocked otherwise).

Release

python -m pip install build twine
python -m build            # dist/kollguard-<version>.tar.gz and .whl
twine upload dist/*        # needs a PyPI account and API token for the `kollguard` project

MIT licensed.

Metadata

Release files for kollguard 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kollguard 0.2.0
File Size Uploaded Provenance Actions
kollguard-0.2.0.tar.gz 37.3 kB Without provenance Details for kollguard-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kollguard 0.2.0
File Interpreter ABI Platform Actions
kollguard-0.2.0-py3-none-any.whl Python 3 none any Details for kollguard-0.2.0-py3-none-any.whl

Total release size: 63.5 kB

Release files / kollguard-0.2.0.tar.gz

Download URL kollguard-0.2.0.tar.gz
Size 37.3 kB
Tags Source
SHA-256 checksum
How to use checksums
84cbdc2c73c2937237a8b3d80245c810341c7da417e2305cc957565a2828b93b
BLAKE2b-256 checksum
How to use checksums
4e6aba6685c18471f93ef830c9e48659fb4279dffd4e91bac60a7d29a39a1cba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Release files / kollguard-0.2.0-py3-none-any.whl

Download URL kollguard-0.2.0-py3-none-any.whl
Size 26.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
87c995f38edd6a92baf22d322c254619594c58a08efc2506165547f6d2def76c
BLAKE2b-256 checksum
How to use checksums
29ebb6bd1e883b860518c9e6ede434349530f28d5312ffa099aed21e8cec92ae
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Security for kollguard 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page