# AI engineer: model your agent on the Trust Canvas

> Start from the code of a tool-using agent, let the scan draw a first graph, draw the zones, tools and data it cannot see, read the boundaries, chains and chokepoints, and see what two approvals change.

Source: https://keryn.dev/docs/journeys/trust-canvas/

**Goal.** Take a tool-using agent you are building, draw what can reach what, and let the engine tell you which edges an attacker can chain and which single guard breaks the most chains.

**Time.** 35 minutes. **You are** an engineer who writes the agent and has to explain to a reviewer where it is safe to give it authority.

**You need.** The Keryn CLI ([install](https://keryn.dev/docs/start/install/)), `git`, `jq`, and a browser for the canvas. The Trust Canvas is in Keryn Web 0.5.0 and later (`#/trust`). The screenshots on this page come from a local build of the 0.5.0 release commit, and `keryn trust-graph` is in the CLI built from that source (0.5.0, 0.5.1 and 0.5.2 were released as the web sites only, so there is no installable binary yet).

> **Leaves your machine**
> **Nothing.** The canvas engine runs in the tab as WebAssembly. The model you open is read locally and is not uploaded. Saving writes a file on your machine.

## 1. The agent

A trip planner. A traveller chats with it, it can read a travel page the traveller points at, book a trip and mail an itinerary, and it picks which of those to do. The files are written for this page. Make the directory and write them.

```python
from fastapi import FastAPI
from pydantic import BaseModel

from trip.agent import plan

app = FastAPI()

class Chat(BaseModel):
    message: str

@app.post("/chat")
def chat(body: Chat) -> dict:
    return {"reply": plan(body.message)}
```

```python
import smtplib
import sqlite3
import urllib.request
from email.message import EmailMessage

def search_pages(url: str) -> str:
    """Read a travel page the user pointed at."""
    with urllib.request.urlopen(url, timeout=10) as resp:
        return resp.read().decode("utf-8", "replace")[:20000]

def book_trip(destination: str, traveller: str) -> int:
    """Create a booking and return its id."""
    db = sqlite3.connect("bookings.db")
    cur = db.execute("INSERT INTO bookings (destination, traveller) VALUES (?, ?)", (destination, traveller))
    db.commit()
    return cur.lastrowid

def send_itinerary(to: str, body: str) -> None:
    """Mail the itinerary to an address."""
    msg = EmailMessage()
    msg["To"], msg["From"], msg["Subject"] = to, "trips@example.invalid", "Your itinerary"
    msg.set_content(body)
    with smtplib.SMTP("localhost") as smtp:
        smtp.send_message(msg)
```

```python
import json
import os

from openai import OpenAI

from trip import tools

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

TOOLS = {"search_pages": tools.search_pages, "book_trip": tools.book_trip, "send_itinerary": tools.send_itinerary}

def plan(message: str) -> str:
    messages = [
        {"role": "system", "content": "You plan trips. Use the tools when the traveller asks."},
        {"role": "user", "content": message},
    ]
    for _ in range(5):
        reply = client.chat.completions.create(model="gpt-4o", messages=messages, tools=[
            {"type": "function", "function": {"name": n, "parameters": {"type": "object"}}} for n in TOOLS
        ])
        choice = reply.choices[0].message
        if not choice.tool_calls:
            return choice.content
        for call in choice.tool_calls:
            result = TOOLS[call.function.name](**json.loads(call.function.arguments))
            messages.append({"role": "tool", "tool_call_id": call.id, "content": str(result)})
    return "I could not finish planning."
```

The agent also uses a calendar through an MCP server, which the repository's client configuration names:

```json
{
  "mcpServers": {
    "calendar": { "command": "npx", "args": ["-y", "@example/calendar-mcp"] }
  }
}
```

```text
fastapi==0.115.0
openai==1.40.0
```

```sh
touch trip/__init__.py
git add -A
git commit -q -m "trip planner agent"
```

## 2. What the code already says

```sh
keryn scan . --verbose
```

```text
Keryn — Policy blocked (Hold); dependency advisories not checked (offline)
  1 violation(s)/finding(s) at or above 'error'
  dependency advisories not checked (offline): 1 lockfile(s); keryn scan --online checks them
Analysis: complete · Dependency advisories: not checked (offline) · Policy: blocked · Approval: not recorded
base not recorded → analyzed d23b7fb1ecb5e4c897c8d64a79111082431ffc51
Comparison: not compared: no finding baseline supplied
Cases: 3 current = 0 new + 0 existing + 3 unclassified; unknown cleared from previous assessment
Newly blocking: unknown (no complete base run to compare with)
Cases: 3 of 3 shown (limit 20); 0 omitted by display limit
  [blocking; unclassified] MCP server is launched through npx/bunx with a package that has no pinned @version (or uses @latest). Every start downloads whatever the registry serves, so a hijacked or typosquatted release runs with your credentials. Pin an exact version, for example @scope/pkg@1.2.3.
    .mcp.json:3 · pattern · 1 contributing rule(s) · sha256:9123e3fa2f1674fe8380599e58e93d99e3cfd45c4f0d9e5e20ed008ba4c153cc
    Pattern match [proof 1]
  [review; unclassified] Claude and Claude Code: MCP client configuration. This shows the tool is set up in this repository; it does not show which code the tool wrote.
    .mcp.json:1 · inventory · 1 contributing rule(s) · sha256:48806ed4d9f1729ba4c27c29433365af83403104c137b83506eb8f42426b0e05
    Inventory [proof 0]
  [review; unclassified] A URL taken straight from a function parameter (typically a tool argument the model fills) is fetched from inside the service, so the model can point the service at internal endpoints or the instance metadata service. Resolve the host and check it against an allowlist before fetching; a well-formedness check is not a destination check.
    trip/tools.py:9 · path-in-file · 3 contributing rule(s) · sha256:f8650b57c1d6949d98c06e85a749754e663e0b8cf4727acacb88c1046413df81
    Within-file flow [proof 2]
Accounting: 15 recorded rule hits; 12 non-case observations; 0 suppressed rule hits; 1 failed checks
Exceptions: 0 expired suppression entries; changes since the base unknown (no base run with its exceptions)
Coverage · source patterns: scanned 6 files; 1598/1598 requested rules; 0 skipped; 0 excluded
Coverage · dataflow: executed; see the recorded cross-file analysis scope
Coverage · dependency advisories: not checked (offline); 1 lockfile(s) (keryn scan --online checks them, sending package names and versions only)
Coverage · known-fix matching: executed; see recorded known-fix scope
  Limitation: Semgrep-compatible SUBSET: no join, no metavariable-pattern/comparison, no cross-file or type inference, no language equivalences/constant propagation; taint is an approximation.
  Limitation: Structural matching uses the bundled language grammars, including Ruby. Unsupported rule/language combinations are listed in coverage; generic text also supports regex rules.
  Limitation: Parity is only claimed where proven by differential tests against native Semgrep CE (results: https://keryn.dev/evals/semgrep-ce/).
  Limitation: Deliberate divergence: each language is matched with its own grammar. Semgrep CE reuses the JavaScript parse of a pattern for every language of a rule that lists javascript, so its Python side never matches keyword arguments, dict literals or eval/require there (reported as a rule warning).
  Limitation: 2 package licences unknown: their lockfiles record none. keryn scan --online looks them up on deps.dev, sending package names and versions only.
  Limitation: 1 lockfile not checked against vulnerability advisories (offline). keryn scan --online checks them, sending package names and versions only.
  Limitation: Maintainer/install-hook transition not checked without --base evidence; a lockfile alone does not record authenticated maintainer history.
  Limitation: 2 npm and PyPI packages checked against the shipped malicious-package table (OSV MAL records) and the popularity list; additional ecosystem signals depend on the available data and package contents.
  Limitation: Malicious-package data: PyPI; source date <time>; shipped. Published MAL records are not proof that unlisted packages are safe.
Exit code: 1
counts: 15 rule matches · 15 findings · 12 excluding AI-BOM inventory · 1 blocking before answers
rules: 1,598 rules available · 1,598 supported · 818 applied to the 6 scanned files
errors: 0 confirmed errors · 1 unconfirmed (pattern match only)
warnings: 1 confirmed warning · 0 unconfirmed (pattern match only)
pattern findings: 1 confirmed by cross-file analysis
```

The inventory lists the SDK, the model and the calendar server: the **nodes** an edge model attaches to. The one finding at `error` is on an edge. The calendar server is started with `npx -y` and no pinned version, so whatever that name resolves to tomorrow runs with the agent's authority. That is a `depends on` edge into your supply chain. The warnings are on `search_pages`, which fetches a URL the model chose.

Ask the CLI what the repository declares about MCP servers:

```sh
keryn mcp servers . | jq -c '.servers[] | {name, transport: .attributes.transport, target: .attributes.target}'
```

```text
{"name":"calendar","transport":"stdio","target":"npx -y @example/calendar-mcp"}
```

A scan finds components and some paths. It does not know that your route is public, that `book_trip` spends money, or that the person on the other end is untrusted. You know those, and the canvas is where you say them. First, though, let the scan draw what it can.

## 3. Derive the graph from the scan

`keryn trust-graph` scans the directory like `keryn scan` (the full rule library, no Deep) and turns what it found into a trust graph: public routes with an internet user in front, each model call site, its providers, tools with their authority, MCP servers, secrets by kind and place, prompt files and data stores. `--analyze` also runs the trust-model engine on it. Nothing is sent anywhere.

```sh
keryn trust-graph . --analyze --out keryn-out/trust-graph.json
```

```text
wrote trust graph -> keryn-out/trust-graph.json
wrote trust analysis -> keryn-out/trust-graph.analysis.json
```

Two files: the graph, which the canvas opens, and the engine's analysis of it. Read the graph with `jq`:

```sh
jq -r '.nodes[] | [.kind, .label, .provenance.basis] | @tsv' keryn-out/trust-graph.json
```

```text
actor.end_user	User prompt	inferred
agent.orchestrator	trip/agent.py agent (OpenAI SDK)	inferred
ai.llm_provider	OpenAI	structured
external.mcp_server	calendar	structured
external.service	Claude and Claude Code (AI coding tool)	structured
```

Every element says how it is known. The OpenAI provider and the calendar server are `structured`: read from the AI-BOM and from `.mcp.json`. The agent and the user entry are `inferred`. Edges first:

```sh
jq -r '.edges[] | [.relation, .provenance.basis, (.provenance.sources | join(","))] | @tsv' keryn-out/trust-graph.json
```

```text
sends	inferred	aibom
calls	inferred	mcp-config
reaches	inferred	agent-surface
```

All three edges are `inferred`, which the canvas draws dashed and which count as weak: a path through one costs more when the engine searches for paths. The scan did not find the `/chat` route, because the route lives in `server.py` and the model call in `agent.py`, and it matched routes to calls within one file. So there is no route, no tools and no database, and the entry is a generic "User prompt". The tools are in `tools.py` and are chosen by name from a dictionary, which is exactly the kind of thing a syntax-tree reader cannot follow. The graph is a start, and it says so.

What it did see is worth reading:

```sh
jq -c '.summary' keryn-out/trust-graph.analysis.json
jq -r '.risks[] | "\(.severity)\t\(.title)"' keryn-out/trust-graph.analysis.json
```

```text
{"nodes":5,"edges":3,"boundaries":3,"unevidencedBoundaries":3,"chains":1,"unguardedChains":1,"risks":{"high":2,"low":1,"medium":2},"truncated":false,"edgesByBasis":{"inferred":3},"weakEdges":3}
high	User-controlled content becomes model-visible without prompt isolation
medium	Trust boundary crossed with no control or evidence
high	User prompt can reach a consequential edge with nothing on the chain
medium	MCP server is not pinned to a version
low	3 trust boundaries rest only on inferred links
```

The calendar server is not pinned (`keryn.trust.mcp-server-unpinned`), which is the `error` finding from step 2 seen as a risk on an element. The user prompt reaches that server through the agent, so there is a chain, and all three boundaries rest only on inferred links (`keryn.trust.boundary-inferred-only`, one risk for the whole graph). The engine identifies two edges where an enforced denial would block the only potentially reachable chain.

```sh
jq -r '.fixFirst[].why' keryn-out/trust-graph.analysis.json
```

```text
An enforced denial on calls trip/agent.py agent (OpenAI SDK) to calendar would block 1 of 1 potentially reachable chains.
An enforced denial on reaches User prompt to trip/agent.py agent (OpenAI SDK) would block 1 of 1 potentially reachable chains.
```

![The Trust Canvas after "Open on trust canvas" on a scanned repository: a User prompt entry, an agent, the OpenAI provider and an unpinned MCP server, joined by dashed edges because each is inferred rather than read from the code.](https://keryn.dev/screens/trust-canvas-scan-1280-light.webp)

*The same graph in Keryn Web, from Open on trust canvas on the repository's zip. The dashed edges are the inferred ones. Taken from keryn.app main-DIcUUbkq.js.*

## 4. Draw the rest of the model

The derived graph knows what the code says. This model adds what only you know. Zones are groups with a trust level, elements live in zones, and an edge has one of eight verbs and says what rides on it. This is the trip planner as a model file. It holds what you know and the scanner does not: who sends text in, which tools exist, what each can change, and where the model sits.

```json
{
  "schemaVersion": "0.1.0", "id": "tm_trip_planner", "kind": "threat_model_graph", "title": "Trip planner agent",
  "groups": [
    {"id": "public", "kind": "zone.public", "label": "Public internet", "bounds": {"x": 0, "y": 0, "width": 260, "height": 420}},
    {"id": "runtime", "kind": "zone.application", "label": "Agent runtime", "bounds": {"x": 300, "y": 0, "width": 260, "height": 560}},
    {"id": "data", "kind": "zone.data_platform", "label": "Data", "bounds": {"x": 600, "y": 0, "width": 260, "height": 200}},
    {"id": "external", "kind": "zone.external_providers", "label": "External services", "bounds": {"x": 900, "y": 0, "width": 260, "height": 420}}
  ],
  "nodes": [
    {"id": "traveller", "type": "block", "kind": "actor.internet_user", "label": "Traveller", "parentId": "public", "position": {"x": 20, "y": 40}},
    {"id": "pages", "type": "block", "kind": "external.service", "label": "Travel web pages", "parentId": "public", "position": {"x": 20, "y": 260}},
    {"id": "chat", "type": "block", "kind": "app.route", "label": "POST /chat", "parentId": "runtime", "position": {"x": 320, "y": 40}},
    {"id": "agent", "type": "block", "kind": "agent.orchestrator", "label": "Trip agent", "parentId": "runtime", "position": {"x": 320, "y": 170}},
    {"id": "search", "type": "block", "kind": "agent.tool", "label": "search_pages", "parentId": "runtime", "position": {"x": 320, "y": 300}, "security": {"toolAuthority": "read"}},
    {"id": "book", "type": "block", "kind": "agent.tool", "label": "book_trip", "parentId": "runtime", "position": {"x": 320, "y": 400}, "security": {"toolAuthority": "execute"}},
    {"id": "bookings", "type": "block", "kind": "data.relational_db", "label": "Bookings database", "parentId": "data", "position": {"x": 620, "y": 40}},
    {"id": "model", "type": "block", "kind": "ai.llm_provider", "label": "Model provider", "parentId": "external", "position": {"x": 920, "y": 40}},
    {"id": "mail", "type": "block", "kind": "external.service", "label": "Email service", "parentId": "external", "position": {"x": 920, "y": 260}}
  ],
  "edges": [
    {"id": "e1", "type": "flow", "kind": "flow.user_input", "relation": "sends", "source": {"nodeId": "traveller"}, "target": {"nodeId": "chat"}, "security": {"userControlled": true}},
    {"id": "e2", "type": "flow", "kind": "ai.prompt_payload", "relation": "sends", "source": {"nodeId": "chat"}, "target": {"nodeId": "agent"}, "security": {"modelVisible": true, "userControlled": true}},
    {"id": "e3", "type": "flow", "kind": "ai.model_request", "relation": "calls", "source": {"nodeId": "agent"}, "target": {"nodeId": "model"}, "security": {"modelVisible": true}},
    {"id": "e4", "type": "flow", "kind": "agent.tool_call", "relation": "calls", "source": {"nodeId": "agent"}, "target": {"nodeId": "search"}},
    {"id": "e5", "type": "flow", "kind": "ai.retrieved_context", "relation": "sends", "source": {"nodeId": "pages"}, "target": {"nodeId": "search"}, "security": {"userControlled": true, "modelVisible": true}},
    {"id": "e9", "type": "flow", "kind": "ai.retrieved_context", "relation": "sends", "source": {"nodeId": "search"}, "target": {"nodeId": "agent"}, "security": {"userControlled": true, "modelVisible": true}},
    {"id": "e6", "type": "flow", "kind": "agent.tool_call", "relation": "calls", "source": {"nodeId": "agent"}, "target": {"nodeId": "book"}, "security": {"stateChanging": true}},
    {"id": "e7", "type": "flow", "kind": "flow.data_write", "relation": "writes", "source": {"nodeId": "book"}, "target": {"nodeId": "bookings"}, "security": {"stateChanging": true}},
    {"id": "e8", "type": "flow", "kind": "flow.external_send", "relation": "sends", "source": {"nodeId": "agent"}, "target": {"nodeId": "mail"}, "security": {"stateChanging": true}}
  ],
  "risks": []
}
```

How the file encodes it:

- `Traveller` and `Travel web pages` sit in the untrusted `Public internet` zone. Text from either can reach the model.
- `book_trip` has `toolAuthority: execute`, and the edges that change state say `stateChanging`.
- `search_pages` returns page text to the agent (`e9`), user-controlled and model-visible. That one edge is how a page the traveller never wrote can steer the agent.

**Web**

Open the canvas at `#/trust` in Keryn Web, choose **Open** (the folder icon in the top bar) and pick `keryn-out/trust-graph.json` to see what the scan drew, then `trip-planner.threat-model.json` for the full model. You can also skip the CLI: scan the repository's zip in Keryn Web and choose **Open on trust canvas** in the results, which builds the same kind of graph in the tab. Keryn Web matches routes to model calls within one file too, so for this repository it sees no more than the CLI did.

![The Trust Canvas with the trip-planner agent, on the Unguarded chains lens: trust zones as groups, elements inside them, red edges that carry chains labelled with a verb and "fix here", boundary shields, and the findings drawer listing what to fix first.](https://keryn.dev/screens/trust-canvas-1280-light.webp)

*The trip planner on the Trust Canvas. Shields mark edges that cross a trust boundary, thick edges are chokepoints, and the drawer lists what to fix first. Taken from keryn.app main-DIcUUbkq.js.*

**CLI**

The CLI does not draw. It writes the inputs a model is built from (`keryn scan . --json result.json`, `keryn mcp servers .`). The model file is plain JSON, so it can be checked in next to the code and diffed in review:

```sh
jq -r '.title, (.nodes | length), (.edges | length)' trip-planner.threat-model.json
```

```text
Trip planner agent
9
9
```

## 5. Read what the engine found

With only the drawing, the engine reports 5 trust boundaries, 5 of them without evidence, and 6 chains from untrusted input to a consequential edge with nothing on them. It lists 14 risks: 8 critical, 3 high and 3 medium. These numbers were read from the canvas when this page's screenshots were taken, and the same file in the same build gives the same numbers. The canvas opens on the Unguarded chains lens, which draws only those chains in red and fades the rest.

Chain: Traveller sends (across a trust boundary), POST /chat sends (chokepoint), Trip agent calls, book_trip writes (across a trust boundary), Bookings database. One of the chains the engine lists. It starts untrusted and ends on a write.

Three things to read in the drawer.

1. **Chains.** There are two untrusted starts, the traveller and the travel pages (the public zone is untrusted), and three consequences, the booking, the database write and the email: six chains. The traveller's reach the agent through the route, and the pages' reach it through `search_pages`, which never touches the route.
2. **Fix first.** The drawer ranks the edges whose guard breaks the most chains. The top entries are "4 chains Trip agent calls book_trip" and "3 chains POST /chat sends Trip agent", each with a sentence that says how many of the six it breaks. The agent is on all six chains, which is the arithmetic behind "guard here first". But a guard in front of the model, such as input checking on the route, does not stop a prompt-injected tool call that happens behind it. That is why the `Travel web pages` edge matters: page text enters behind your input check.
3. **Risks.** Two say a state-changing tool action lacks an approval requirement, and point at the booking call and the email send. Three say user-controlled text reaches the model without prompt isolation: the route, the page text going into the tool and the tool's result going to the agent.

The canvas does not say the agent is unsafe. It says which edges have nothing recorded on them. [The reference](https://keryn.dev/docs/reference/trust-canvas/) explains each rule.

## 6. Add the guards you actually have

Record that booking and sending mail need a person to approve. In the canvas, select the edge and tick **Requires approval**. On the file, which is how you would keep it in a pull request:

```sh
jq '(.edges[] | select(.id == "e6" or .id == "e8") | .security.approvalRequired) = true' trip-planner.threat-model.json > guarded.threat-model.json
jq -c '[.edges[] | select(.security.approvalRequired) | .id]' guarded.threat-model.json
```

```text
["e6","e8"]
```

Open the guarded file. The chains chip now reads 0 unguarded and 6 guarded, and the risks fall from 14 to 6: 3 high and 3 medium remain. The chains are guarded, not removed. A chain is broken at an edge with an approval, and an approval is a claim until you attach evidence for it, such as the code that enforces it. The five boundaries still have nothing recorded on them, and the high risks are about user-controlled text reaching the model without isolation, which an approval on a later edge does not touch.

Diagram: trip agent calls book_trip, across a approval. With an approval on the edge, the chain is broken here. It is not shown to be safe.

> **Note: In the next release**
> Before you build the guards, you can price them. **Plan fixes** in the top bar lists a proposed guard for every edge that would break an unguarded chain, takes your minimum and maximum engineer-days for each and a capacity, and proposes which to build first, with the chains it would cover and the ones that remain. It is arithmetic over your estimates, not a risk ranking. See [Plan fixes](https://keryn.dev/docs/guides/trust-canvas/#plan-fixes).

## 7. Make the guard true in the code

An approval on the canvas is a statement. Make it true in the repository, then record on the edge what enforces it (a file, a test, a review) so the next reader can open it. The pattern is the one from [the AppSec journey](https://keryn.dev/docs/journeys/appsec/): the model names a tool, and code you control decides whether that tool may run without a person. Scan again after the change. A scan that stops reporting an unguarded edge is evidence worth attaching.

## What you just proved

- **What a scan can draw by itself, and where it stops**: the provider, the MCP server and an unpinned-server risk, each marked as read from the code or inferred, and not the route and tools that live in other files.
- **The edges that matter in this agent**: a public route into the agent, a tool that reads untrusted pages, and two tools that change the world. Not a list of components but a list of who can make what happen.
- **Where the chokepoints are**, as arithmetic about your drawing, with the edges shown so you can disagree.
- **That a guard in front of the model is not enough.** The page the tool reads enters behind it.
- **What two approvals change, and what they do not.** The risks fall. The boundaries and the injection risks stay until you record controls and evidence for them.

What this does not show: that the model file matches the running system. A model derived from a scan is only as complete as the scan (the one in step 3 missed the route and the tools), and one you draw is only as true as you make it. Chains are searched within bounds, and the analysis says when a bound was hit.

## Next

- Learn the vocabulary in full: [the Trust Canvas guide](https://keryn.dev/docs/guides/trust-canvas/), [the reference](https://keryn.dev/docs/reference/trust-canvas/) and [the eight edge kinds](https://keryn.dev/docs/edges/edge-kinds/).
- Gate the code side in CI: [Platform and CI](https://keryn.dev/docs/journeys/ci/).
- Ask a model for a second opinion on findings, within bounds and under your decision: [agentic triage](https://keryn.dev/docs/edges/agentic-triage/).
