Fake tools and a sandbox with an effect log

Study time
≈ 2 h (estimate)
Needs
L3-M02-L03
Updated
2026-11-04

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L3-M02 · Duration: ~120 min (estimate, including the independent exercise) · Previous: L03 · Next: L05

1. Introduction

A read tool that goes wrong returns a wrong result; a write tool that goes wrong changes the world. To test an agent without causing real effects, the tool layer has to run in an isolated environment, and every effect has to leave a trail that can be checked: which call ran, what it changed, whether it changed things twice, whether something changed without being recorded.

This lesson builds a fake-tool (mock) layer with a sandbox and an effect log for ThuVien Mini (fictional): classifying tools by effect, an allowlist and a denylist, approval by a person, an idempotency key (which lets a request be repeated without further effect), rate and budget limits, a run with no effect (dry-run), and a function that reconciles the log with the real state. L3-M01-L01 already built the directory sandbox, L3-M01-L04 taught traces and L3-M01-L05 taught the permission map; this lesson adds measures that have tests. Everything is simulated: the book store and the loan table live in memory, the mailbox that sends notices is only a list, and nothing leaves the process.

2. Learning objectives

  1. Tell apart a mock tool, a sandbox and the three kinds of effect (read, write, external). Read: §4.1.
  2. Run the tool layer in real mode and in dry-run mode and read the effect log. Practice: §8.2, §8.3.
  3. Explain and check the idempotency key: repeating the same request, and the same key with different parameters. Practice: §8.3 (lines 3, 4 and 8), §8.4.
  4. Configure the allowlist and denylist, approval, rate limit and budget, then predict the result. Practice: §9.
  5. Use reconcile to detect a state change that did not go through the log, and state its limits. Practice: §8.3 (line 9).
  6. State what a simulated sandbox cannot replace. Read: §6.1.

3. Prerequisites and tools

  • L3-M02-L01 to L03, L3-M01-L01 (sandbox), L3-M01-L04 (traces, redaction), L3-M01-L05 (permission map and approval). The lab code is code-labs/l3-m02; it needs only pytest.
  • Separating the senses. A mock (fake tool) replaces a real tool with predefined behavior for testing; in the lab every tool is a mock. A sandbox is an isolated zone for effects; in the lab it is memory plus a temporary directory, which differs from an operating-system sandbox. An effect is a state change beyond the return value: read (changes nothing), write (changes state inside the sandbox), external (leaves the system; in the lab, a simulated mailbox). The effect log differs from the trace (L3-M01-L04): it records the call and the state before and after, not the span tree. An approval is a person's condition for one specific request. The budget and costs are counted in fake units (cu); the window of a rate limit ends with a tick command, with no real clock.
  • The earlier policy still stands: offline, fake tools or a sandbox. Lints and validators only flag; the loop guard and the limits lint block the run (fail closed); a person decides the thresholds, whether to accept a description change, and every real-world effect.

4. Concept explanation

4.1 Mock tool, sandbox and effect kind

A mock tool makes tests fast, deterministic and free of consequences; a sandbox makes sure that if a mock has a bug, the bug stays inside a small zone. The two are different: a mock protects nothing if it accidentally writes outside the temporary directory. The lab classifies tools by the effect field the author declares (L01): search_books, get_book and read_document are read; borrow_book and save_note are write; send_notice is external. The effect kind decides the measure: read also runs in dry-run, write and external do not; external always needs approval.

4.2 The order of the measures

ToolLayer.call checks in order: the tool does not exist (UNKNOWN_TOOL); the allowlist and denylist (DENIED; a deny wins, and a denied call does not have its parameters parsed); the parameter check (L03); approval for an external tool (APPROVAL_REQUIRED); the idempotency key (replay or conflict); the rate limit (RATE_LIMITED); the budget (BUDGET); dry-run; and finally the tool body. Every call, whatever the result, leaves one entry in the log with status rejected, denied, blocked, duplicate, dry_run, applied or failed.

Decision diagram of the tool layer: an unknown tool or invalid arguments give rejected; a tool that is not allowed or is denied gives denied; an external tool without approval, a key reused with different arguments, or exceeding the rate limit or budget gives blocked; a key already used with the same arguments gives duplicate; a dry run of a non-read tool gives dry_run; otherwise the tool runs and gives applied or failed.
Diagram: The order of the measures

The order has reasons: cheap, deterministic checks come first; approval comes after the parameter check so the approver only sees valid calls; replay comes before the limit so a repeat costs no resources; the budget comes last because the exact cost of the tool must be known.

4.3 What the documentation says

MCP's Tools page writes that, for trust and safety reasons, there should always be a person in the loop with the ability to deny a tool call; a server must validate all inputs, apply access control, rate-limit and sanitize output; a client should ask for confirmation on sensitive operations, show the input to a person before the call, set timeouts, and log tool use for auditing [R1]. The local server security page writes that a local MCP server is not a plugin running inside a sandbox the protocol provides but an ordinary operating-system process, and that the stdio channel is not a sandbox [R2]. OWASP's LLM06 page advises reducing the number of extensions, reducing the functionality and permissions of each, avoiding open-ended extensions (such as running shell commands) in favor of narrower ones, requiring a person to approve high-impact actions, and authorizing in the downstream system [R3].

The pages read have no section on idempotency keys (searching for "idempot" in the downloaded text of R1 and R3: no results), so the lab's key, dry-run and hash-chained log are the lab's design choices, not a recommendation of the sources.

5. Technical deep dive

5.1 The effect log and reconcile

EffectLog has only append, entries (returns a copy), verify and __len__: there is no function to edit or delete. Each entry has a sequence number, tool, status, code, effect kind, key, tick, a parameter hash (args_sha, SHA-256 cut to 12 hex characters and unsalted: it does not store the raw parameters but it also does not hide a value from a small set, such as a student id), the before and after state digests, and the hash of the previous entry. verify() detects direct edits to the private list; it detects, it does not prevent.

reconcile() returns a list of problems: a broken hash chain; the after of one entry differing from the before of the next (state changed outside the log); or the final state differing from the current state digest. The starting point is the state the tool layer saw at initialization. The digest covers only the loans table, the mailbox and the notes (snapshot); a change to layer.books is not seen. A tool body that "forgets to log" (edits layer.loans directly) is caught at the second or third check. reconcile only compares digests; it does not know whether an effect that was logged should have happened.

5.2 Idempotency key and dry-run

The key is inside the parameters (idempotency_key); the scope is the pair (tool name, key). Same key and same parameters (compared as normalized JSON): the earlier result is returned with status duplicate, cost 0, no further effect. Same key with different parameters: IDEMPOTENCY_CONFLICT. Only a successful call holds the key, so a failed request can be retried with the same key. Dry-run does not store keys, so in dry-run two identical borrow_book calls both log dry_run, with no duplicate. A new key is a new request: a second loan by the same student under a different key is stopped by the business rule LIMIT (one book per student), not by the idempotency mechanism.

For an external tool, "approval" is a set of keys: a person approves the key of one request (approved={"notice-s0042-fri"}); another key is still blocked. Approval is bound to the key, not to the content: the same approved key with different parameters still runs (test test_approval_is_bound_to_the_key_not_to_the_content). The lab does not check who approves.

5.3 Cost, budget and window

Each tool has a fake cost (cu): search_books, get_book, read_document 1; save_note and borrow_book 2; send_notice 3. A call rejected at the check step costs 1 cu if budget remains (so guessing tool names is not free); a call that enters the tool body and then fails (such as borrow_book with B999, failed) still costs the full 2 cu; a blocked call (denied, blocked) and a duplicate cost 0; dry-run charges the cost as if it ran for real, so the dry-run produces an equivalent bill. The test runs one scenario with every budget from 0 to 12 and asserts 0 <= spent <= budget. The rate limit counts one tool's calls within a window; tick() opens a new window.

6. The QA perspective

6.1 What a simulated tool layer cannot replace

  • A simulated sandbox is not an operating-system sandbox. The MCP page says stdio is not a sandbox and isolating a local server is the job of the host and the machine's operator [R2]; a mock tool in memory cannot measure that.
  • The log lives in memory; whoever controls the process controls it. The hash chain only means something if someone keeps the final hash elsewhere; reconcile only compares digests, not intent.
  • reconcile does not see layer.books. The set of approved keys does not say who approved, and is tied to the key, not the content; args_sha is unsalted so it does not hide a value from a small set; idempotency holds only within one process and one thread, so races (two calls at the same moment) have not been tried.
  • Dry-run runs read tools for real, so if a read tool leaks data, the dry-run leaks it too. The mailbox is a simulation; nothing has been tried against a real mail service.
  • The limits (a budget of 30 cu, the window, the costs) are lab choices; a person decides the real numbers. Time is a logical counter and does not measure latency.
  • A static test scans the lab's source code with a syntax tree, looking for network modules, processes, and eval, exec, open; it is a proxy: it allows pathlib (which can write or delete files anywhere) and does not see a module imported from a string at run time.

6.2 Tests for the tool layer

  1. One log entry per call, including rejected, blocked or nonexistent ones; the log contains no raw parameters.
  2. Dry-run does not change state but still logs and charges cost.
  3. Repeating the same key runs once; the same key with different parameters conflicts; a failed call does not hold the key.
  4. A deny wins over an allow; a denied call is not parsed; an external tool needs exactly the approved key.
  5. The rate limit counts per window and tick resets it; spent never exceeds budget.
  6. reconcile is empty after a normal run and not empty after a change outside the log.
  7. Files are written only inside the sandbox directory; there is no primitive that runs a real command in the source code. A person decides whether to widen a tool's permissions.

7. Real-world scenarios

Scenario 1 (fictional): "Retry after a timeout". The ThuVien Mini agent (fictional) calls borrow_book, the connection is flaky, so it repeats the same request. With the same key loan-s0042-b003, the second call returns duplicate and the loan table has one row (§8.2, the real run). If the agent generates a new key for each attempt, this mechanism no longer helps; the LIMIT rule is what stops the second loan, and that is why the key must be derived from the user's request, not from the attempt.

Scenario 2 (fictional): "The bill of a dry-run". The team runs a six-call scenario in dry-run to estimate cost. The real run costs 6 cu and the dry-run 8 cu, because in dry-run the repeated loan is not recognized as duplicate (the key is not stored) and so is charged twice. The right conclusion: dry-run shows the plan and the effect kinds, not the exact cost when there are repeated calls.

8. Hands-on tutorial

8.1 Setup

cd academy-content/code-labs/l3-m02
python3 -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest            # 73 passed

8.2 Run the demo

python -m lab.demo l04

Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-04; the two versions give identical output). Every tool and the mailbox are simulated:

A. real run
   get_book: status=applied code=None cost=1
   borrow_book: status=applied code=None cost=2
   borrow_book: status=duplicate code=None cost=0
   save_note: status=applied code=None cost=2
   send_notice: status=blocked code=APPROVAL_REQUIRED cost=0
   nope: status=rejected code=UNKNOWN_TOOL cost=1
   spent=6 loans=1 notes=['memo'] reconcile=[]
A. dry run
   get_book: status=applied code=None cost=1
   borrow_book: status=dry_run code=None cost=2
   borrow_book: status=dry_run code=None cost=2
   save_note: status=dry_run code=None cost=2
   send_notice: status=blocked code=APPROVAL_REQUIRED cost=0
   nope: status=rejected code=UNKNOWN_TOOL cost=1
   spent=8 loans=0 notes=[] reconcile=[]
B. effect log of a second real run, with send_notice approved by key notice-s0042-fri
   1 get_book applied changed=False key=None
   2 borrow_book applied changed=True key=loan-s0042-b003
   3 borrow_book duplicate changed=False key=loan-s0042-b003
   4 save_note applied changed=True key=None
   5 send_notice applied changed=True key=notice-s0042-fri
   6 <unknown> rejected changed=False key=None
C. a state change that bypassed the log
   reconcile=['final state differs from the log']
D. rate limit 2 per window for get_book
   None None RATE_LIMITED | tick | None

Reading the output: part A compares the real run with the dry-run on the same six calls (costs 6 and 8 cu; the dry-run does not change state); part B prints the log of a second real run, this time with send_notice approved by its key; part C edits loans directly and reconcile reports that the final state differs from the log; part D shows the limit window opening again after tick.

8.3 Try it yourself

Save it as try_l04.py in the lab's root directory (next to lab/, not inside lab/), run python try_l04.py, then delete the file:

import tempfile

from lab.toollayer import ToolLayer

borrow = '{"book_id": "B003", "student_id": "S0042", "idempotency_key": "loan-s0042-b003"}'
with tempfile.TemporaryDirectory() as root:
    layer = ToolLayer(root, budget=6, rate_limit={"get_book": 1})
    for name, raw in [("get_book", '{"book_id": "B003"}'), ("get_book", '{"book_id": "B001"}'), ("borrow_book", borrow), ("borrow_book", borrow),
                      ("save_note", '{"name": "memo", "text": "hi"}'), ("save_note", '{"name": "memo2", "text": "hi"}')]:
        r = layer.call(name, raw)
        print(name, r["status"], r["code"], layer.remaining())
    print([e["status"] for e in layer.log.entries()], layer.reconcile())
    print(layer.call("borrow_book", borrow.replace("B003", "B005"))["code"], layer.reconcile())
    layer.loans.clear()
    print(layer.reconcile())

Output (Python 3.14.6 and 3.12.14 identical):

get_book applied None 5
get_book blocked RATE_LIMITED 5
borrow_book applied None 3
borrow_book duplicate None 3
save_note applied None 1
save_note blocked BUDGET 1
['applied', 'blocked', 'applied', 'duplicate', 'applied', 'blocked'] []
IDEMPOTENCY_CONFLICT []
['final state differs from the log']

Reading: line 1: the first call runs, 5 budget left. Line 2: the second get_book gets RATE_LIMITED because the limit is one per window, and costs nothing. Lines 3 and 4: borrow_book runs, then duplicate (3 left). Lines 5 and 6: save_note runs (1 left), the next one gets BUDGET. Line 7: the statuses in order, and reconcile is empty. Line 8: the same key with a different book gets IDEMPOTENCY_CONFLICT and the log still matches. Line 9: after clearing the loan table directly, reconcile reports that the final state differs from the log.

8.4 Run the lesson's tests

python -m pytest tests/test_l04_toollayer.py -v

Result: 16 passed. Read test_idempotency_key_makes_a_repeated_write_run_once, test_reconcile_notices_a_state_change_that_bypassed_the_log and test_files_are_written_only_inside_the_sandbox_folder. The tests use pytest's temporary directory.

8.5 Troubleshooting

Symptom Cause Fix
send_notice is always APPROVAL_REQUIRED The request's key is not in approved Add the request's exact key; another key is still blocked
A repeated call does not give duplicate You are in dry-run, or the first attempt failed Run for real; only a successful call holds the key

9. Independent exercise

Problem: A ten-step scenario (with one tick step) for ThuVien Mini. Choose a tool layer configuration so the scenario gives a predetermined result, and predict the log of a dry-run.

Requirements: complete exercises/test_l04_toollayer.py:

  1. TODO 1: LIMITS: a dict of parameters for ToolLayer (some of budget, allow, deny, rate_limit, approved; no dry_run) such that when the scenario runs: no call ends in BUDGET, exactly two calls end in RATE_LIMITED, exactly one call in DENIED, the send_notice call is applied, there is exactly one loan, the note todo holds the second text, and layer.reconcile() == [].
  2. TODO 2: DRY_STATUSES: the list of statuses in the log, in call order (not counting tick), when the scenario runs on ToolLayer(budget=9, dry_run=True) with no other configuration.

Test data: exercises/ex_script.json.

Deliverable: the two variables above, in the file exercises/test_l04_toollayer.py itself.

Acceptance criteria: python -m pytest exercises/test_l04_toollayer.py passes (2 tests), recomputed with lab.toollayer. The tests do not check that the values you chose make sense for a real product.

Hints: TODO 1: go through the scenario step by step in the check order of §4.2 and add up the costs; the window changes only at the tick step; a blocked tool does not run, so it does not change state. TODO 2: for each call, ask its effect kind, then ask what dry-run does with it and what happens to a repeated call.

10. Knowledge check

0/16 done · Results are kept in this browser only.

P02 · True or false

A ToolLayer has deny={"save_note"}. Calling save_note with broken argument text (not JSON) still returns BAD_JSON, because the tool layer parses the arguments before considering the deny list.

P04 · Select all that apply

Select every correct statement about the made-up cost (cu) in the lab's ToolLayer.

P05 · Put in order

Order the steps that ToolLayer.call checks for a call, from the step done first to the step done last.

  1. The tool body runs
  2. Dry-run simulates a non-read tool
  3. Rate limit (RATE_LIMITED)
  4. Allow and deny lists (DENIED)
  5. Idempotency key: replay (duplicate) or conflict (IDEMPOTENCY_CONFLICT)
  6. The arguments are valid per L03's check chain
  7. An external tool has been approved for the call's key (APPROVAL_REQUIRED)
  8. Does the tool exist (UNKNOWN_TOOL)
  9. Budget (BUDGET)

P06 · Match

Match each status in the effect log with the situation that produces it.

P07 · Spot the bug

A colleague reimplemented the idempotency-key replay for a write tool. The function has one bug that makes a failed request impossible to retry. Find it.

def call_write(store, key, args, run):
    if key in store:
        if store[key]["args"] != args:
            return {"ok": False, "code": "IDEMPOTENCY_CONFLICT"}
        return store[key]["result"]
    result = run(args)
    store[key] = {"args": args, "result": result}
    return result

P08 · Short answer

A scenario of six calls (search for a book, borrow B002 for S0007 with the key loan-s0007-b002, repeat exactly that borrow call, save_note memo, save_note memo again without a key, read_document rules.txt) costs 8 cu when run for real and 10 cu when run in dry-run. Explain the difference and what conclusion to draw about dry-run.

P09 · Essay

Write 5-8 sentences (fictional): in the lab, the reviewer approves send_notice by adding the key notice-s0007-mon to the approved set. Explain what "approval is bound to the key, not the content" means, a situation in which it causes harm, and how you propose to fix it.

P11 · Recall

Lesson: L3-M01-L04

According to L3-M01-L04, what does the lab's trace record, and what is the "time" in it?

P12 · Recall

Lesson: L3-M01-L05

According to L3-M01-L05, for a tool with which permission does the architecture map's validator accept approval: none_sandbox_only (together with sandboxed: true)?

P13 · Multiple choice

The key notice-s0007-mon is in approved, and the reviewer read the message "Book due Monday". The model sends send_notice with exactly that key but the content "Meet me at the gate", the first call to use this key. What is the result?

P14 · Select all that apply

Select every change that reconcile() or log.verify() detects in the lab.

P15 · Fill in the blank

ToolLayer(root, budget=4, approved={"notice-s0007-mon"}) runs three valid calls in order: save_note, then send_notice with the key notice-s0007-mon, then get_book. The send_notice call returns the code ___, and the final remaining() is ___ cu.

P16 · True or false

In dry-run mode, two identical borrow_book calls (same key, same arguments) give the statuses dry_run and then duplicate.

11. Summary

  • Concepts: a mock tool differs from a sandbox; three effect kinds; an append-only effect log; idempotency; approval by key [R1][R3].
  • Skills: configuring allow/deny, approval, limits and budget; running a dry-run; reading the log; using reconcile.
  • Traps: treating a simulated sandbox like an operating-system sandbox [R2]; generating a new idempotency key for each attempt; trusting a dry-run for exact cost; treating the log hash as tamper-proof.
  • You can now: take a write tool and ask: which effect kind does it have, who approves, what happens on repeat, which effects leave a trail, and who chose the limit numbers.

12. References

ID Title Publisher URL Accessed Relevance
R1 Tools (MCP specification, revision 2026-07-28) Model Context Protocol https://modelcontextprotocol.io/specification/2026-07-28/server/tools 2026-11-04 Read the page text, to the end: person in the loop, Security Considerations
R2 Local Server Security (MCP documentation) Model Context Protocol https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/local-server-security 2026-11-04 Read the page text up to the end of the threats section; did not read the mitigations after it, so they are not used in this lesson
R3 LLM06:2025 Excessive Agency (OWASP Gen AI Security Project) OWASP https://genai.owasp.org/llmrisk/llm062025-excessive-agency/ 2026-11-04 Read the page text up to mitigation 7; did not read the rest

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Mock tool Tool giả: thay tool thật bằng hành vi định sẵn để test
Effect (read, write, external) Tác động: thay đổi trạng thái ngoài giá trị trả về; ba loại
Effect log Nhật ký tác động: ghi mỗi lời gọi cùng trạng thái trước và sau; chỉ ghi thêm
Idempotency key Khóa idempotency: lặp lại cùng yêu cầu không tác động thêm
Dry-run Chạy thử không tác động: chạy tool đọc, giả lập tool ghi
Approval Duyệt: điều kiện của người cho một yêu cầu cụ thể (theo khóa)