Metadata-Version: 2.4
Name: shieldaai-agent-guard
Version: 0.1.0.dev0
Summary: Python client for the Agent Guard decision server: ask before every AI agent tool call, run it, report back. LangChain, LangGraph and CrewAI helpers. No runtime dependencies.
Keywords: ai-agents,security,authorization,tool-calling,langchain,langgraph,crewai,human-in-the-loop
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.10
Project-URL: Homepage, https://github.com/ShieldaAI/agent-guard/tree/main/clients/python
Project-URL: Documentation, https://github.com/ShieldaAI/agent-guard/blob/main/docs/decide-api.md
Project-URL: Issues, https://github.com/ShieldaAI/agent-guard/issues
Description-Content-Type: text/markdown

# shieldaai-agent-guard

> **Preview.** New in Agent Guard 1.9.0. The HTTP API it speaks may still change in a minor
> release, and it has no production users yet. Please
> [open an issue](https://github.com/ShieldaAI/agent-guard/issues) if something does not fit.

Python client for the Agent Guard decision server. Before each tool call, your agent asks the
server whether the call may run. On yes, it runs the tool itself with the arguments the server
checked, then reports the outcome. The server applies Agent Guard's checks: grants per task and
resource, allowed recipients, sensitive and untrusted data, secrets in external calls, approvals
by a person, call and cost budgets, and your policies.

No runtime dependencies. Python 3.10 or later. Helpers for LangChain, LangGraph and CrewAI.

```sh
pip install shieldaai-agent-guard
```

## Start the server

The server is `agent-guard-decide`, from the npm package `@shieldaai/agent-guard-adapters`
(Node.js 22 or later). It reads a JSON file that lists your tools, and you get its admin token
from the environment:

```sh
export AGENT_GUARD_ADMIN_TOKEN="$(npx -y -p @shieldaai/agent-guard-adapters@1.9.0 agent-guard-decide --new-token)"
npx -y -p @shieldaai/agent-guard-adapters@1.9.0 agent-guard-decide --config decide.json
```

```json
{
  "version": 1,
  "tools": [
    {
      "name": "ticket_read",
      "description": "Read one support ticket",
      "inputSchema": {
        "type": "object",
        "properties": { "id": { "type": "string", "pattern": "^[0-9]+$" } },
        "required": ["id"],
        "additionalProperties": false
      },
      "resource": "ticket:{id}",
      "readsUntrusted": true
    },
    {
      "name": "ticket_close",
      "description": "Close one support ticket",
      "inputSchema": { "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] },
      "resource": "ticket:{id}",
      "requiresApproval": true
    }
  ]
}
```

`resource` names what the call touches, built from its arguments. A task may only call a tool
on the resources it was granted. Every field is described in
[the API reference](https://github.com/ShieldaAI/agent-guard/blob/main/docs/decide-api.md#configuration).

## Create a task, then guard the tools

Your backend creates one task per job, for the user it signed in, and gives the agent only the
task's token:

```python
from shieldaai.agent_guard import AdminClient, Grant, TaskClient

admin = AdminClient("http://127.0.0.1:8787", admin_token)  # your backend only
task = admin.create_task(
    principal_id=user.id,          # from your own sign-in, never from the model
    tenant_id=user.tenant_id,
    grants=[Grant("ticket_read", ["ticket:42"]), Grant("ticket_close", ["ticket:42"])],
    max_calls=20,
    max_concurrent=4,              # LangGraph runs one message's tool calls in parallel
    ttl_seconds=600,
)

guard = TaskClient("http://127.0.0.1:8787", task.token)  # the agent side

@guard.tool()
def ticket_read(id: str) -> dict:
    return tickets.get(id)
```

`ticket_read(id="42")` asks the server, runs the function and reports the outcome.
`ticket_read(id="7")` raises `ToolDenied`, because the task was granted ticket 42 only;
`str(error)` is a message written for the model. If the function raises, the failure is
reported and the exception propagates.

A tool that needs approval raises `ApprovalPending` (with `action_id`). Calling it again with
the same arguments does not queue a second request: it raises `ApprovalPending` for the same
action until a person approves it, and then runs it. Pass `wait_for_approval=120` to wait in the
call instead.

- `max_concurrent` (default 1) is how many calls may run at once. Set it to at least the number
  of tool calls a model may make in one turn, or the extra ones are denied with
  `CONCURRENCY_EXCEEDED`. The server lets one task token have 8 requests in progress (a call
  waiting for approval counts); raise `server.maxActiveRequestsPerCredential` in its
  configuration for more.
- The guard sees every argument by name, defaults included (except a default of `None`, which is
  not sent), so the schema must list every parameter. The function runs with the values it
  checked after a JSON round trip: a tuple arrives as a list, a date as a string.
- `@guard.tool` and `@guard.tool("name")` both work, on `def` and `async def`. For a method, call
  `guard.run("name", args, call)` inside it.
- `cost=lambda result: ...` reports what the call cost. A cost that fails or is out of range is
  logged and the call is charged its maximum.

## LangChain and LangGraph

```python
from shieldaai.agent_guard.langchain import guard_tools
from langgraph.prebuilt import create_react_agent

agent = create_react_agent(model, guard_tools(guard, [ticket_read, ticket_close]))
```

Each guarded tool keeps its name, description and schema. A denial reaches the model as the
tool's error message, so the agent reads why instead of stopping. Arguments the tool marks as
injected (`InjectedToolArg`, `InjectedState`, `InjectedToolCallId`) are filled in by your code
or LangGraph, so they are not sent to the guard and it does not check them; every other
argument is. A tool that returns a LangGraph `Command` returns it unchanged. `config_entry(tool,
resource="ticket:{id}")` builds the server configuration entry from a LangChain tool, so the
server checks the same schema the model is shown.

## CrewAI

```python
from shieldaai.agent_guard.crewai import guard_tools

agent = Agent(role="Support", goal="...", backstory="...", tools=guard_tools(guard, [ReadTicket()]))
```

The guarded copies never write to CrewAI's result cache: a cached answer would skip the check
and the budget. CrewAI also reads that cache by tool name for the whole crew, so create the crew
with `cache=False`.

## Approvals

```python
for item in admin.pending(tenant_id=reviewer.tenant_id):
    if item.state == "pending":          # "approved" ones wait for the agent to collect them
        # Show item.tool, item.args and item.resource_id to the reviewer, then:
        admin.approve(item.action_id, approver_id=reviewer.id)   # or admin.reject(item.action_id)
```

The agent collects the approval by calling the tool again with the same arguments, by calling
`guard.wait(action_id, timeout=...)`, or in the call itself when the decorator was given
`wait_for_approval`.

## Connections

Each call through the decorator, `run` or the framework helpers sends a fresh `callId` with its
decision. If the answer is lost to a timeout or a dropped connection, the client asks once more
with the same ID and gets the first answer back, so a retry never starts a second call.

The client never follows a redirect and ignores proxy settings such as `HTTP_PROXY`, so the
token goes only to the URL you gave. Plain `http://` is accepted for this machine
(`localhost`, `127.0.0.1`); for any other host use `https://`, or pass
`allow_insecure_http=True` on a network you trust.

## What it does not do

- **It cannot stop a call that is already running.** Revoking a task stops new decisions. A
  call that was allowed and has started finishes on your side.
- **It never sees results.** It records what you report. If no report arrives within the
  server's lease (60 seconds by default), it records the call as failed with an unknown effect
  and charges its full cost.
- **Resource templates cannot look up who owns a resource.** Grant the exact resources a task
  needs. When the owner has to be checked, write the tool in JavaScript with its own `resolve`
  function ([guard library](https://github.com/ShieldaAI/agent-guard/tree/main/packages/core)).
- **It does not detect prompt injection.** It limits what a misled agent can do.

## API

| | |
| --- | --- |
| `TaskClient(url, token)` | `decide(tool, args)` returns `Allow`, `Deny` or `NeedsApproval` (the HTTP API's `allow`, `deny` and `require_approval`). Also `wait(action_id, timeout)`, `report(action_id, "succeeded" \| "failed", actual_cost)`, `status()`, `run(tool, args, call)`, `arun(...)` and the `tool()` decorator |
| `AdminClient(url, admin_token)` | `create_task(...)`, `revoke_task(task_id)`, `task_status(task_id)`, `pending(task_id=..., tenant_id=...)`, `approve(action_id, approver_id=...)` (returns when the approval expires, in clock milliseconds), `reject(action_id)` |
| Exceptions | `ToolDenied` (nothing ran), `ApprovalPending` (nothing ran yet), `ServiceError` (the server refused the request or could not be reached), all subclasses of `GuardError` |

Licensed under Apache-2.0.
