Week 2: Advanced context engineering
Learning objectives
By the end of this week, you can:
- LO2: choose, order and check context for a coding-agent task, and design a small MCP-style tool whose name, schema and errors guide a model toward a safe call.
- LO3: turn a project proposal into executable acceptance cases, including a case that must fail, and use the cases to connect research, a plan, implementation and verification.
Every example below has a generate step and a verify step. The examples are course-authored and synthetic; they are not claims about a product or a benchmark.
Minimal example
One constraint, four places to lose it
Suppose a proposal says: “A report may read reports/, but it must never write there.”
A direct request to an agent—“add CSV export”—does not say where the rule came from or
how to check it. The constraint can disappear in four transitions:
- Research: the agent reads an old README but not the current permission test.
- Plan: the plan says “add export” and drops the read-only boundary.
- Implement: the tool schema exposes
pathwith no allowed-root description. - Verify: the test checks that a CSV exists but never attempts a write to
reports/.
Generate: write a one-paragraph plan for the export request. Verify: underline the constraint, its source, the implementation boundary and the negative test (a test that tries the forbidden action). If one is missing, the plan is incomplete, even when the generated code looks plausible.
Research, plan, implement
Use three short artifacts rather than one unbounded prompt:
| Phase | Question | Artifact that can be checked |
|---|---|---|
| Research | What is true at this revision? | Evidence table with paths, symbols and unknowns |
| Plan | What small change would satisfy the request? | Ordered steps, boundaries and acceptance cases |
| Implement | What code expresses that plan? | Patch plus the commands that exercise each case |
Generate: for the synthetic export request, make an evidence table with two rows naming
the export handler and its rejection test. Mark an unknown explicitly rather than guessing.
Verify: the export request is invented, so there is no file to open yet. For now,
every “confirmed” in your table becomes “cannot tell”. In the studio, the handler is the
export_result function in week02-studio/check_cases.py. Its rejection test is the
forbidden case in the same file. Check your two rows against that file then. In your own
project, open the file that each row names, at the revision you are working on. Change
“confirmed” to “cannot tell” when the source does not show the claim. A plan is more
useful when a reader can disagree with one row and run one check.
A specification that can fail
Write acceptance cases as observable input and output. The following cases are deliberately small:
Given an export root called out/
When the request names out/summary.csv and rows are valid
Then the file is created and the command reports exported
Given the same root
When the request names reports/summary.csv
Then no file is written and the command reports refused: read-only root
Given the same root
When a row is missing its id
Then no file is written and the command reports invalid row: id
Generate: implement the smallest function that could satisfy the three cases.
Verify: run the positive case and each negative case against a fresh temporary
directory. A specification that only says “export works” cannot reveal a missing
refusal or a partial write. The studio's first checker runs only the first two cases,
and it compares only the returned text. Your own checker must observe that no file is
written, and it must cover the row without id.
The project proposal due this week asks for less than this. Its form asks for the core scenario, a scope boundary and your first observable acceptance case. The three to five cases you write in the studio go further. Keep them with the proposal. They are the first draft of the requirements table in the technical specification due in week 4. If research shows that a case is not observable, revise it.
Context packets and compaction
A context window is a working budget. Tool output, repeated reads and failed attempts consume it; a later request can then miss the one constraint that mattered. With the saved session recording and dissection, you can inspect this effect without making a model call. The course-written compaction script shows it on one hand-written session. It reads the session file beside it, so run it from its own folder:
(cd lectures/week-03/fixture && python compaction.py full)
(cd lectures/week-03/fixture && python compaction.py auto)
full keeps all 19 messages, reports "check": "passed" and exits 0. auto clears the
older tool results. In doing so it loses the line that says not to edit view.py. It
then reports "check": "failed" and exits 1. No model is called in either run.
Generate: before shortening a history, write a handoff with the task, the source of each constraint, the current file state, the last failed check, what is still unknown and the next action. Verify: compare each line with the recorded messages, then rerun the check on the current revision. A summary that says “tests passed” without the tested revision is not evidence.
Try it on the session above. --show prints the recorded messages before the result. Save
your handoff as handoff.txt at the top of the course checkout, then restart from it alone:
(cd lectures/week-03/fixture && python compaction.py full --show)
(cd lectures/week-03/fixture && python compaction.py fresh ../../../handoff.txt)
fresh gives the course-written policy only two things: the task and your handoff. The
policy is not a model. It looks for a line that names view.py and says not to change it.
It also looks for a line that mentions strip and a failure. The run reports
"check": "passed" only when your handoff contains both lines. If you leave either out,
the check fails. Keep the handoff within 600 bytes. The script does not run a longer file.
It prints the file size and the limit instead.
When most entries are stale or contradictory, restart with a written handoff and reread the next files. Compacting is a choice about information, not a guarantee that the model will remember the right information.
Tool design for a model reader
A model sees a tool's name, description, input schema and returned message. Treat these as a contract, not decoration. A small example:
{
"name": "export_report",
"description": "Write a CSV below out/; never writes reports/.",
"inputSchema": {
"type": "object",
"additionalProperties": false,
"required": ["path", "rows"],
"properties": {
"path": {"type": "string", "pattern": "^out/[A-Za-z0-9_.-]+\\.csv$"},
"rows": {"type": "array", "items": {"type": "object"}}
}
}
}
Generate: propose a call for out/summary.csv and one for reports/summary.csv.
Verify: validate both against the schema and run the handler. The first should reach
the handler. The second should produce a short error that says how to fix the call, and it
should not touch any file. The studio gives you a stub that runs both calls, plus a third
call with an unknown field. It stands in for a schema validator: it reads the required
fields and the allowed names from the JSON and checks the path with a rule of its own.
Use five design checks:
- Name: use a verb and an object, so the model can pick the intended action.
- Description: state the allowed root and the important exclusion.
- Schema: make required fields, types, closed properties and simple patterns machine-checkable.
- Errors: identify the bad field and the next repair; never return a traceback.
- Result: return the observation the next decision needs, including refusal and partial-failure states.
MCP is the name of a protocol family. It connects a model application with tools and resources. The protocol does not make a vague tool safe: the handler still enforces its boundary, and the controller still has to pass the result back to the model. Read the interface as a model would read it, then test the behavior with calls.
A2 applies these five checks to a real local server. You start from the starter code linked on that page and run its protocol check. Then you register the server with your coding agent and record three real trials:
- selection: the agent must pick the right tool;
- arguments: a valid call and an invalid call;
- recovery: the agent recovers from an error.
The schema you tighten in the studio is practice for that work. It is not the A2 hand-in.
Reading a production agent's instructions
The factsheet readings compare two open-source files, each pinned to one fixed version. Select one rule about plans, one about a tool schema and one about stopping. For each, write four labels: what the text asks the model to do, what code checks, what the runtime checks and what remains unknown. For example, a description can ask for three lines of context, while the tool code enforces only a single-match rule. Keep those two claims separate. A pinned file shows one fixed version, so do not draw conclusions about current releases from it.
Hands-on exercise
The studio is an individual 75-minute pass over your own project proposal. You will write three to five acceptance cases that can fail, then tighten one small tool schema and error message. Keep the before/after schema and every command result. The Week 1 fixture and session are still stored in this folder, so you can inspect them.
Verification
Use this order:
- Check each research claim against the file and revision named in the evidence table.
- Validate every acceptance case once on a fresh temporary directory, including its expected failure.
- Validate the revised schema with a valid call, an invalid call and an unknown field.
- Record the command, exit status, observed output and the decision to accept, narrow, recheck or stop.
Common mistakes
- Prompt first, evidence later: search the relevant files and record unknowns before asking for an implementation.
- A plan with no rejection: add a malformed or forbidden input whose expected result is an observable refusal.
- A schema that accepts everything: close the object and constrain paths, enums or bounds that the handler relies on.
- An error that only says “invalid”: name the field and a repair, then test that the model receives the message.
- Confusing a generated answer with verification: rerun the acceptance case after the last write. Keep the failed result and the tested revision.
- Treating a protocol name as enforcement: identify the handler and runtime checks; mark anything else as unknown.
- Compacting away the rule: keep the task, constraint source, current file state, last failed check, remaining unknown and next action in the handoff.