Skip to content

Latest commit

 

History

History
230 lines (183 loc) · 12.4 KB

architecture.md

File metadata and controls

230 lines (183 loc) · 12.4 KB

Architecture

toolguard is one control inside an AI gateway. This page shows where it sits, what it decides, what it stores, and how it behaves when things around it fail. The reasoning behind each choice is in decisions/.

Context

Agents call models through a gateway. Models propose tool calls; the gateway dispatches them to MCP servers. toolguard sits between the proposal and the dispatch.

flowchart LR
  A["Agents<br/><i>ours and third-party</i>"]

  subgraph GW["AI gateway (LiteLLM)"]
    direction TB
    AUTH["Authenticate<br/><i>identity from the key</i>"]
    TG["<b>toolguard</b><br/><i>classify · budget · approve · audit</i>"]
  end

  P["Model providers"]
  M["MCP servers<br/><i>wiki · tickets · repo · mail</i>"]
  DB[("Postgres<br/><i>budgets, events, audit</i>")]
  OBS["Metrics<br/><i>aggregates only</i>"]
  H["Humans<br/><i>approver · operator reset</i>"]

  A --> AUTH --> P
  P -. "proposes a tool call" .-> TG
  TG -->|"allowed calls only"| M
  TG <--> DB
  TG --> OBS
  H --> TG
Loading

Three properties of this picture carry the design:

  • Identity comes from the authenticated key, never from the request body. The request is downstream of a model an attacker may have influenced.
  • The gateway must be the only path to MCP servers. If an agent can reach a server directly, every control here is optional, so network egress to MCP servers should be allowed only from the gateway.
  • toolguard is in-process, a library loaded by the gateway, not a separate service, so there is no extra network hop on every tool call (ADR 0008).

Request path

What happens to one proposed tool call, and every way out of toolguard.

flowchart TB
  START(["Model proposes a tool call"]) --> TG

  subgraph TGBOX["toolguard"]
    direction TB
    TG{"<b>Registered, and on a server<br/>this agent may reach?</b>"}
    TG -->|"no"| DENY1["<b>Deny.</b> Unknown blast radius,<br/>or server not allowed"]
    TG -->|"yes"| IMPACT{"<b>Effective impact?</b><br/><i>declared, then promoted if</i><br/><i>irreversible or externally visible</i>"}
    IMPACT -->|"read or reversible write"| PASS["<b>Allow.</b> No budget consumed"]
    IMPACT -->|"destructive"| APPR{"Approval<br/>required?"}
    APPR -->|"yes, and none given"| ASK["<b>Require approval</b><br/><i>bound to the exact arguments</i>"]
    APPR -->|"no, or valid grant"| BUDGET{"<b>Budget, every scope</b><br/><i>run · actor · agent · team · tool</i><br/><b>locked in key order, atomically</b>"}
    BUDGET -->|"any scope exhausted"| DENY2["<b>Deny</b>, naming the scope.<br/><i>Human reset required</i>"]
    BUDGET -->|"within"| ALLOW["<b>Allow.</b> Slot reserved"]
  end

  ALLOW --> DISPATCH["Gateway dispatches to the MCP server"]
  DISPATCH --> SETTLE{"Outcome?"}
  SETTLE -->|"executed"| KEEP["Slot stays charged"]
  SETTLE -->|"provably not"| REL["Slot released"]
  SETTLE -->|"unknown"| PROV["<b>Stays charged</b>, provisionally.<br/><i>Reconcilable if the tool can be asked</i>"]

  classDef decision fill:#e8eef7,stroke:#4a6484,color:#111
  classDef deny fill:#7a2e2e,stroke:#4a1b1b,color:#fff
  classDef allow fill:#1f6f4a,stroke:#0d3d28,color:#fff
  class TG,IMPACT,APPR,BUDGET,SETTLE decision
  class DENY1,DENY2 deny
  class PASS,ALLOW allow
Loading

toolguard binds to LiteLLM's pre_mcp_call guardrail hook: after the model proposes, before the gateway dispatches (ADR 0001). Every decision except an allowed read is written to the audit log; reads are audited too if audit_reads is on. Settling an outcome updates the reservation rather than writing a new audit record.

Components

The engine has no gateway dependency at all. Everything LiteLLM-specific is one adapter file, so an upstream API change costs one file.

Module Responsibility
domain.py Typed model: principals, tool calls, impact, judgements. Holds the promotion rule
registry.py, config.py The tool inventory, and strict YAML validation that rejects unsafe settings outright
policy.py Scope derivation, server allowlists, fail behaviour per impact class
engine.py The decision path, in four phases: may this agent reach this tool, let reads and reversible writes through, check approval, take the budget
audit.py Audit record payloads and the hash chain that links them
store/ One contract, two backends: Postgres for production, SQLite for tests and the demo. Also seals the audit chain
metrics.py, otel.py Bounded-cardinality metrics behind a tag allowlist; OpenTelemetry transport
adapters/litellm_guardrail.py The gateway binding: reads identity from the key, blocks, propagates the idempotency key

Classification

Every tool is declared in tool_registry.yaml with an impact (read, write, destructive) and two more properties: reversible and external_side_effect. Anything irreversible or externally visible is budgeted as destructive, whatever it was declared as. Publishing a page or sending an external email deletes nothing and still cannot be taken back (ADR 0004).

A tool that is not in the registry is denied. Its blast radius is unknown, and registering it is a pull request, so the safe path is also the easy one.

Budgets

A destructive call is counted against every scope that applies, and the most restrictive one wins (ADR 0002). The denial names the scope, because that tells a responder whether to reset one run or look at a whole team.

Scope Bounds
agent_run a runaway loop inside one execution
actor one person's blast radius across runs
agent a bad deployment, across all its runs
team a last-resort ceiling
tool one especially sharp tool

Windows are exact and sliding, one row per action, which is affordable at tens of destructive actions per hour and wrong for a general rate limiter (ADR 0005). Recovery is an explicit, dual-controlled reset that moves a sequence watermark; it never deletes the evidence of what happened before (ADR 0006).

Storage

Postgres, not Redis: the gateway already runs a backed-up, highly available Postgres, and the hard part of this control is an atomic, multi-row reservation, which Postgres does natively (ADR 0003).

Table Holds
budget_scope one row per scope: the lock target that serialises reservations, and its reset watermark
action_event, action_event_scope one row per destructive action, and which scopes it counted against
budget_reset who requested and approved each reset, why, and when
approval_grant single-use grants, bound to an argument hash
audit_record, audit_chain_head, audit_seal the hash-chained audit log, its head, and its seals

Nothing is deleted. The runtime database role has no DELETE privilege on any table and can UPDATE only the four that legitimately change state. audit_record and budget_reset also carry triggers that refuse updates and deletes from every role, including the owner. Event and audit tables are partitioned by month and retired by detaching old partitions (ADR 0010, migrations/).

Concurrency

The gateway runs several replicas, so the dangerous case is many simultaneous calls each reading "under budget" before any of them has written. Every scope a call touches is locked in scope-key order before counting, which stops two reservations sharing two scopes from deadlocking. Counting happens after the call's own row exists, so the test is count > limit.

Measured on Postgres (benchmarks): 500 attempts from 64 threads against a limit of 25 admitted exactly 25. An uncontended decision takes about 2 ms at p50 with a connection pool; with 64 workers racing for the same budget, about 70 ms.

When dependencies fail

Fail behaviour is set per impact class, because one global answer is wrong in one direction or the other (ADR 0007, failure modes).

Dependency state read write destructive
Store unavailable allow allow deny
Audit write fails allow allow deny, and release the reservation
Metrics backend down allow allow allow

An unknown outcome, such as a timeout, is charged as executed, because assuming it did not happen is how a control meant to bound irreversible actions stops counting them. Where a tool records the idempotency key toolguard sends, a reconciliation step can release the slot on positive evidence that the action never landed (ADR 0009).

Observability

Personal data never reaches metrics: tag keys are checked against an allowlist that raises rather than drops, and audit records carry an argument hash rather than argument values. Request-level detail belongs in your tracing system; the audit log answers a different question — what was authorised, under which policy version — and is complete and append-only.

Only two monitors page: the control store being unavailable while destructive calls fail closed, and a destructive call ever being allowed while degraded, which can only be a defect. A blocked agent and an exhausted budget do not page, because a control working as designed is not an incident. infra/terraform asserts that split in tests, and the runbooks cover what to do.

Security

The full analysis is the threat model. In short:

  • The model is untrusted input. No model output is ever an authorisation; identity and policy come from the key.
  • Least privilege at three levels: an agent reaches only the MCP servers its policy names, approval-gated tools need a human, and the database role can insert but never delete.
  • Approvals are bound to the exact arguments, single-use and time-limited, and nobody can approve their own request. Resets need a permitted role, a reason and, under dual control, a second person.
  • The audit chain is tamper-evident, not tamper-proof. An operator with owner access could disable a trigger and re-chain history, so production should mirror records to a write-once store.

Deployment

Decisions

Decision
0001 Enforce at execution, not at proposal
0002 Several budget scopes at once, most restrictive wins
0003 Postgres, not Redis
0004 Impact is declared, and promoted by two properties
0005 Exact sliding window, one row per action
0006 Reset moves a sequence watermark, not a timestamp
0007 Fail behaviour is set per impact class
0008 Python, in-process, rather than Go in a sidecar
0009 Unknown outcomes are charged provisionally, then reconciled
0010 Partition monthly, retire by detaching, delete nothing