Skip to content

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 Pradhan44f4822122ec
diff --git a/src/mcp.zig b/src/mcp.zig
index c7a76b6f..eaf97f65 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -24,6 +24,8 @@ const mcp_stdio = @import("mcp_stdio.zig");
const mcp_teardown = @import("mcp_teardown.zig");
const shutdown_trace = @import("shutdown_trace.zig"); // #364: teardown phase stamps
const mcp_rpc = @import("mcp_rpc.zig");
+const mcp_cache = @import("mcp_cache.zig");
+const util = @import("util.zig");
const smolify_manifest = @import("smolify_manifest.zig");
const vision = @import("vision.zig"); // #249: MCP image results become staged vision blocks
const renderContent = @import("mcp_content.zig").renderContent;
@@ -54,6 +56,8 @@ pub const Registry = struct {
mutex: Io.Mutex = .init,
servers: []*Server = &.{},
tools: []Tool = &.{},
+ /// Startup connection/failure lines are developer diagnostics, not normal REPL output.
+ show_diagnostics: bool = false,
/// The stdio spec's backward-compatibility SHOULD: a dual-era client
/// probes `server/discover` before assuming legacy. ON by default;
/// `GRAFF_MCP_PROBE=0` opts out.
@@ -87,6 +91,8 @@ pub const Registry = struct {
/// registry arena is not thread-safe, so each task allocated its own).
/// Freed in deinit AFTER the transports referencing them are torn down.
task_arenas: []std.heap.ArenaAllocator = &.{},
+ /// Unjoined startServer futures from a deferred --yolo boot.
+ pending_starts: []Io.Future(mcp_boot.StartOutcome) = &.{},
pub fn arena(self: *Registry) Allocator {
return self.arena_state.allocator();
@@ -233,7 +239,7 @@ pub const Registry = struct {
};
if (present) continue;
reg.startServer(a, &servers, &tools, try a.dupe(u8, name), entry.value_ptr.*.object) catch |err| {
- std.debug.print(" [mcp:{s}] failed to start: {t}\n", .{ name, err });
+ if (reg.show_diagnostics) std.debug.print(" [mcp:{s}] failed to start: {t}\n", .{ name, err });
};
}
reg.servers = try a.dupe(*Server, servers.items);
@@ -373,45 +379,52 @@ pub const Registry = struct {
const tools_before = tools.items.len;
errdefer tools.shrinkRetainingCapacity(tools_before);
- // Probe-then-fallback for HTTP (mcp_rpc.connectHttp), the unchanged
- // legacy handshake for stdio unless GRAFF_MCP_PROBE=1 opts into the
- // gated server/discover probe (mcp_rpc.probeStdio) — either way,
- // server.era and server.protocol_version are set by the time this
- // returns, and the model sees whichever revision was negotiated.
- const listed = switch (server.transport) {
- .http => try mcp_rpc.connectHttp(server, a, a),
- .stdio => stdio_listed: {
- if (!reg.stdio_probe) break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io);
- // #327: every legacy landing records WHY (and a probe that
- // could not run is retried before it is allowed to downgrade
- // anything), so a fallback shows up in the connect line and
- // `/mcp` instead of being indistinguishable from a server
- // that genuinely speaks only the legacy protocol.
- switch (try mcp_rpc.probeStdioResilient(server, a, reg.io)) {
- .modern => break :stdio_listed try mcp_rpc.finishModernStdio(server, a, a, reg.io),
- .legacy => |reason| {
- server.probe_fallback = reason;
- break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io);
- },
- .closed => {
- // The probe write/read found a dead process (some
- // legacy SDK servers exit on an unrecognized
- // pre-initialize message) — respawn once and go
- // straight to legacy on the fresh process, no
- // second probe against a server that already
- // proved it can't tolerate one.
- server.probe_fallback = .server_exited;
- mcp_stdio.stopChild(reg.io, &server.transport.stdio.child);
- server.transport = try spawnStdio(reg, a, stdio_argv.items, stdio_env_map);
- break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io);
- },
- }
- },
+ // A fresh process can reuse last session's tools/list (MCP 2026-07-28
+ // 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 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 (looked.hit) |hit| blk: {
+ server.era = hit.era;
+ server.protocol_version = try a.dupe(u8, hit.protocol_version);
+ // 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) {
+ .http => try mcp_rpc.connectHttp(server, a, a, era_hint),
+ .stdio => stdio_listed: {
+ if (!reg.stdio_probe) break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io);
+ switch (try mcp_rpc.probeStdioResilient(server, a, reg.io)) {
+ .modern => break :stdio_listed try mcp_rpc.finishModernStdio(server, a, a, reg.io),
+ .legacy => |reason| {
+ server.probe_fallback = reason;
+ break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io);
+ },
+ .closed => {
+ server.probe_fallback = .server_exited;
+ mcp_stdio.stopChild(reg.io, &server.transport.stdio.child);
+ server.transport = try spawnStdio(reg, a, stdio_argv.items, stdio_env_map);
+ break :stdio_listed try mcp_rpc.connectStdio(server, a, a, reg.io);
+ },
+ }
+ },
+ };
+ const result_v = listed.object.get("result") orelse return error.BadMcpResponse;
+ if (result_v != .object) return error.BadMcpResponse;
+ const tv = result_v.object.get("tools") orelse return error.BadMcpResponse;
+ if (tv != .array) return error.BadMcpResponse;
+ listed_result = result_v;
+ break :blk tv;
};
- const result_v = listed.object.get("result") orelse return error.BadMcpResponse;
- if (result_v != .object) return error.BadMcpResponse;
- const tools_v = result_v.object.get("tools") orelse return error.BadMcpResponse;
- if (tools_v != .array) return error.BadMcpResponse;
for (tools_v.array.items) |t| {
if (t != .object) continue;
const name_v = t.object.get("name") orelse continue;
@@ -437,8 +450,9 @@ pub const Registry = struct {
}
try servers.append(a, server);
registry_owns_server = true;
+ if (listed_result) |rv| mcp_cache.store(reg.io, a, reg.home, cache_key, server.era, server.protocol_version, rv, now_ms);
const probe_note = if (server.probe_fallback) |reason| reason.note() else ""; // #327: a downgrade is never silent
- std.debug.print(" [mcp:{s}] connected (mcp {s}) — {d} tool(s){s}\n", .{ name, server.protocol_version, tools_v.array.items.len, probe_note });
+ if (reg.show_diagnostics) std.debug.print(" [mcp:{s}] connected (mcp {s}) — {d} tool(s){s}\n", .{ name, server.protocol_version, tools_v.array.items.len, probe_note });
}
/// One shared window bounds the whole teardown: the loop is sequential, so
@@ -454,6 +468,7 @@ pub const Registry = struct {
}
pub fn deinit(reg: *Registry) void {
+ _ = mcp_boot.joinPending(reg);
const budget: mcp_teardown.Budget = .init(reg.io, mcp_teardown.teardown_grace);
for (reg.servers) |server| deinitServer(server, reg.io, budget);
for (reg.task_arenas) |*ta| ta.deinit();
@@ -564,3 +579,8 @@ pub const Registry = struct {
return .{ .text = try ow.toOwnedSlice(), .is_error = is_error };
}
};
+
+test {
+ _ = @import("mcp_cache.zig");
+ _ = @import("mcp_boot.zig");
+}
diff --git a/src/mcp_boot.zig b/src/mcp_boot.zig
index 52029130..739258ee 100644
--- a/src/mcp_boot.zig
+++ b/src/mcp_boot.zig
@@ -2,9 +2,14 @@
//! mcp.zig under the 600-line ceiling (#123). The fan-out is the point: each
//! server's handshake is a network or process round trip, so connecting them
//! serially charged every startup the SUM of the latencies. They now run
-//! concurrently (one task per server) and merge in config order, so the
+//! concurrently (one `io.concurrent` task per server — `io.async` can run
+//! inline and would serialize again) and merge in config order, so the
//! resulting tool list is identical to the serial build — only the wait is
//! shorter: max(latency) instead of sum(latency).
+//!
+//! Interactive `--yolo` sets `defer_join`: tasks start immediately but the
+//! REPL prompt is not blocked. `joinPending` merges them before the first
+//! model call, `/mcp`, or teardown.
const std = @import("std");
@@ -21,20 +26,39 @@ const Registry = mcp.Registry;
/// PER-TASK arena — the registry arena is not thread-safe — and the arena
/// travels with the outcome so the registry can free it at deinit, after the
/// transports referencing it are torn down.
-const StartOutcome = struct {
+pub const StartOutcome = struct {
server: ?*mcp_rpc.Server = null,
tools: []mcp.Tool = &.{},
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| {
- 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;
};
@@ -43,18 +67,19 @@ fn startServerTask(reg: *Registry, name: []const u8, cfg: std.json.ObjectMap) St
outcome.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
/// outlive the registry, which re-reads it on `/mcp trust`.
-pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]const u8, home: []const u8, environ_map: anytype) !?Registry {
+/// `defer_join` starts the handshakes but returns before they finish.
+pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]const u8, home: []const u8, show_diagnostics: bool, environ_map: anytype, defer_join: bool) !?Registry {
var reg: Registry = .{
.gpa = gpa,
.io = io,
.home = home,
.arena_state = std.heap.ArenaAllocator.init(gpa),
.stdio_probe = if (environ_map.get("GRAFF_MCP_PROBE")) |v| !std.mem.eql(u8, v, "0") else true,
+ .show_diagnostics = show_diagnostics,
.global_config_path = global_path,
};
mcp_rpc.applyHandshakeTimeoutEnv(environ_map); // #275 GRAFF_MCP_HANDSHAKE_SECS + #327 GRAFF_MCP_PROBE_MS, on the same pass as the probe flag
@@ -81,27 +106,73 @@ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]con
try entries.append(a, .{ .name = try a.dupe(u8, entry.key_ptr.*), .cfg = entry.value_ptr.*.object });
}
+ const 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 = .{ ctx, e.name, e.cfg };
+ fut.* = io.concurrent(startServerTask, args) catch io.async(startServerTask, args);
+ }
+ if (defer_join) {
+ reg.pending_starts = futures;
+ return reg;
+ }
+ defer gpa.free(futures);
+ mergeOutcomes(&reg, futures);
+ return reg;
+}
+
+fn mergeOutcomes(reg: *Registry, futures: []Io.Future(StartOutcome)) void {
+ const a = reg.arena();
var servers: std.ArrayList(*mcp_rpc.Server) = .empty;
var tools: std.ArrayList(mcp.Tool) = .empty;
var task_arenas: std.ArrayList(std.heap.ArenaAllocator) = .empty;
-
- const futures = try gpa.alloc(Io.Future(StartOutcome), entries.items.len);
- defer gpa.free(futures);
- for (entries.items, futures) |e, *fut| fut.* = io.async(startServerTask, .{ &reg, e.name, e.cfg });
- // Join in config order: every tool's server_index is rewritten to its
- // server's final slot, so the merged lists match the serial build exactly.
+ servers.appendSlice(a, reg.servers) catch {};
+ tools.appendSlice(a, reg.tools) catch {};
+ task_arenas.appendSlice(a, reg.task_arenas) catch {};
for (futures) |*fut| {
- const outcome = fut.await(io);
+ const outcome = fut.await(reg.io);
const server = outcome.server orelse continue;
const server_index = servers.items.len;
- try servers.append(a, server);
- for (outcome.tools) |*t| t.server_index = server_index;
- try tools.appendSlice(a, outcome.tools);
- if (outcome.arena_state) |ta| try task_arenas.append(a, ta);
+ servers.append(a, server) catch continue;
+ for (outcome.tools) |*tool| tool.server_index = server_index;
+ tools.appendSlice(a, outcome.tools) catch {};
+ if (outcome.arena_state) |ta| task_arenas.append(a, ta) catch {};
}
+ reg.servers = a.dupe(*mcp_rpc.Server, servers.items) catch reg.servers;
+ reg.tools = a.dupe(mcp.Tool, tools.items) catch reg.tools;
+ reg.task_arenas = a.dupe(std.heap.ArenaAllocator, task_arenas.items) catch reg.task_arenas;
+}
- reg.servers = try a.dupe(*mcp_rpc.Server, servers.items);
- reg.tools = try a.dupe(mcp.Tool, tools.items);
- reg.task_arenas = try a.dupe(std.heap.ArenaAllocator, task_arenas.items);
- return reg;
+/// Await deferred startServer tasks and append them to the live registry
+/// (companion servers may already be present). Idempotent. Returns true
+/// when this call actually merged something, so the agent can rebuild catalogs.
+pub fn joinPending(reg: *Registry) bool {
+ if (reg.pending_starts.len == 0) return false;
+ const futures = reg.pending_starts;
+ reg.pending_starts = &.{};
+ mergeOutcomes(reg, futures);
+ reg.gpa.free(futures);
+ return true;
+}
+
+test "MCP boot fans server handshakes out with io.concurrent" {
+ const src = @embedFile("mcp_boot.zig");
+ try std.testing.expect(std.mem.indexOf(u8, src, "io.concurrent(startServerTask") != null);
+ try std.testing.expect(std.mem.indexOf(u8, src, "io.async(startServerTask") != null);
+ try std.testing.expect(std.mem.indexOf(u8, src, "defer_join") != null);
+}
+
+test "joinPending is a no-op on an empty registry" {
+ const io = std.testing.io;
+ var reg = Registry.empty(std.testing.allocator, io);
+ defer reg.deinit();
+ try std.testing.expect(!joinPending(&reg));
}
diff --git a/src/mcp_cache.zig b/src/mcp_cache.zig
new file mode 100644
index 00000000..d8f2f28f
--- /dev/null
+++ b/src/mcp_cache.zig
@@ -0,0 +1,264 @@
+//! On-disk `tools/list` cache (MCP 2026-07-28 CacheableResult / rust-sdk
+//! ClientCacheConfig). Remote servers are stateless: a fresh process can
+//! reuse last session's tool catalog and skip the handshake until TTL.
+//!
+//! Modern HTTP: no network at all on a hit. Legacy: still `initialize`,
+//! but not a second `tools/list`. Nothing secret is stored — names,
+//! descriptions, schemas, era, TTL.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const mcp_rpc = @import("mcp_rpc.zig");
+const credential_store = @import("credential_store.zig");
+const util = @import("util.zig");
+
+const rel_path = ".codegraff/mcp-list-cache.json";
+const default_ttl_ms: u64 = 60 * 60 * 1000;
+const min_ttl_ms: u64 = 60 * 1000;
+const max_ttl_ms: u64 = 24 * 60 * 60 * 1000;
+
+pub const Hit = struct {
+ era: mcp_rpc.Era,
+ protocol_version: []const u8,
+ tools: Value,
+};
+
+pub fn keyFor(arena: Allocator, cfg: std.json.ObjectMap) []const u8 {
+ if (cfg.get("url")) |u| if (u == .string) {
+ return std.fmt.allocPrint(arena, "url:{s}", .{u.string}) catch "";
+ };
+ const cmd = if (cfg.get("command")) |c| (if (c == .string) c.string else "") else "";
+ var aw: Io.Writer.Allocating = .init(arena);
+ aw.writer.print("cmd:{s}", .{cmd}) catch return "";
+ if (cfg.get("args")) |args| if (args == .array) {
+ for (args.array.items) |arg| if (arg == .string) {
+ aw.writer.print(" {s}", .{arg.string}) catch {};
+ };
+ };
+ return aw.writer.buffered();
+}
+
+fn cachePath(arena: Allocator, home: []const u8) []const u8 {
+ if (home.len == 0) return "";
+ return std.fmt.allocPrint(arena, "{s}/" ++ rel_path, .{home}) catch "";
+}
+
+fn readFile(io: Io, arena: Allocator, home: []const u8) ?[]const u8 {
+ const path = cachePath(arena, home);
+ if (path.len == 0) return null;
+ return Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(2 * 1024 * 1024)) catch null;
+}
+
+fn parseRoot(arena: Allocator, data: []const u8) ?std.json.ObjectMap {
+ const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;
+ if (v != .object) return null;
+ return v.object;
+}
+
+fn eraFrom(s: []const u8) mcp_rpc.Era {
+ if (std.mem.eql(u8, s, "modern")) return .modern;
+ if (std.mem.eql(u8, s, "legacy")) return .legacy;
+ return .unknown;
+}
+
+fn eraName(e: mcp_rpc.Era) []const u8 {
+ return switch (e) {
+ .modern => "modern",
+ .legacy => "legacy",
+ .unknown => "unknown",
+ };
+}
+
+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
+ 0;
+ const ttl = if (entry.object.get("ttl_ms")) |v|
+ (if (v == .integer and v.integer > 0) @as(u64, @intCast(v.integer)) else default_ttl_ms)
+ else
+ default_ttl_ms;
+ 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 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 {
+ 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 {
+ if (result != .object) return default_ttl_ms;
+ const v = result.object.get("ttlMs") orelse result.object.get("ttl_ms") orelse return default_ttl_ms;
+ const n: u64 = switch (v) {
+ .integer => |i| if (i > 0) @intCast(i) else default_ttl_ms,
+ .float => |f| if (f > 0) @intFromFloat(f) else default_ttl_ms,
+ else => default_ttl_ms,
+ };
+ return @min(max_ttl_ms, @max(min_ttl_ms, n));
+}
+
+pub fn store(
+ io: Io,
+ arena: Allocator,
+ home: []const u8,
+ key: []const u8,
+ era: mcp_rpc.Era,
+ protocol_version: []const u8,
+ result: Value,
+ now_ms: i64,
+) void {
+ if (key.len == 0 or home.len == 0 or era == .unknown) return;
+ const tools = if (result == .object) result.object.get("tools") else null;
+ if (tools == null or tools.? != .array) return;
+ const ttl = ttlFromResult(result);
+
+ var root_map: std.json.ObjectMap = .empty;
+ if (readFile(io, arena, home)) |data| {
+ if (parseRoot(arena, data)) |existing| root_map = existing;
+ }
+ var servers_map: std.json.ObjectMap = .empty;
+ if (root_map.get("servers")) |s| if (s == .object) {
+ servers_map = s.object;
+ };
+
+ var entry: std.json.ObjectMap = .empty;
+ entry.put(arena, "era", .{ .string = eraName(era) }) catch return;
+ entry.put(arena, "protocol_version", .{ .string = protocol_version }) catch return;
+ entry.put(arena, "fetched_unix_ms", .{ .integer = now_ms }) catch return;
+ entry.put(arena, "ttl_ms", .{ .integer = @intCast(ttl) }) catch return;
+ entry.put(arena, "tools", tools.?) catch return;
+ servers_map.put(arena, key, .{ .object = entry }) catch return;
+ root_map.put(arena, "servers", .{ .object = servers_map }) catch return;
+
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.write(Value{ .object = root_map }) catch return;
+ const path = cachePath(arena, home);
+ if (path.len == 0) return;
+ if (std.fs.path.dirname(path)) |dir| Io.Dir.cwd().createDirPath(io, dir) catch {};
+ credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), .default_file) catch {};
+}
+
+test "keyFor distinguishes url and command+args" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var url_cfg: std.json.ObjectMap = .empty;
+ try url_cfg.put(a, "url", .{ .string = "https://example.com/mcp" });
+ try std.testing.expectEqualStrings("url:https://example.com/mcp", keyFor(a, url_cfg));
+ var cmd_cfg: std.json.ObjectMap = .empty;
+ try cmd_cfg.put(a, "command", .{ .string = "npx" });
+ var args = std.json.Array.init(a);
+ try args.append(.{ .string = "-y" });
+ try args.append(.{ .string = "foo" });
+ try cmd_cfg.put(a, "args", .{ .array = args });
+ try std.testing.expectEqualStrings("cmd:npx -y foo", keyFor(a, cmd_cfg));
+}
+
+test "ttlFromResult honors CacheableResult ttlMs and clamps" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const empty: std.json.ObjectMap = .empty;
+ try std.testing.expectEqual(default_ttl_ms, ttlFromResult(.{ .object = empty }));
+ var short: std.json.ObjectMap = .empty;
+ try short.put(a, "ttlMs", .{ .integer = 10 });
+ try std.testing.expectEqual(min_ttl_ms, ttlFromResult(.{ .object = short }));
+ var long: std.json.ObjectMap = .empty;
+ try long.put(a, "ttl_ms", .{ .integer = 99_000_000_000 });
+ try std.testing.expectEqual(max_ttl_ms, ttlFromResult(.{ .object = long }));
+}
+
+test "store then load within TTL; miss after expiry" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+
+ var result: std.json.ObjectMap = .empty;
+ var tools = std.json.Array.init(a);
+ var tool: std.json.ObjectMap = .empty;
+ try tool.put(a, "name", .{ .string = "search" });
+ try tool.put(a, "description", .{ .string = "find things" });
+ try tools.append(.{ .object = tool });
+ try result.put(a, "tools", .{ .array = tools });
+ try result.put(a, "ttlMs", .{ .integer = 5_000 });
+
+ const key = "url:https://example.com/mcp";
+ store(io, a, home, key, .modern, "2026-07-28", .{ .object = result }, 1_000_000);
+ const hit = load(io, a, home, key, 1_000_000 + 2_000) orelse return error.TestExpectedEqual;
+ try std.testing.expectEqual(mcp_rpc.Era.modern, hit.era);
+ try std.testing.expectEqualStrings("2026-07-28", hit.protocol_version);
+ try std.testing.expectEqual(@as(usize, 1), hit.tools.array.items.len);
+ try std.testing.expect(load(io, a, home, key, 1_000_000 + 70_000) == null);
+ try std.testing.expect(load(io, a, home, "url:https://other.example/mcp", 1_000_000) == null);
+ try std.testing.expectEqual(mcp_rpc.Era.modern, loadEra(io, a, home, key));
+ try std.testing.expectEqual(mcp_rpc.Era.unknown, loadEra(io, a, home, "url:https://other.example/mcp"));
+}
+
+test "loadEra survives tools TTL so Auto can skip the modern probe" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+ var result: std.json.ObjectMap = .empty;
+ const tools = std.json.Array.init(a);
+ try result.put(a, "tools", .{ .array = tools });
+ try result.put(a, "ttlMs", .{ .integer = 1_000 });
+ const key = "url:https://mcp.deepwiki.com/mcp";
+ store(io, a, home, key, .legacy, "2025-11-25", .{ .object = result }, 1_000);
+ 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.zig
new file mode 100644
index 00000000..d70f240a
--- /dev/null
+++ b/src/mcp_lifecycle.zig
@@ -0,0 +1,281 @@
+//! HTTP client lifecycle matching rust-sdk `ClientLifecycleMode::Auto`.
+//!
+//! Probe `server/discover` and `tools/list` in parallel (two HTTP clients so
+//! the shared `std.http.Client` is never raced). A modern `tools/list` result
+//! is enough — the 2026-07-28 spec lets any request be first. A modern
+//! `supportedVersions` list without a usable `tools/list` pays one follow-up
+//! list. Anything else falls back to the legacy initialize handshake, the
+//! same METHOD_NOT_FOUND path as `auto_startup_falls_back_after_discover_method_not_found`.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const mcp_http = @import("mcp_http.zig");
+const mcp_oauth = @import("mcp_oauth.zig");
+const mcp_protocol = @import("mcp_protocol.zig");
+const mcp_rpc = @import("mcp_rpc.zig");
+
+const modern_protocol = mcp_protocol.modern_protocol;
+
+pub const Fallback = enum { rejected, no_modern_version };
+
+/// rust-sdk Auto: discover (and a parallel tools/list) then maybe initialize.
+pub const Decision = union(enum) {
+ modern_list,
+ legacy_handshake: Fallback,
+ retry,
+ reject_modern,
+ incompatible,
+};
+
+pub fn decideDiscover(a: Allocator, status: u16, body: []const u8) Decision {
+ if (status >= 200 and status < 300) modern: {
+ const trimmed = std.mem.trim(u8, body, " \t\r\n");
+ if (trimmed.len == 0) break :modern;
+ const parsed = std.json.parseFromSliceLeaky(Value, a, trimmed, .{ .allocate = .alloc_always }) catch break :modern;
+ if (parsed != .object or parsed.object.get("result") == null) break :modern;
+ const versions = mcp_protocol.discoverSupportedVersions(parsed) catch
+ return .{ .legacy_handshake = .no_modern_version };
+ for (versions) |v| {
+ if (v == .string and std.mem.eql(u8, v.string, modern_protocol)) return .modern_list;
+ }
+ return .{ .legacy_handshake = .no_modern_version };
+ }
+ return switch (mcp_protocol.classifyProbe(a, body)) {
+ .legacy => .{ .legacy_handshake = .rejected },
+ .modern => .reject_modern,
+ .incompatible => .incompatible,
+ .unsupported_version => |supported| {
+ for (supported) |v| {
+ if (v == .string and std.mem.eql(u8, v.string, modern_protocol)) return .retry;
+ }
+ return .{ .legacy_handshake = .no_modern_version };
+ },
+ };
+}
+
+const ProbeOut = struct {
+ reply: mcp_http.ProbeReply,
+ id: i64,
+};
+
+fn probeMethod(
+ io: Io,
+ gpa: Allocator,
+ url: []const u8,
+ headers: []const std.http.Header,
+ oauth_home: ?[]const u8,
+ method: []const u8,
+ id: i64,
+) ProbeOut {
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ var transport: mcp_http.HttpTransport = .{
+ .url = url,
+ .client = .{ .allocator = gpa, .io = io },
+ .headers = headers,
+ .oauth_home = oauth_home,
+ };
+ defer transport.client.deinit();
+ const body = mcp_protocol.buildRequest(arena_state.allocator(), id, method, "{}", true) catch
+ return .{ .reply = .{ .status = 0, .body = null }, .id = id };
+ const reply = mcp_http.probe(&transport, body, .{
+ .protocol_version = modern_protocol,
+ .method = method,
+ .modern = true,
+ }) catch return .{ .reply = .{ .status = 0, .body = null }, .id = id };
+ return .{ .reply = reply, .id = id };
+}
+
+fn listResult(a: Allocator, out: ProbeOut) ?Value {
+ if (out.reply.status < 200 or out.reply.status >= 300) return null;
+ const body = out.reply.body orelse return null;
+ const parsed = mcp_http.parseHttpResponse(a, body, out.id) orelse return null;
+ if (parsed != .object or parsed.object.get("result") == null) return null;
+ return parsed;
+}
+
+fn markModern(server: *mcp_rpc.Server, session_alloc: Allocator) !void {
+ server.era = .modern;
+ server.protocol_version = try session_alloc.dupe(u8, modern_protocol);
+ 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);
+}
+
+fn connectHttpAttempt(server: *mcp_rpc.Server, a: Allocator, session_alloc: Allocator, retried: bool) !Value {
+ const http = &server.transport.http;
+ const io = http.client.io;
+ const gpa = http.client.allocator;
+
+ // Two probes may load the same OAuth file. Refresh once so neither races a mint.
+ if (http.oauth_home) |home| {
+ var oa = std.heap.ArenaAllocator.init(gpa);
+ defer oa.deinit();
+ _ = mcp_oauth.loadAccessToken(io, gpa, oa.allocator(), home, http.url);
+ }
+
+ const id_discover = server.next_id;
+ server.next_id += 1;
+ const id_list = server.next_id;
+ server.next_id += 1;
+
+ // 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);
+
+ // Spec: any modern request can be first. A real tools/list result is the
+ // 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);
+ return mcp_rpc.request(server, a, "{}", "tools/list", null);
+ },
+ .legacy_handshake => |why| {
+ server.probe_fallback = switch (why) {
+ .rejected => .rejected,
+ .no_modern_version => .no_modern_version,
+ };
+ return mcp_rpc.connectLegacy(server, a, session_alloc, null);
+ },
+ .retry => {
+ if (!retried) return connectHttpAttempt(server, a, session_alloc, true);
+ return error.McpIncompatibleProtocolVersion;
+ },
+ .reject_modern => return error.McpModernRequestRejected,
+ .incompatible => return error.McpIncompatibleProtocolVersion,
+ }
+}
+
+fn expectDecision(body: []const u8, status: u16, want: std.meta.Tag(Decision)) !void {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const got = decideDiscover(arena_state.allocator(), status, body);
+ try std.testing.expectEqual(want, std.meta.activeTag(got));
+}
+
+test "Auto: server/discover listing 2026-07-28 is modern_list" {
+ try expectDecision(
+ \\{"jsonrpc":"2.0","id":1,"result":{"supportedVersions":["2026-07-28","2025-11-25"]}}
+ , 200, .modern_list);
+}
+
+test "Auto: discover without 2026-07-28 falls back (no_modern_version)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const got = decideDiscover(arena_state.allocator(), 200,
+ \\{"jsonrpc":"2.0","id":1,"result":{"supportedVersions":["2025-11-25"]}}
+ );
+ try std.testing.expectEqual(Decision{ .legacy_handshake = .no_modern_version }, got);
+}
+
+test "Auto: METHOD_NOT_FOUND (-32601) falls back like rust-sdk Auto" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const got = decideDiscover(arena_state.allocator(), 200,
+ \\{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"Method not found"}}
+ );
+ try std.testing.expectEqual(Decision{ .legacy_handshake = .rejected }, got);
+}
+
+test "Auto: initialize-first rejection falls back" {
+ try expectDecision(
+ \\{"jsonrpc":"2.0","error":{"code":-32000,"message":"Bad Request: Server not initialized"},"id":null}
+ , 200, .legacy_handshake);
+}
+
+test "Auto: -32020 is a modern reject, never a legacy fallback" {
+ try expectDecision(
+ \\{"jsonrpc":"2.0","id":1,"error":{"code":-32020,"message":"header mismatch"}}
+ , 400, .reject_modern);
+}
+
+test "Auto: -32022 listing only 2025-11-25 is a legacy handshake" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const got = decideDiscover(arena_state.allocator(), 400,
+ \\{"jsonrpc":"2.0","id":1,"error":{"code":-32022,"data":{"supported":["2025-11-25"]}}}
+ );
+ try std.testing.expectEqual(Decision{ .legacy_handshake = .no_modern_version }, got);
+}
+
+test "Auto: -32022 that also lists 2026-07-28 retries once" {
+ try expectDecision(
+ \\{"jsonrpc":"2.0","id":1,"error":{"code":-32022,"data":{"supported":["2026-07-28"]}}}
+ , 400, .retry);
+}
+
+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");
+}