Programmatic Context Management
Keep raw tool results outside the prompt, compute bounded views in code, and query the original records when the question changes.
Put computation before the model
A log dump costs attention. When a tool returns a full incident export, the next model call pays to read every stack trace, even if the agent only needs a count and a single failing request. Summarizing it still requires that first read. Programmatic context management moves filtering and aggregation ahead of the model boundary: the runtime keeps the raw result and returns a small, computed view with source references.
Context Engineering for Autonomous Agents describes budgeting for agent loops; here the question is how bytes cross the model boundary. Context compaction handles the growing chat history, while MCP and A2A cover how agents connect to tools and each other. None of those operations requires dumping each tool result into the prompt.
Separate the session from its current view
Session state holds user messages, tool arguments, raw results and computed values, while the model sees only the view built for its next call. A variable can hold an entire parsed export without its contents appearing in the prompt; showing its name, schema and source address lets the model request code to run over it.
Scroll makes this distinction explicit in its system design. Its append-only Event Log retains original events and payload references; a sandboxed persistent Python kernel holds typed variables across calls. Only printed projections enter the working view. When old spans leave that view, an eviction index retains landmarks tied to exact log addresses.
Durable logs preserve recorded bytes; the kernel holds mutable objects that later code can change or delete, and a kernel failure can lose those objects even when the log survives. Reading a recorded tool response does not imply that replaying a payment, deployment or other side effect is safe. Computed values need source references and the version of the code that produced them if the app must rebuild them.
Anthropic’s MCP example uses code to filter spreadsheet rows before returning selected rows to the model. Tool results stay in the runtime unless explicitly logged or returned, so the client decides whether raw results cross the model boundary even though MCP supplies the connection.
Trace a log result through the runtime
Consider a request to investigate slow checkout responses. The downloadable standard-library example embeds synthetic request logs and runs with python3 context_projection.py. Its JSON output reports an eight-record JSONL artifact of 5,954 bytes, including repeated stack frames to represent a bulky tool response.
With a raw tool response, the model receives those records, including the stack frames, and must count slow requests itself. A projected response leaves the bytes in RAW, unchanged and named by their SHA-256 hash, while code parses each record, checks the service and duration, updates the counts, and keeps only the first matching samples. Memory use for samples stays bounded.
After downloading the file, run this calling path:
from context_projection import SOURCE, encode_view, project, recover
wrong_view = project(level="ERROR")
print(encode_view(wrong_view).decode("utf-8"))
model_view = project() # All checkout completion levels.
print(encode_view(model_view).decode("utf-8"))
# A follow-up asks about a request omitted from the first sample.
expanded_view = project(limit=3)
request_ref = expanded_view["samples"][2]
original = recover(SOURCE, request_ref["line"])
print(encode_view(original).decode("utf-8"))
A corrected model view is 422 encoded UTF-8 bytes and includes the artifact hash alongside the full filter and threshold. It reports seven matching checkout completions, five slow requests, and two sample records with source line numbers; omitted_slow is three. The model can report the count without reading every trace, but cannot claim the sample contains all slow requests.
Counts cover the whole matching fixture. Samples follow source order, so the first examples may miss a different failure later in the export; the count remains correct even when those examples are unhelpful. The size measurement covers compact JSON only, excluding tool wrappers and chat history. Each encoded view has a 2,048-byte ceiling, alongside sample and message limits; oversize output fails before any JSON crosses the model boundary.
A wrong projection produces a wrong answer
An error-only filter looks plausible. The first call finds one checkout completion and no slow requests, which could tempt the model to conclude that checkout latency looks normal because it cannot see the successful requests that took too long. That conclusion is wrong: the slow requests completed after retries and were logged at INFO. The filter discarded the relevant evidence.
Keeping the query in the returned view makes this mistake visible. Zero slow requests among error-level completions supports only that narrow statement; it says nothing about successful completions. Removing the level filter changes the derived view without replacing the artifact or fetching the logs again.
A follow-up asks, “What happened to request r3?” Raising the sample limit reveals its source line; recover resolves the same artifact hash and line to the original record. Its message says the payment upstream timed out before a retry succeeded, which supports looking into that service. A completion message alone cannot establish the incident’s root cause.
Across these calls, the runtime moved through raw bytes, an error-only view, a corrected view, and an expanded record while retaining the same source artifact. Write Outside the Window provides storage, and Select, Don’t Dump supplies the selection principle; executable projection lets the agent change a filter without losing the source.
Make recovery survive the runtime
In this example, the artifact stays in memory. An app needs durable storage and a compact list of artifact handles with schemas and capture scopes, otherwise a later model call cannot discover what remains available after the kernel restarts. Store the original tool arguments, capture time, environment and capture status beside each artifact; exact counts over a partial export remain partial evidence.
Resolve references through access-checked handles: a hash identifies bytes but grants no access, so both projection and later expansion must recheck the user’s tenant and resource scope. Keep original logs read-only, redact sensitive fields before exposure, and treat log messages as untrusted data even after filtering.
Fixed Python functions implement this example; it neither accepts supplied code nor provides isolation. If the model can author projection programs, the app must enforce sandbox capabilities and wall-clock timeouts outside those programs, with memory and output limits. Disable ambient credentials and unrestricted network or filesystem access. Preserve the artifact when execution fails, and return a bounded error with its handle, so a failed computation does not force the next attempt to repeat the original tool operation.