GebSecure Docs v0.1.0

Get started

Quickstart: protect an agent with Python

Authorize and execute agent actions with the gebsecure Python SDK — allowed, approval-gated and denied.

This quickstart follows the Python example agent. Every snippet is taken from it, and the documentation test suite runs it against a real api, gateway and worker.

1. Install the SDK#

bash
pip install gebsecure          # Python 3.9+; depends on httpx, pydantic v2 and cryptography

The package provides a synchronous GebSecure client and an asyncio AsyncGebSecure client with the same methods, typed pydantic models (py.typed) and typed exceptions.

2. Provision the agent#

With a local stack running (self-hosting quickstart), an administrator signs in with a user session and uses the management API to deploy the policy, register the agent and install the billing connection:

examples/python-agent/provision.py
session = GebSecure(api_url=api_url, gateway_url=gateway_url, auth=Unauthenticated()).login(
    email=env("GEBSECURE_ADMIN_EMAIL"), password=env("GEBSECURE_ADMIN_PASSWORD")
)
admin = GebSecure(api_url=api_url, gateway_url=gateway_url, auth=StaticTokenAuth(session.access_token))
examples/python-agent/provision.py
source = (SHARED / "policy.gsl").read_text(encoding="utf-8")
if not admin.validate_policy(source).ok:
    raise SystemExit("policy.gsl is invalid")
existing = next((p for p in admin.list_policies(environment_id=environment["id"]).data if p.name == POLICY_NAME), None)
if existing:
    saved = admin.update_policy(existing.id, source=source, message="examples/python-agent provision")
else:
    saved = admin.create_policy(name=POLICY_NAME, source=source, scope={"type": "environment", "environmentId": environment["id"]})
deployment = admin.deploy_policy(saved.id, version_id=saved.version_id, comment="examples/python-agent provision")
if not deployment.deployed:
    raise SystemExit(f"deployment blocked: tests={deployment.tests} conflicts={deployment.conflicts}")
examples/python-agent/provision.py
agent = next((a for a in admin.list_agents(environment_id=environment["id"], q=AGENT_NAME).data if a.name == AGENT_NAME), None)
if agent:
    client_secret = admin.create_agent_credential(agent.id, type="client_secret", name=f"example-{int(time.time())}").client_secret
    # A previous run's injected article tainted the agent for 30 minutes; start clean.
    httpx.delete(f"{api_url}/v1/injection/taint/{agent.id}", headers=headers)
else:
    created = admin.create_agent(
        environment_id=environment["id"],
        name=AGENT_NAME,
        description="Customer-support agent that issues refunds (examples/python-agent)",
        framework="custom",
        tags=["support"],
        credential={"type": "client_secret", "name": "example"},
    )
    assert created.credential is not None
    client_secret = created.credential.client_secret
examples/python-agent/provision.py
config: dict[str, Any] = json.loads((SHARED / "billing-connection.json").read_text(encoding="utf-8"))
config.pop("$comment", None)
config["baseUrl"] = env("BILLING_API_URL", "http://127.0.0.1:4300")
try:
    connection = admin.create_connection(
        project_id=project["id"], environment_id=environment["id"], connector="rest", name=CONNECTION_NAME, auth_type="none", config=config
    )
except ConflictError:
    found = next(c for c in admin.list_connections(project_id=project["id"]).data if c.name == CONNECTION_NAME)
    connection = admin.update_connection(found.id, config=config)

provision.py prints GEBSECURE_CLIENT_SECRET (shown once) and the URLs for the agent.

3. Create a client#

Keyword arguments override the environment; without them the client reads GEBSECURE_GATEWAY_URL, GEBSECURE_API_URL and GEBSECURE_API_KEY or GEBSECURE_CLIENT_SECRET:

examples/python-agent/agent.py
# Reads GEBSECURE_GATEWAY_URL, GEBSECURE_API_URL and GEBSECURE_CLIENT_SECRET (or GEBSECURE_API_KEY).
client = GebSecure(max_retries=3)
connection = os.environ.get("BILLING_CONNECTION", "billing-api")
approval_timeout = float(os.environ.get("APPROVAL_TIMEOUT_SECONDS", "600"))

Use it as a context manager (with client:) or call client.close() to release the HTTP connection pool.

4. Inspect untrusted input#

examples/python-agent/agent.py
# 1. The ticket is untrusted: inspect it before the model reads it.
inspected = client.inspect(content=TICKET, source="email", origin="mailto:dana@example.com", traceparent=traceparent)
if text(inspected.action) == "BLOCK":
    raise SystemExit(f"ticket blocked: injection {text(inspected.injection.level)}")
ticket_for_model = str(inspected.content if inspected.content is not None else TICKET)
print(f"ticket inspection: {text(inspected.action)} (injection score {inspected.injection.score})")
outcomes["ticketInspection"] = text(inspected.action)

5. Authorize, then act#

guard() returns GuardResult(allowed=…, decision=…); allowed is true only for ALLOW. Denials and approval requirements are results, not exceptions.

examples/python-agent/agent.py
# 2. Authorize-only: read the ticket from the agent's own store if policy allows it.
plan_start = now_ms()
read = client.guard("support:tickets.read", "ticket:T-1042", {"channel": "email"}, traceparent=traceparent)
if not read.allowed:
    raise SystemExit(f"cannot read tickets: {read.decision.reason}")
outcomes["readTicket"] = text(read.decision.decision)
plan = ["refund-small", "refund-large", "delete-customer"] if "ch_0977" in ticket_for_model else ["refund-small"]
plan_span = build_span(
    "agent.plan", plan_start, now_ms(), traceparent=traceparent, kind="internal", status="ok", attributes={"steps": len(plan)}
)
child = traceparent_of(plan_span)  # later calls are children of the plan span

6. Execute through GebSecure#

examples/python-agent/agent.py
# 3. A small refund: allowed, executed through the billing-api connection with brokered credentials.
small = client.execute(
    connection=connection,
    action="refunds.create",
    input={"chargeId": "ch_1043", "amount": 40, "currency": "USD"},
    traceparent=child,
)
summarize("refund $40", small)
outcomes["smallRefund"] = text(small.status)

Every method accepts a request model, a mapping (wire or Python names) or keyword fields. execute() returns an ExecuteResult for succeeded, simulated, awaiting_approval, running, denied and failed, and adds an idempotency key when retries are enabled.

7. Wait for a human approval#

The $400 refund needs an owner's approval. Once a reviewer approves it, the GebSecure worker resumes the stored execution; the agent waits for the decision and follows the execution:

examples/python-agent/agent.py
# 4. A larger refund needs a human approval. The execution is stored as awaiting_approval; once a
#    reviewer approves, the GebSecure worker resumes it with the approval (consumed exactly once).
large = client.execute(
    connection=connection,
    action="refunds.create",
    input={"chargeId": "ch_0977", "amount": 400, "currency": "USD"},
    traceparent=child,
)
if text(large.status) == "awaiting_approval" and large.approval and large.execution_id:
    print(f"refund $400: waiting for approval {large.approval.id} ({large.approval.url})")
    try:
        approval = client.wait_for_approval(large.approval.id, timeout=approval_timeout, poll_interval=2, traceparent=child)
        # "consumed" means the worker already resumed the execution with it.
        if text(approval.status) not in ("approved", "consumed"):
            raise ApprovalNotGrantedError(approval)
        done = wait_for_execution(client, large.execution_id)
        print(f"refund $400: {text(done.status)} {json.dumps(done.output)}")
        outcomes["largeRefund"] = text(done.status)
    except ApprovalNotGrantedError as e:
        outcomes["largeRefund"] = f"approval {text(e.approval.status)}"
        print(f"refund $400: {outcomes['largeRefund']}")
    except ApprovalTimeoutError:
        outcomes["largeRefund"] = "approval timed out"
        print("refund $400: approval timed out")
else:
    summarize("refund $400", large)
    outcomes["largeRefund"] = text(large.status)
examples/python-agent/agent.py
ACTIVE = {"pending", "running", "awaiting_approval", "cancelling"}


def wait_for_execution(client: GebSecure, execution_id: str, timeout: float = 120.0) -> Execution:
    """Polls an execution until it reaches a final status (succeeded, failed, denied, cancelled)."""
    deadline = time.time() + timeout
    while True:
        execution = client.get_execution(execution_id)
        if text(execution.status) not in ACTIVE:
            return execution
        if time.time() > deadline:
            raise TimeoutError(f"execution {execution_id} still {text(execution.status)}")
        time.sleep(1)

The reviewer, with the Python SDK:

examples/python-agent/approve.py
# Pending approvals this reviewer can decide right now; this reviewer handles refunds only.
inbox = reviewer.list_approvals(inbox=True, status="pending")
refunds = [a for a in inbox.data if a.action == "rest:refunds.create"]
for a in refunds:
    details = reviewer.get_approval_details(a.id)  # the snapshot the reviewer is deciding on
    print(f"{verdict} {a.id}: {details.action} on {details.resource} - {details.reason or ''}")
    result = reviewer.decide_approval(
        a.id,
        decision=verdict,
        snapshot_hash=details.snapshot_hash,
        comment="Verified the duplicate charge" if verdict == "approve" else "Refund not justified",
        channel="api",
    )
    print(f"  -> {getattr(result.status, 'value', result.status)}")

8. Denials, retrieved content and spans#

examples/python-agent/agent.py
# 5. Deleting a customer is forbidden; a denial is a result, not an exception.
deleted = client.execute(connection=connection, action="customers.delete", input={"customerId": "cus_dana"}, traceparent=child)
summarize("delete customer", deleted)
outcomes["deleteCustomer"] = text(deleted.status)
examples/python-agent/agent.py
# 6. Retrieved content is inspected too; a flagged result taints the agent for a while.
kb = client.inspect(content=KB_ARTICLE, source="rag", origin="kb://refund-policy", traceparent=child)
print(
    f"knowledge-base inspection: {text(kb.action)} (injection {text(kb.injection.level)}, "
    f"score {kb.injection.score}, tainted: {bool(kb.injection.tainted)})"
)
outcomes["kbInspection"] = text(kb.action)
examples/python-agent/agent.py
# 7. Report the agent's spans; the run span is the trace root every traceparent above points to.
run_span = build_span("agent.run", plan_start, now_ms(), span_id=root_span_id, kind="internal", status="ok")
run_span = run_span.model_copy(update={"trace_id": trace_id})
reported = client.report_spans([plan_span, run_span])
print(f"trace {trace_id}: {reported.accepted} agent spans reported")

Async#

AsyncGebSecure mirrors the synchronous client; cancelling the awaiting task aborts the in-flight request, a pending backoff sleep or an approval poll:

docs/site/snippets/python/async_guard.py
"""AsyncGebSecure: concurrent authorization checks with asyncio.

    GEBSECURE_CLIENT_SECRET=gsa_... GEBSECURE_GATEWAY_URL=http://localhost:4100 GEBSECURE_API_URL=http://localhost:4000 \\
    python docs/site/snippets/python/async_guard.py
"""

from __future__ import annotations

import asyncio
import json

from gebsecure import AsyncGebSecure


async def main() -> None:
    async with AsyncGebSecure(max_retries=2) as client:
        # dry_run=True evaluates without side effects (no approval request, no limit consumption).
        read, delete = await asyncio.gather(
            client.authorize(action="support:tickets.read", resource="ticket:T-1042", dry_run=True),
            client.authorize(action="rest:customers.delete", resource="billing:customer/cus_dana", dry_run=True),
        )
        for d in (read, delete):
            print(getattr(d.decision, "value", d.decision), "-", d.reason, f"(risk {d.risk.score})")
        print("RESULT " + json.dumps({"read": getattr(read.decision, "value", read.decision), "delete": getattr(delete.decision, "value", delete.decision)}))


if __name__ == "__main__":
    asyncio.run(main())

Next steps#