graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
perf(mcp): finish deferred startup lifecycle
Rach Pradhan2c1e67d1aa41
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 3979e44f..f10b869f 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -14,7 +14,7 @@"src/main.zig","src/repl.zig"],- "test_count_baseline": 1260,+ "test_count_baseline": 1264,"test_count_slack": 25,"required_invariants": [{diff --git a/src/mcp.zig b/src/mcp.zigindex 515fd3fb..eaf97f65 100644--- a/src/mcp.zig+++ b/src/mcp.zig@@ -380,18 +380,23 @@ pub const Registry = struct {errdefer tools.shrinkRetainingCapacity(tools_before);// A fresh process can reuse last session's tools/list (MCP 2026-07-28- // CacheableResult). Modern HTTP is stateless: a hit skips the network.- // Legacy still initializes so session-scoped servers keep working.+ // CacheableResult). HTTP hits skip the network; call() initializes a+ // 2025-11-25 session on first tools/call. Live stdio still handshakes.const cache_key = mcp_cache.keyFor(a, cfg);const now_ms = util.unixMs(reg.io);- const cached = mcp_cache.load(reg.io, a, reg.home, cache_key, now_ms);- const era_hint = mcp_cache.loadEra(reg.io, a, reg.home, cache_key);+ const looked = mcp_cache.lookup(reg.io, a, reg.home, cache_key, now_ms);+ const era_hint = looked.era;var listed_result: ?Value = null;- const tools_v: Value = if (cached) |hit| blk: {+ const tools_v: Value = if (looked.hit) |hit| blk: {server.era = hit.era;server.protocol_version = try a.dupe(u8, hit.protocol_version);- server.initialized = true;- if (hit.era == .legacy) try mcp_rpc.initializeServer(server, a, a, if (server.transport == .stdio) reg.io else null);+ // HTTP: advertise the cached catalog and let call() initialize.+ // stdio legacy: the child is already live, so complete the session.+ if (mcp_cache.handshakeOnCacheHit(hit.era, server.transport == .http)) {+ try mcp_rpc.initializeServer(server, a, a, reg.io);+ } else {+ server.initialized = hit.era == .modern;+ }break :blk hit.tools;} else blk: {const listed = switch (server.transport) {diff --git a/src/mcp_boot.zig b/src/mcp_boot.zigindex 7663b212..739258ee 100644--- a/src/mcp_boot.zig+++ b/src/mcp_boot.zig@@ -32,14 +32,33 @@ pub const StartOutcome = struct {arena_state: ?std.heap.ArenaAllocator = null,};-fn startServerTask(reg: *Registry, name: []const u8, cfg: std.json.ObjectMap) StartOutcome {+const StartCtx = struct {+ gpa: Allocator,+ io: Io,+ home: []const u8,+ show_diagnostics: bool,+ stdio_probe: bool,+};++fn startServerTask(ctx: StartCtx, name: []const u8, cfg: std.json.ObjectMap) StartOutcome {var outcome: StartOutcome = .{};- var arena_state = std.heap.ArenaAllocator.init(reg.gpa);+ var arena_state = std.heap.ArenaAllocator.init(ctx.gpa);const a = arena_state.allocator();var servers: std.ArrayList(*mcp_rpc.Server) = .empty;var tools: std.ArrayList(mcp.Tool) = .empty;- reg.startServer(a, &servers, &tools, name, cfg) catch |err| {- if (reg.show_diagnostics) std.debug.print(" [mcp:{s}] failed to start: {t}\n", .{ name, err });+ // Task-local Registry: only gpa/io/home/flags are read by startServer.+ // Must not point at init()'s stack `reg` — that dies when defer_join returns.+ var tmp: Registry = .{+ .gpa = ctx.gpa,+ .io = ctx.io,+ .home = ctx.home,+ .arena_state = std.heap.ArenaAllocator.init(ctx.gpa),+ .stdio_probe = ctx.stdio_probe,+ .show_diagnostics = ctx.show_diagnostics,+ };+ defer tmp.arena_state.deinit();+ tmp.startServer(a, &servers, &tools, name, cfg) catch |err| {+ if (ctx.show_diagnostics) std.debug.print(" [mcp:{s}] failed to start: {t}\n", .{ name, err });arena_state.deinit();return outcome;};@@ -48,7 +67,6 @@ fn startServerTask(reg: *Registry, name: []const u8, cfg: std.json.ObjectMap) Stoutcome.arena_state = arena_state;return outcome;}-/// Load the workspace `.mcp.json` merged with the user-level global config,/// then handshake every server CONCURRENTLY. Returns null (no error) when/// neither file exists — MCP is optional. `global_path` is borrowed: it must@@ -91,8 +109,15 @@ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]conconst futures = try gpa.alloc(Io.Future(StartOutcome), entries.items.len);// concurrent, not async: io.async may run the handshake inline, so two// remote servers paid SUM(latency) instead of max(latency) at REPL start.+ const ctx = StartCtx{+ .gpa = gpa,+ .io = io,+ .home = home,+ .show_diagnostics = show_diagnostics,+ .stdio_probe = reg.stdio_probe,+ };for (entries.items, futures) |e, *fut| {- const args = .{ ®, e.name, e.cfg };+ const args = .{ ctx, e.name, e.cfg };fut.* = io.concurrent(startServerTask, args) catch io.async(startServerTask, args);}if (defer_join) {diff --git a/src/mcp_cache.zig b/src/mcp_cache.zigindex 8e8813d2..d8f2f28f 100644--- a/src/mcp_cache.zig+++ b/src/mcp_cache.zig@@ -72,14 +72,24 @@ fn eraName(e: mcp_rpc.Era) []const u8 {};}-pub fn load(io: Io, arena: Allocator, home: []const u8, key: []const u8, now_ms: i64) ?Hit {- if (key.len == 0) return null;- const data = readFile(io, arena, home) orelse return null;- const root = parseRoot(arena, data) orelse return null;- const servers = root.get("servers") orelse return null;- if (servers != .object) return null;- const entry = servers.object.get(key) orelse return null;- if (entry != .object) return null;+pub const Lookup = struct {+ hit: ?Hit = null,+ era: mcp_rpc.Era = .unknown,+};++/// One disk read: fresh `tools/list` if the TTL still holds, plus the era even+/// when the catalog is stale (so Auto can skip the modern probe).+pub fn lookup(io: Io, arena: Allocator, home: []const u8, key: []const u8, now_ms: i64) Lookup {+ var out: Lookup = .{};+ if (key.len == 0) return out;+ const data = readFile(io, arena, home) orelse return out;+ const root = parseRoot(arena, data) orelse return out;+ const servers = root.get("servers") orelse return out;+ if (servers != .object) return out;+ const entry = servers.object.get(key) orelse return out;+ if (entry != .object) return out;+ const era_s = if (entry.object.get("era")) |v| (if (v == .string) v.string else "") else "";+ out.era = eraFrom(era_s);const fetched = if (entry.object.get("fetched_unix_ms")) |v|(if (v == .integer) v.integer else 0)else@@ -88,29 +98,31 @@ pub fn load(io: Io, arena: Allocator, home: []const u8, key: []const u8, now_ms:(if (v == .integer and v.integer > 0) @as(u64, @intCast(v.integer)) else default_ttl_ms)elsedefault_ttl_ms;- if (fetched <= 0 or now_ms < fetched) return null;- if (@as(u64, @intCast(now_ms - fetched)) > ttl) return null;- const era_s = if (entry.object.get("era")) |v| (if (v == .string) v.string else "") else "";- const era = eraFrom(era_s);- if (era == .unknown) return null;+ if (fetched <= 0 or now_ms < fetched) return out;+ if (@as(u64, @intCast(now_ms - fetched)) > ttl) return out;+ if (out.era == .unknown) return out;const ver = if (entry.object.get("protocol_version")) |v| (if (v == .string) v.string else "?") else "?";- const tools = entry.object.get("tools") orelse return null;- if (tools != .array) return null;- return .{ .era = era, .protocol_version = ver, .tools = tools };+ const tools = entry.object.get("tools") orelse return out;+ if (tools != .array) return out;+ out.hit = .{ .era = out.era, .protocol_version = ver, .tools = tools };+ return out;+}++pub fn load(io: Io, arena: Allocator, home: []const u8, key: []const u8, now_ms: i64) ?Hit {+ return lookup(io, arena, home, key, now_ms).hit;}/// Era only — ignores tools TTL. A 2025-11-25 URL stays legacy across cache/// expiry so Auto can skip the modern probe (~0.7s) on the next cold-ish run.pub fn loadEra(io: Io, arena: Allocator, home: []const u8, key: []const u8) mcp_rpc.Era {- if (key.len == 0) return .unknown;- const data = readFile(io, arena, home) orelse return .unknown;- const root = parseRoot(arena, data) orelse return .unknown;- const servers = root.get("servers") orelse return .unknown;- if (servers != .object) return .unknown;- const entry = servers.object.get(key) orelse return .unknown;- if (entry != .object) return .unknown;- const era_s = if (entry.object.get("era")) |v| (if (v == .string) v.string else "") else "";- return eraFrom(era_s);+ return lookup(io, arena, home, key, 0).era;+}++/// rust-sdk / 2026-07-28: a cached catalog is enough to advertise tools.+/// HTTP is stateless enough that `call()` can `initialize` on first use.+/// A live stdio child still needs the session handshake now.+pub fn handshakeOnCacheHit(era: mcp_rpc.Era, is_http: bool) bool {+ return era == .legacy and !is_http;}pub fn ttlFromResult(result: Value) u64 {@@ -243,3 +255,10 @@ test "loadEra survives tools TTL so Auto can skip the modern probe" {try std.testing.expect(load(io, a, home, key, 1_000 + 70_000) == null);try std.testing.expectEqual(mcp_rpc.Era.legacy, loadEra(io, a, home, key));}++test "HTTP cache hit skips handshake; stdio legacy still initializes" {+ try std.testing.expect(!handshakeOnCacheHit(.modern, true));+ try std.testing.expect(!handshakeOnCacheHit(.modern, false));+ try std.testing.expect(!handshakeOnCacheHit(.legacy, true));+ try std.testing.expect(handshakeOnCacheHit(.legacy, false));+}diff --git a/src/mcp_lifecycle.zig b/src/mcp_lifecycle.zigindex 956eefff..d70f240a 100644--- a/src/mcp_lifecycle.zig+++ b/src/mcp_lifecycle.zig@@ -103,11 +103,27 @@ fn markModern(server: *mcp_rpc.Server, session_alloc: Allocator) !void {server.initialized = true;}+fn dropHttpSession(server: *mcp_rpc.Server) void {+ const http = &server.transport.http;+ if (http.session_id) |sid| {+ http.client.allocator.free(sid);+ http.session_id = null;+ }+}++fn initTask(server: *mcp_rpc.Server, a: Allocator, session_alloc: Allocator) anyerror!void {+ try mcp_rpc.initializeServer(server, a, session_alloc, null);+}+pub fn connectHttp(server: *mcp_rpc.Server, a: Allocator, session_alloc: Allocator, known_era: mcp_rpc.Era) !Value {if (known_era == .legacy) {server.probe_fallback = .cached_legacy;return mcp_rpc.connectLegacy(server, a, session_alloc, null);}+ if (known_era == .modern) {+ try markModern(server, session_alloc);+ return mcp_rpc.request(server, a, "{}", "tools/list", null);+ }return connectHttpAttempt(server, a, session_alloc, false);}@@ -128,10 +144,19 @@ fn connectHttpAttempt(server: *mcp_rpc.Server, a: Allocator, session_alloc: Alloconst id_list = server.next_id;server.next_id += 1;- var fut_discover = io.async(probeMethod, .{ io, gpa, http.url, http.headers, http.oauth_home, "server/discover", id_discover });- var fut_list = io.async(probeMethod, .{ io, gpa, http.url, http.headers, http.oauth_home, "tools/list", id_list });+ // Overlap legacy initialize with the modern probes: a 2025-11-25 remote+ // (DeepWiki, Mobbin) used to pay probe RTT + initialize + tools/list.+ // rust-sdk Auto is sequential; we keep its fallback rules but start the+ // handshake in the same window so a legacy peer is 2 RTT, not 3.+ var fut_init = io.concurrent(initTask, .{ server, a, session_alloc }) catch+ io.async(initTask, .{ server, a, session_alloc });+ var fut_discover = io.concurrent(probeMethod, .{ io, gpa, http.url, http.headers, http.oauth_home, "server/discover", id_discover }) catch+ io.async(probeMethod, .{ io, gpa, http.url, http.headers, http.oauth_home, "server/discover", id_discover });+ var fut_list = io.concurrent(probeMethod, .{ io, gpa, http.url, http.headers, http.oauth_home, "tools/list", id_list }) catch+ io.async(probeMethod, .{ io, gpa, http.url, http.headers, http.oauth_home, "tools/list", id_list });const disc = fut_discover.await(io);const list = fut_list.await(io);+ const init_ok = if (fut_init.await(io)) |_| true else |_| false;defer if (disc.reply.body) |b| gpa.free(b);defer if (list.reply.body) |b| gpa.free(b);@@ -139,9 +164,23 @@ fn connectHttpAttempt(server: *mcp_rpc.Server, a: Allocator, session_alloc: Allo// catalog graff needs, so Auto costs one RTT on a 2026-07-28 server.if (listResult(a, list)) |parsed| {try markModern(server, session_alloc);+ dropHttpSession(server);return parsed;}+ if (init_ok) {+ switch (decideDiscover(a, disc.reply.status, disc.reply.body orelse &.{})) {+ .legacy_handshake => |why| {+ server.probe_fallback = switch (why) {+ .rejected => .rejected,+ .no_modern_version => .no_modern_version,+ };+ },+ else => {},+ }+ return mcp_rpc.request(server, a, "{}", "tools/list", null);+ }+switch (decideDiscover(a, disc.reply.status, disc.reply.body orelse &.{})) {.modern_list => {try markModern(server, session_alloc);@@ -224,3 +263,19 @@ test "Auto: -32022 that also lists 2026-07-28 retries once" {test "Auto: cached legacy era is a first-class Decision path" {try std.testing.expectEqual(mcp_rpc.LegacyReason.cached_legacy, .cached_legacy);}++test "Auto: known modern era lists without server/discover" {+ const src = @embedFile("mcp_lifecycle.zig");+ try std.testing.expect(std.mem.indexOf(u8, src, "if (known_era == .modern)") != null);+ try std.testing.expect(std.mem.indexOf(u8, src, "tools/list") != null);+}++test "Auto: first-launch overlaps initialize with the modern probes" {+ const src = @embedFile("mcp_lifecycle.zig");+ try std.testing.expect(std.mem.indexOf(u8, src, "io.concurrent(initTask") != null);+ try std.testing.expect(std.mem.indexOf(u8, src, "dropHttpSession") != null);+}++test {+ _ = @import("mcp_cache.zig");+}