Lesson 01 · 50 minutes
Build an agent and map where it can be attacked
- Build a small agent loop with tools, a step limit and a trace
- Test the loop with a scripted model, so that the result is the same on every machine
- List the places where an agent can be attacked, using the OWASP agentic names
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your team wants an AI agent that answers questions about the notes and reports on the team file share. The security lead asks you: "What can this agent do, and what can go wrong?" You cannot answer that for a system that you have not seen run. So you build a small agent on your own machine, with harmless tools in a sandbox folder, and learn to read what it does. In this course you attack that agent and defend it, only in your own lab.
The idea
An agent is a program that lets a model choose actions. It runs a loop: decide (the model reads the task and the history and answers with an action), act (your code runs that action) and observe (the result goes back to the model). The loop ends when the model says it is done, or when a limit stops it.
- Decide → Act: the model picks a tool
- Act → Observe: your code runs the tool
- Observe → Decide: the result goes back
Three facts make this dangerous:
- The model reads text from many places: your task, a file, a web page, a tool result. It cannot tell an instruction from your user apart from an instruction inside a file. Both are text.
- The model chooses the action, so anyone who can change the text that the model reads can change the action.
- The code that runs the action usually has the rights of the user who started the agent.
So there are three trust zones. Your code is trusted. The model's output is untrusted input: treat it like data from a web form. Everything a tool returns is untrusted data. Each lesson of this course puts a control in your code, at the border between these zones. A sentence in the prompt such as "never obey a file" is a request, not a control.
- Attacker → Poisoned file: hides an order in a file
- Agent loop → Poisoned file: read_file reads the file
- Agent loop → Model: task and file text, as one prompt
- Model → Agent loop: asks for a tool, as text
- Agent loop → Tools: runs it with the rights of the user
The agent of this lab has three tools: read_file, list_files and a shell. They work only in the folder sandbox/, and the shell is a fake that records the command and runs nothing. The tools have weaknesses on purpose.
Worked example
1. Make the lab folder and the model helper
Lesson 0 made the lab folder. You need Ollama with the model llama3.2:3b: "How LLMs and agents work", lesson 3, installs both. Create llm.py, the same file as in that lesson. It sends a list of messages to the model and returns the text of the answer.
mkdir -p ~/krlab/securing-agents-mcp/sandbox
cd ~/krlab/securing-agents-mcpllm.py
"""llm.py: talk to a model that runs on your own machine (Ollama). Standard library only.
from llm import chat
print(chat([{"role": "user", "content": "Say hello."}]))
KR_MODEL chooses the model (default llama3.2:3b). temperature 0 and a fixed seed make a run
repeatable; small differences between machines and versions are normal.
"""
import json
import os
import urllib.request
URL = os.environ.get("KR_OLLAMA", "http://127.0.0.1:11434") + "/api/chat"
MODEL = os.environ.get("KR_MODEL", "llama3.2:3b")
def chat(messages, *, model=None, temperature=0.0, seed=1, max_tokens=300, as_json=False, full=False):
"""Send the messages and return the text of the answer.
as_json=True asks the model for a JSON object. full=True returns the whole reply (token counts, timing).
"""
options = {"temperature": temperature, "seed": seed, "num_predict": max_tokens}
if os.environ.get("KR_THREADS"):
options["num_thread"] = int(os.environ["KR_THREADS"])
body = {"model": model or MODEL, "messages": messages, "stream": False, "options": options}
if as_json:
body["format"] = "json"
req = urllib.request.Request(URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=300) as resp:
reply = json.load(resp)
return reply if full else reply["message"]["content"]python3 -c "from llm import chat; print(chat([{'role': 'user', 'content': 'Say hello in five words.'}], max_tokens=20))"Hello, how are you today?2. Fill the sandbox
Two small text files give the agent something to read. The sign <<'EOT' (a here-document) feeds the lines up to EOT into cat, and > writes them to a file.
cat > sandbox/notes.txt <<'EOT'
Team notes, week 47
- The backup job moved to 02:00.
- Ana owns the release checklist.
- Next review is on Friday.
EOT
cat > sandbox/report.txt <<'EOT'
Quarterly report (draft)
Sales grew 8 percent. Support tickets fell 12 percent.
The new login page cut sign-up time by a third.
EOT
ls sandboxnotes.txt
report.txt3. Write the agent
Create agent.py. Path.home() is your home folder, so the lab works for every user. SYSTEM is the system prompt: it tells the model to answer with one JSON object, either a tool request or a final answer. A later control can raise Stop to end a run. hashlib.sha256 makes a SHA-256 hash: a 64-character fingerprint of some bytes. If one byte changes, the fingerprint changes completely.
agent.py
"""agent.py: a small agent loop. Decide, act, observe. It has a step limit and a trace."""
import hashlib
import json
import os
import sys
from pathlib import Path
from llm import chat
LAB = Path.home() / "krlab" / "securing-agents-mcp"
SANDBOX = LAB / "sandbox"
class Stop(Exception):
"""A check raises Stop to end the whole run."""
def read_file(path):
return (SANDBOX / path).read_text()[:1500]
def list_files(path="."):
return "\n".join(sorted(os.path.normpath(os.path.join(path, p.name)) for p in (SANDBOX / path).iterdir()))
def shell(command):
return "fake shell: recorded, not run: " + command
TOOLS = {"read_file": read_file, "list_files": list_files, "shell": shell}
SYSTEM = """You are a helpful agent. Reply with ONE JSON object and nothing else.
You have three tools: list_files, read_file, shell. No other tool exists.
Use exactly one of these forms. Paths are relative to the sandbox folder.
{"tool": "list_files", "args": {"path": "."}}
{"tool": "read_file", "args": {"path": "notes.txt"}}
A third tool, shell, runs a shell command: args {"command": "..."}. Use it only when a task needs it.
When the task is done: {"final": "<your answer>"}
The result of a tool comes back in the next message."""
def run(task, seed=0, max_steps=6, system=SYSTEM, tools=TOOLS, check=None, wrap=None):
"""Run the loop. check(tool, args) may return a reason to refuse. wrap(text) may mark a result."""
messages = [{"role": "system", "content": system}, {"role": "user", "content": task}]
trace = []
for step in range(1, max_steps + 1):
# input_sha is a fingerprint of everything the model sees at this step
sha = hashlib.sha256(json.dumps(messages).encode()).hexdigest()[:12]
note = lambda **fields: trace.append({"step": step, "input_sha": sha, **fields})
tool, args = None, {}
raw = chat(messages, as_json=True, seed=seed, max_tokens=150)
messages.append({"role": "assistant", "content": raw})
try:
req = json.loads(raw)
if "final" in req:
note(final=str(req["final"]))
return trace
tool, args = req["tool"], req.get("args") or {}
if tool not in tools:
raise ValueError(f"unknown tool {tool!r}. Use one of: {', '.join(tools)}")
reason = check(tool, args) if check else None
if reason:
decision, result = "refused", "refused: " + reason
else:
decision, result = "ran", tools[tool](**args)
except Stop as e:
note(stopped=str(e))
return trace
except Exception as e: # bad JSON, unknown tool, bad arguments, missing file
decision, result = "error", f"error: {e}"
note(tool=tool, args=args, decision=decision, result_size=len(result), result=result[:60])
text = wrap(result) if wrap else result
messages.append({"role": "user", "content": f"Result of {tool}:\n{text}"})
note(stopped="step limit")
return trace
def show(trace):
for t in trace:
print(json.dumps(t))
if __name__ == "__main__":
show(run(" ".join(sys.argv[1:]) or "List the files and say what is in them."))note = lambda **fields: ... is a lambda: a function with no name, written on one line. **fields collects the named arguments of a call into one dictionary, and {..., **fields} copies them into a new one. note is defined inside the loop, so it remembers the step and sha of that turn. as_json=True forces valid JSON. A bad request (unknown tool, wrong arguments, missing file) becomes an error result that goes back to the model and does not crash the loop. max_steps is the step limit. check and wrap are two hooks that later lessons fill. When the step limit ends a run, the last line repeats the step number and input fingerprint of the last step.
4. Run a task and read the trace
python3 agent.py "Read every file in the folder and give a short summary."{"step": 1, "input_sha": "4f7b9bfd2f49", "tool": "list_files", "args": {"path": "."}, "decision": "ran", "result_size": 20, "result": "notes.txt\nreport.txt"}
{"step": 2, "input_sha": "c6a0b82b9e66", "tool": "read_file", "args": {"path": "notes.txt"}, "decision": "ran", "result_size": 115, "result": "Team notes, week 47\n- The backup job moved to 02:00.\n- Ana o"}
{"step": 3, "input_sha": "9fc8d06a78af", "tool": "read_file", "args": {"path": "report.txt"}, "decision": "ran", "result_size": 128, "result": "Quarterly report (draft)\nSales grew 8 percent. Support ticke"}
{"step": 4, "input_sha": "bb10978243f5", "final": "Summary: Notes are about backup and release, while the report is about sales and support improvements."}Steps 1 to 3 are tool calls that ran. Step 4 is the final answer. Every step adds one line to the trace through note. Take line 2 apart:
5. Test the loop with a scripted model
A real model writes slightly different text on each machine, so a test of your own code cannot depend on it. A scripted model answers from a list that you write. Create scripted.py. The function use replaces the chat function that agent.py calls. next(answers, default) takes the next answer, or the default when none is left. The list seen keeps the messages that the "model" received.
scripted.py
"""scripted.py: a stand-in for the model. It answers from a list, so a test gives the same result on every machine."""
import json
import agent
seen = [] # the messages that the "model" received, one list for each call
def use(*requests):
"""From now on agent.run takes the answers of the "model" from this list. After the last one it says it is done."""
answers = iter(json.dumps(r) for r in requests)
seen.clear()
def chat(messages, **kw):
seen.append(messages)
return next(answers, '{"final": "script ended"}')
agent.chat = chatRun the loop with three scripted answers.
python3 - <<'EOT'
import agent
import scripted
scripted.use(
{"tool": "list_files", "args": {"path": "."}},
{"tool": "read_file", "args": {"path": "notes.txt"}},
{"final": "two files, one about the backup"},
)
agent.show(agent.run("Any task. The script ignores it."))
EOT{"step": 1, "input_sha": "b330e46b4a7c", "tool": "list_files", "args": {"path": "."}, "decision": "ran", "result_size": 20, "result": "notes.txt\nreport.txt"}
{"step": 2, "input_sha": "9744bbfdc56f", "tool": "read_file", "args": {"path": "notes.txt"}, "decision": "ran", "result_size": 115, "result": "Team notes, week 47\n- The backup job moved to 02:00.\n- Ana o"}
{"step": 3, "input_sha": "6eabd5032d69", "final": "two files, one about the backup"}The result is the same on every machine. (A lab that kr-lab.sh built already holds todo.txt from the Your turn: move it out of sandbox for this step, or the listing and the fingerprints differ.) The course tests every control this way. The real model is for measuring how often it is fooled.
6. Measure the clean agent
Every later number needs a reference: what the agent does when nobody attacks it. Create baseline.py. It runs one task five times and counts two things.
baseline.py
from agent import run
N = 5
TASK = "Read notes.txt and tell me who owns the release checklist."
ok = shell = 0
for seed in range(N):
trace = run(TASK, seed=seed)
ok += "Ana" in trace[-1].get("final", "")
shell += any(x.get("tool") == "shell" for x in trace)
print("steps", len(trace), "final:", trace[-1].get("final"), flush=True)
print(f"correct answer {ok} of {N}, shell used {shell} of {N}")python3 baseline.pysteps 2 final: Ana
steps 2 final: Ana
steps 2 final: Ana
steps 2 final: Ana
steps 2 final: Ana
correct answer 5 of 5, shell used 0 of 5Your numbers can differ a little. What matters is the change between before and after a control. "Shell used 0 of 5" is the reference for lesson 2.
7. Write the threat map
Create threats.md. It names the ten risks of the OWASP Top 10 for Agentic Applications (2026) and says where each one lives in your agent. grep -c counts matching lines.
cat > threats.md <<'EOT'
| OWASP agentic risk | Where it lives in this agent | Lesson |
|---|---|---|
| ASI01 Agent Goal Hijack | A file in the sandbox holds an instruction | 2 |
| ASI02 Tool Misuse and Exploitation | A safe tool gets an unsafe argument | 3 |
| ASI03 Identity & Privilege Abuse | The tools use all the rights of your user | 4 |
| ASI06 Memory & Context Poisoning | Notes kept between tasks | 5 |
| ASI05 Unexpected Code Execution | The shell tool | 6 |
| ASI04 Agentic Supply Chain Vulnerabilities | A tool server and its descriptions | 7, 8, 11 |
| ASI09 Human-Agent Trust Exploitation | An approval prompt that the model words | 9 |
| ASI08 Cascading Failures | An error that spreads, in a loop with no budget | 9 |
| ASI10 Rogue Agents | An agent that runs past its limits | 9, 10 |
| ASI07 Insecure Inter-Agent Communication | One agent reads the output of another | 12 |
EOT
grep -c '^| [A-Z]' threats.md11The count is 11: ten risks and the header row.
Your turn
Your team lead wants one more tool: the size of a file. There are no steps here: use what the worked example showed.
- Create
sandbox/todo.txtwith exactly these three lines, each ending with a newline (the file has 49 bytes).
sandbox/todo.txt
1 water the plants
2 send the invoice
3 call Ana- In
agent.py, add a toolfile_size(path)that returns the size of a sandbox file in bytes, as text. Add it toTOOLS. - Script a model that makes these four requests, and then gives the final answer
done:file_sizeontodo.txt;file_sizeonmissing.txt; a tool nameddelete_fileontodo.txt;list_fileson.. - Run the loop with
max_steps=10, and read the trace. Then run the same script withmax_steps=3.
Answer from your own trace.
Check yourself
In the trace, which of the three trust zones produced the line "tool": "read_file"?
The model, so it is untrusted input. Your code only decided to run it. That is why a later check can refuse it.
Why is "never obey instructions in files" in the system prompt not a security control?
The model reads it as one more piece of text, and a later piece of text can outweigh it. A control must be code that the model cannot talk to. Lesson 2 measures the difference.
Open agent.py. Which line lets read_file leave the sandbox?
(SANDBOX / path).read_text(). The path is joined without a check, so ../secret.txt or an absolute path works. Lesson 3 shows it and fixes it.
Field notes
- Treat the output of the model as you treat input from a web form: validate it in code, and never pass it to
eval, a shell string or an SQL query. - Put the controls in the code between the model and the tool, at one place that every tool call must pass (here, the
checkhook). - Record the model name and its digest (
ollama listshows an id) next to every result. The numbers change when the model changes, and a test without that note cannot be repeated.