graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Pass caller-owned turn context to computer tools
justrach200b21dcf443
diff --git a/docs/adr/0119-computer-tools-receive-caller-context.md b/docs/adr/0119-computer-tools-receive-caller-context.mdnew file mode 100644index 00000000..359ec650--- /dev/null+++ b/docs/adr/0119-computer-tools-receive-caller-context.md@@ -0,0 +1,29 @@+# 0119. Computer tools receive caller-owned turn context++Status: accepted 2026-09-15++## Context++The computer-use MCP adapter requires session and turn correlation metadata+before browser selection. Plain tool arguments cannot supply that request+context, so the initial browser entry fails even when the tool is loaded.++## Decision++Each agent owns opaque session and turn identifiers. Begin a new turn ID at+`runTurn`, retain the session ID for that agent, and copy the context through+`ToolCtx` into MCP dispatch. The IDs are independent of account information,+saved-session names and model arguments. Concurrent callers do not mutate a+shared registry-level context.++Attach the required `x-codex-turn-metadata` request field only for the+`cua_repl` and `node_repl` adapters. Keep ordinary MCP requests unchanged.+The adapter's authentication, permissions and action review remain intact.++## Consequences++Browser selection can initialize through the installed adapter. The+`computer-tool-turn-context` behavior regression checks real MCP dispatch,+stability within a turn, and rotation on the next user turn. Unit coverage+also verifies that model arguments cannot replace host metadata and that+unrelated servers receive none of it.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 429735ae..7db59a4b 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -126,6 +126,7 @@ record only when you need the evidence or the edge cases.| [0113](0113-clipboard-errors-need-evidence.md) | Direct AppKit clipboard failures need typed evidence; generic helper failures never imply Automation permission. || [0114](0114-live-citations-are-terminal-presentation.md) | Live terminal citations use per-stream display filters with independent reasoning state; structured JSON/ACP output stays unchanged. || [0116](0116-informational-turns-have-bounded-scope.md) | Summary turns gather bounded evidence; coding completion requirements apply to requested changes. |+| [0119](0119-computer-tools-receive-caller-context.md) | Computer-use MCP requests receive opaque caller-owned session and turn context. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex b10aab47..f8871873 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -92,3 +92,4 @@{"id": "informational-mixed-request-keeps-mutation", "why": "#884: a mixed fix-and-summary request must still read, apply the root-cause change, and verify in the fixture project.", "prompt": "Fix slug.py so whitespace-only labels return an empty string, add a regression test, run the project tests, and summarize the change.", "workspace_seed": {"slug.py": "def slug(label):\n result = \"-\".join(label.strip().lower().split())\n if not result:\n raise ValueError(\"empty label\")\n return result\n", "test_slug.py": "import unittest\nfrom slug import slug\n\nclass SlugTests(unittest.TestCase):\n def test_words(self):\n self.assertEqual(slug(\"Hello World\"), \"hello-world\")\n", "README.md": "Run tests with python3 -m unittest discover.\n"}, "script": [{"tool": "read_file", "arguments": {"path": "slug.py"}}, {"tool": "read_file", "arguments": {"path": "test_slug.py"}}, {"tool": "read_file", "arguments": {"path": "README.md"}}, {"tool": "edit_file", "arguments": {"path": "slug.py", "old_string": " if not result:\n raise ValueError(\"empty label\")\n", "new_string": ""}}, {"tool": "edit_file", "arguments": {"path": "test_slug.py", "old_string": "import unittest\nfrom slug import slug\n\nclass SlugTests(unittest.TestCase):\n def test_words(self):\n self.assertEqual(slug(\"Hello World\"), \"hello-world\")\n", "new_string": "import unittest\nfrom slug import slug\n\nclass SlugTests(unittest.TestCase):\n def test_words(self):\n self.assertEqual(slug(\"Hello World\"), \"hello-world\")\n\n def test_whitespace_only(self):\n self.assertEqual(slug(\" \\t\\n \"), \"\")\n"}}, {"tool": "bash", "arguments": {"command": "python3 -m unittest discover"}}, {"text": "Whitespace-only labels now return an empty string. Both project tests passed."}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "read_file"}, "count": 3}}, {"events_at_least": {"match": {"type": "tool_call", "name": "edit_file"}, "count": 2}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 0}}, {"request_contains": {"index": -1, "text": "Ran 2 tests"}}, {"request_contains": {"index": -1, "text": "OK"}}, {"request_lacks": {"index": -1, "text": "Summary scope checkpoint:"}}, {"final_text_contains": "Both project tests passed."}]}{"id": "internal-budget-note-keeps-wire-clean", "why": "#912: internal budget reminders must remain effective without exposing saved notification metadata on the model wire.", "args": ["--max-model-calls", "2"], "prompt": "Read the checklist and summarize its current state.", "script": [{"tool": "todo_read", "arguments": {}}, {"text": "The checklist is empty."}], "assert": [{"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "Read the checklist and summarize its current state."}}, {"request_lacks": {"index": -1, "text": "_graff_origin"}}, {"final_text_contains": "The checklist is empty."}]}{"id": "cli-outside-path-recovers-through-shell", "why": "#902/#903: a missing PATH lookup must prompt executable discovery instead of declaring the CLI absent or abandoning the shell workflow.", "env": {"PATH": "/usr/bin:/bin"}, "prompt": "Use the installed fixture CLI to file the local test issue and verify its receipt.", "workspace_seed": {"bin/graff_fixture_cli": "#!/bin/sh\n[ \"$1 $2\" = \"issue create\" ] || exit 2\nprintf \"FILED_LOCALLY\\n\" > \"$HOME/issue-receipt.txt\"\nprintf \"CLI_OPERATION_COMPLETE\\n\"\n"}, "script": [{"tool": "bash", "arguments": {"command": "chmod +x \"$HOME/bin/graff_fixture_cli\""}}, {"tool": "bash", "arguments": {"command": "graff_fixture_cli issue create --title \"Fixture issue\""}}, {"tool": "bash", "arguments": {"command": "if [ -x \"$HOME/bin/graff_fixture_cli\" ]; then \"$HOME/bin/graff_fixture_cli\" issue create --title \"Fixture issue\"; fi"}}, {"tool": "bash", "arguments": {"command": "test -s \"$HOME/issue-receipt.txt\" && cat \"$HOME/issue-receipt.txt\""}}, {"text": "The CLI operation completed."}], "assert": [{"request_contains": {"index": 2, "text": "[CLI lookup]"}}, {"request_contains": {"index": 2, "text": "does not prove the executable is absent"}}, {"request_contains": {"index": -1, "text": "CLI_OPERATION_COMPLETE"}}, {"events_at_least": {"match": {"type": "tool_call", "name": "bash"}, "count": 4}}, {"events_at_most": {"match": {"type": "tool_call"}, "count": 4}}, {"final_text_contains": "The CLI operation completed."}, {"request_contains": {"index": -1, "text": "FILED_LOCALLY"}}]}+{"id": "computer-tool-turn-context", "why": "Computer-use MCP calls require stable caller session and turn context, with a new turn identifier on the next user turn.", "env": {"GRAFF_MCP_SCHEMA_BUDGET": "0", "GRAFF_MCP_PROBE": "0", "GRAFF_LEARN_AUTO": "off"}, "workspace_seed": {".mcp.json": "{\"mcpServers\": {\"cua_repl\": {\"command\": \"python3\", \"args\": [\"context_mcp.py\"]}}}", "context_mcp.py": "import json, sys\nfirst = None\ncalls = 0\nfor line in sys.stdin:\n r = json.loads(line)\n if 'id' not in r: continue\n method = r.get('method')\n if method == 'initialize':\n result = {'protocolVersion':'2025-06-18','capabilities':{'tools':{}},'serverInfo':{'name':'fixture','version':'1'}}\n elif method == 'tools/list':\n result = {'tools':[{'name':'js','description':'Check caller context','inputSchema':{'type':'object','properties':{'code':{'type':'string'}}}}]}\n elif method == 'tools/call':\n calls += 1\n meta = r['params'].get('_meta', {}).get('x-codex-turn-metadata', {})\n if isinstance(meta, str): meta = json.loads(meta)\n valid = all(isinstance(meta.get(key), str) and meta[key] for key in ('session_id','turn_id'))\n if calls == 1:\n first = meta\n valid = valid\n elif calls == 2: valid = valid and meta == first\n else: valid = valid and meta['session_id'] == first.get('session_id') and meta['turn_id'] != first.get('turn_id')\n text = ('initial context received' if calls == 1 else 'same-turn context preserved' if calls == 2 else 'next-turn context rotated') if valid else 'context missing or incorrectly scoped'\n result = {'content':[{'type':'text','text':text}], 'isError':not valid}\n else: result = {}\n print(json.dumps({'jsonrpc':'2.0','id':r['id'],'result':result}),flush=True)\n"}, "prompt": "Load the context-check tool and call it twice.", "second_prompt": "Call the context-check tool once more.", "script": [{"tool": "load_tool_schemas", "arguments": {"server": "cua_repl"}}, {"tool": "mcp__cua_repl__js", "arguments": {"code": "first"}}, {"tool": "mcp__cua_repl__js", "arguments": {"code": "same"}}, {"text": "Both calls completed."}, {"tool": "mcp__cua_repl__js", "arguments": {"code": "next"}}, {"text": "Context verified."}], "assert": [{"request_contains": {"index": 2, "text": "initial context received"}}, {"request_contains": {"index": 3, "text": "same-turn context preserved"}}, {"request_contains": {"index": 5, "text": "next-turn context rotated"}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "mcp__cua_repl__js", "is_error": true}, "count": 0}}]}diff --git a/src/agent.zig b/src/agent.zigindex 8ef2e7c4..a96517e2 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -114,6 +114,7 @@ pub const Agent = struct {/// process mode (engine_sink.forAgent); set to inject a custom frontend.sink: ?@import("engine_sink.zig").EngineSink = null,registry: ?*mcp.Registry = null,+ mcp_context: @import("mcp_turn_context.zig").State = .{},approvals: ?*approvals_mod.Approvals = null, // shared bash-approval state, set by main()tracer: ?*trace.Tracer = null, // shared JSONL event trace, set by main()run_budget: ?*run_budget_mod.RunBudget = null, // shared invocation-wide call/concurrency ceiling@@ -333,6 +334,7 @@ pub const Agent = struct {try self.ensureRootTools(self.provider.kind);var pending_work: empty_completion.PendingWork = .{};self.completed = null;+ self.mcp_context.begin(self.io);@import("named_work.zig").beginTurn(self);var task_scope = @import("task_intent.zig").State.begin(self);if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) @import("cancel_source.zig").clear();diff --git a/src/agent_argstream.zig b/src/agent_argstream.zigindex 4fdb6694..238431d2 100644--- a/src/agent_argstream.zig+++ b/src/agent_argstream.zig@@ -46,6 +46,7 @@ fn toolCtx(self: *Agent) tools_mod.ToolCtx {.provider = self.provider,.subagent_provider = self.subagent_provider,.subagent_cross_provider = self.subagent_cross_provider,+ .mcp_context = self.mcp_context.value,.registry = if (self.sub) null else self.registry,.from_sub = self.sub,.has_eval = self.eval_cmd != null,diff --git a/src/agent_eval.zig b/src/agent_eval.zigindex e7bb03ad..1b497386 100644--- a/src/agent_eval.zig+++ b/src/agent_eval.zig@@ -348,6 +348,7 @@ pub fn runJudge(self: *Agent, rubric: []const u8, eval_output: []const u8, note:.provider = self.provider,.subagent_provider = self.subagent_provider,.subagent_cross_provider = self.subagent_cross_provider,+ .mcp_context = self.mcp_context.value,.registry = if (self.sub) null else self.registry,.from_sub = self.sub,.has_eval = self.eval_cmd != null,diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 04ab4b70..dd236b97 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -137,6 +137,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {.provider = self.provider,.subagent_provider = self.subagent_provider,.subagent_cross_provider = self.subagent_cross_provider,+ .mcp_context = self.mcp_context.value,.registry = self.registry, // workers get licensed codedb-pro reads too (#627).from_sub = self.sub,.has_eval = self.eval_cmd != null,diff --git a/src/exec.zig b/src/exec.zigindex 4948c966..2eae89ff 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -178,7 +178,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {return failure(gpa, err);};defer prepared.deinit(gpa);- const r = reg.call(gpa, call.name, prepared.value) catch |err| {+ const r = reg.callWithContext(gpa, call.name, prepared.value, ctx.mcp_context) catch |err| {codedbpro_report.onFailure(ctx, call.name, @errorName(err));return failure(gpa, err);};diff --git a/src/main.zig b/src/main.zigindex 34c349fb..f0318a3b 100644--- a/src/main.zig+++ b/src/main.zig@@ -596,5 +596,5 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("subagent_recovery.zig");_ = @import("acp_agent_activity.zig");_ = @import("read_image.zig");- _ = .{ @import("mcp_names.zig"), @import("workspace_history.zig") };+ _ = .{ @import("mcp_names.zig"), @import("workspace_history.zig"), @import("mcp_turn_context.zig") };}diff --git a/src/mcp.zig b/src/mcp.zigindex 61731e2b..1b8269ad 100644--- a/src/mcp.zig+++ b/src/mcp.zig@@ -472,23 +472,19 @@ pub const Registry = struct {/// Invoke a tool by its qualified name. `input` is the model-supplied/// argument object. Returns result text (caller-owned, allocated with/// `out_alloc`) and whether the server reported an error.- pub fn call(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value) !struct { text: []u8, is_error: bool } {+ const CallResult = struct { text: []u8, is_error: bool };+ pub fn call(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value) !CallResult {+ return reg.callWithContext(out_alloc, qualified, input, null);+ }+ pub fn callWithContext(reg: *Registry, out_alloc: Allocator, qualified: []const u8, input: Value, context: ?@import("mcp_turn_context.zig").Snapshot) !CallResult {const tool = for (reg.tools) |t| {if (std.mem.eql(u8, t.qualified_name, qualified)) break t;} else return .{ .text = try out_alloc.dupe(u8, "unknown MCP tool"), .is_error = true };const server = reg.servers[tool.server_index];- // Build the tools/call params: {"name":..., "arguments":{...}}.- var pw: Io.Writer.Allocating = .init(reg.gpa);- defer pw.deinit();- var s: std.json.Stringify = .{ .writer = &pw.writer };- try s.beginObject();- try s.objectField("name");- try s.write(tool.original_name);- try s.objectField("arguments");- try s.write(input);- try s.endObject();+ const params = try @import("mcp_turn_context.zig").params(reg.gpa, server.name, tool.original_name, input, context);+ defer reg.gpa.free(params);reg.mutex.lockUncancelable(reg.io);defer reg.mutex.unlock(reg.io);@@ -499,9 +495,9 @@ pub const Registry = struct {defer response_arena_state.deinit();const response_alloc = response_arena_state.allocator();if (!server.initialized) try initializeServer(server, response_alloc, reg.arena(), null);- server.elicit_source = pw.writer.buffered();+ server.elicit_source = params;defer server.elicit_source = "";- const resp = request(server, response_alloc, pw.writer.buffered(), "tools/call", tool.original_name) catch |err| switch (err) {+ const resp = request(server, response_alloc, params, "tools/call", tool.original_name) catch |err| switch (err) {// Streamable HTTP servers use 404 to expire a session. Re-run the// MCP handshake once, then retry the call without the stale ID.// A modern-era server never carries a session id in the first@@ -512,7 +508,7 @@ pub const Registry = struct {error.McpSessionExpired => retry: {if (server.era != .legacy) return err;try initializeServer(server, response_alloc, reg.arena(), null);- break :retry try request(server, response_alloc, pw.writer.buffered(), "tools/call", tool.original_name);+ break :retry try request(server, response_alloc, params, "tools/call", tool.original_name);},else => return err,};diff --git a/src/mcp_turn_context.zig b/src/mcp_turn_context.zignew file mode 100644index 00000000..faa2d0cb--- /dev/null+++ b/src/mcp_turn_context.zig@@ -0,0 +1,88 @@+//! Opaque caller-owned correlation IDs for the computer-use MCP bridge.+const std = @import("std");+const Allocator = std.mem.Allocator;+pub const Snapshot = struct { session: [36]u8, turn: [36]u8 };+pub const State = struct {+ value: ?Snapshot = null,+ pub fn begin(self: *State, io: std.Io) void {+ const session = if (self.value) |v| v.session else uuid(io);+ self.value = .{ .session = session, .turn = uuid(io) };+ }+};+fn uuid(io: std.Io) [36]u8 {+ var bytes: [16]u8 = undefined;+ io.random(&bytes);+ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ const hex = std.fmt.bytesToHex(bytes, .lower);+ var result: [36]u8 = undefined;+ var offset: usize = 0;+ for (&result, 0..) |*c, i| {+ if (i == 8 or i == 13 or i == 18 or i == 23) c.* = '-' else {+ c.* = hex[offset];+ offset += 1;+ }+ }+ return result;+}++/// Metadata is host-owned and scoped to the computer-use adapter, never+/// merged from model arguments or sent to unrelated MCP servers.+pub fn params(a: Allocator, server: []const u8, name: []const u8, input: std.json.Value, context: ?Snapshot) ![]u8 {+ var out: std.Io.Writer.Allocating = .init(a);+ errdefer out.deinit();+ var s: std.json.Stringify = .{ .writer = &out.writer };+ try s.beginObject();+ try s.objectField("name");+ try s.write(name);+ try s.objectField("arguments");+ try s.write(input);+ if (std.mem.eql(u8, server, "cua_repl") or std.mem.eql(u8, server, "node_repl")) {+ if (context) |ctx| {+ try s.objectField("_meta");+ try s.beginObject();+ try s.objectField("x-codex-turn-metadata");+ try s.write(.{ .session_id = ctx.session[0..], .turn_id = ctx.turn[0..] });+ try s.endObject();+ }+ }+ try s.endObject();+ return out.toOwnedSlice();+}++test "turn context is stable within a turn, rotates between turns and differs by caller" {+ var first: State = .{};+ var second: State = .{};+ first.begin(std.testing.io);+ const before = first.value.?;+ second.begin(std.testing.io);+ try std.testing.expect(!std.mem.eql(u8, &before.session, &second.value.?.session));+ first.begin(std.testing.io);+ try std.testing.expectEqualStrings(&before.session, &first.value.?.session);+ try std.testing.expect(!std.mem.eql(u8, &before.turn, &first.value.?.turn));+ try std.testing.expectEqual(@as(u8, '4'), before.session[14]);+ try std.testing.expectEqual(@as(u8, '-'), before.turn[8]);+}++test "computer bridge metadata stays outside arguments and unrelated MCP calls" {+ const a = std.testing.allocator;+ var state: State = .{};+ state.begin(std.testing.io);+ const input = try std.json.parseFromSlice(std.json.Value, a, "{\"_meta\":{\"x-codex-turn-metadata\":\"untrusted\"}}", .{});+ defer input.deinit();+ for ([_][]const u8{ "cua_repl", "node_repl", "ordinary" }) |server| {+ const text = try params(a, server, "js", input.value, state.value);+ defer a.free(text);+ const decoded = try std.json.parseFromSlice(std.json.Value, a, text, .{});+ defer decoded.deinit();+ const object = decoded.value.object;+ try std.testing.expectEqualStrings("untrusted", object.get("arguments").?.object.get("_meta").?.object.get("x-codex-turn-metadata").?.string);+ if (std.mem.eql(u8, server, "ordinary")) {+ try std.testing.expect(object.get("_meta") == null);+ } else {+ const context = object.get("_meta").?.object.get("x-codex-turn-metadata").?.object;+ try std.testing.expectEqualStrings(&state.value.?.session, context.get("session_id").?.string);+ try std.testing.expectEqualStrings(&state.value.?.turn, context.get("turn_id").?.string);+ }+ }+}diff --git a/src/tools.zig b/src/tools.zigindex e9f026e8..4da46561 100644--- a/src/tools.zig+++ b/src/tools.zig@@ -103,6 +103,7 @@ pub const ToolCtx = struct {subagent_provider: ?Provider = null,subagent_cross_provider: bool = false,registry: ?*mcp.Registry,+ mcp_context: ?@import("mcp_turn_context.zig").Snapshot = null,from_sub: bool,has_eval: bool = false, // the root's --eval loop: escalation's strongest verifierapprovals: ?*Approvals,