Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

graff mcp serve: speak MCP 2026-07-28 beside the legacy handshake

justrach8ce15de20664
diff --git a/docs/mcp-server.md b/docs/mcp-server.md
index 52dc9a3e..b4097654 100644
--- a/docs/mcp-server.md
+++ b/docs/mcp-server.md
@@ -56,7 +56,11 @@ the Host and Origin headers, and exposes only `/mcp`. There is no public bind
or browser CORS access. The embedded UI is delivered through the MCP host.
POST accepts JSON-RPC and returns JSON, or HTTP 202 for accepted notifications.
-Initialization returns `Mcp-Session-Id`; later calls must send it. DELETE closes
+A 2026-07-28 request is stateless: no session, and its `MCP-Protocol-Version`,
+`Mcp-Method` and `Mcp-Name` headers must match the body (HTTP 400 with
+`-32020` otherwise; an unknown version gets HTTP 400 with `-32022`). For the
+older revisions, initialization returns `Mcp-Session-Id`; later calls must
+send it. DELETE closes
a session, and GET returns 405 (no SSE stream). The service retains up to 64
client handshakes, replacing the oldest on overflow; an evicted client gets
404 and must initialize again. Each client negotiates Apps support separately.
@@ -159,12 +163,19 @@ See the [MCP Apps specification](https://github.com/modelcontextprotocol/ext-app
## Lifecycle and limits
-The server implements MCP initialization, `ping`, `tools/list`, and
-`tools/call`, `resources/list`, `resources/read`, and an empty
-`resources/templates/list` using newline-delimited JSON-RPC on stdin/stdout. It supports
-protocol revisions 2024-11-05, 2025-03-26, and 2025-06-18, negotiating the
-last of these for an unknown revision. See the
-[MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle).
+The server implements `server/discover`, `ping`, `tools/list`, `tools/call`,
+`resources/list`, `resources/read`, and an empty `resources/templates/list`
+using newline-delimited JSON-RPC on stdin/stdout.
+
+- **2026-07-28** (stateless): each request carries its version and client
+ capabilities in `_meta`; no `initialize`. Results carry `resultType`, and
+ discovery, list and read results add `ttlMs` and `cacheScope: "public"`.
+ An unknown version gets `-32022` with `supported` and `requested`.
+- **2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05**: the `initialize`
+ handshake, negotiating 2025-11-25 for an unknown revision. `server/discover`
+ without `_meta` is method-not-found, so dual-era clients fall back.
+
+See the [MCP specification](https://modelcontextprotocol.io/specification).
Calls run serially. This initial adapter has no progress stream, live
cancellation, session continuation, or background task handle.
diff --git a/src/mcp_server.zig b/src/mcp_server.zig
index 5cb920cd..6ac0fca7 100644
--- a/src/mcp_server.zig
+++ b/src/mcp_server.zig
@@ -4,6 +4,7 @@ const Io = std.Io;
const Allocator = std.mem.Allocator;
const Value = std.json.Value;
const app = @import("mcp_server_app.zig");
+const modern = @import("mcp_server_modern.zig");
const runner = @import("process_runner.zig");
pub const Task = struct {
@@ -37,32 +38,48 @@ pub const Server = struct {
return;
}
const params = request.object.get("params") orelse Value.null;
- if (std.mem.eql(u8, method, "ping")) return reply(out, id, struct {}{});
- if (std.mem.eql(u8, method, "initialize")) {
+ // 2026-07-28: the version rides each request's _meta; no handshake.
+ const era: ?[]const u8 = modern.requestedVersion(params);
+ if (era) |requested| if (!modern.isSupported(requested)) return modern.unsupported(out, id, requested);
+ const apps = if (era != null) app.supported(try modern.capabilityParams(a, params)) else self.apps;
+ const answer: Answer = .{ .a = a, .out = out, .id = id, .modern = era != null };
+ if (std.mem.eql(u8, method, "ping")) return answer.send(struct {}{}, false);
+ if (std.mem.eql(u8, method, "server/discover")) {
+ if (era == null) return failure(out, id, -32601, "Method not found");
+ return answer.send(.{
+ .supportedVersions = modern.supported_versions,
+ .capabilities = capabilities,
+ .serverInfo = server_info,
+ .instructions = instructions,
+ }, true);
+ }
+ if (era == null and std.mem.eql(u8, method, "initialize")) {
if (self.initialized) return failure(out, id, -32600, "Already initialized");
const requested = string(params, "protocolVersion") orelse
return failure(out, id, -32602, "protocolVersion is required");
- const protocol = if (std.mem.eql(u8, requested, "2024-11-05") or std.mem.eql(u8, requested, "2025-03-26") or std.mem.eql(u8, requested, "2025-06-18")) requested else "2025-06-18";
+ const protocol = for (modern.supported_versions[1..]) |v| {
+ if (std.mem.eql(u8, requested, v)) break v;
+ } else modern.supported_versions[1];
self.apps = app.supported(params);
self.initialized = true;
return reply(out, id, .{
.protocolVersion = protocol,
- .capabilities = .{ .tools = struct {}{}, .resources = struct {}{} },
- .serverInfo = .{ .name = "codegraff", .title = "Codegraff", .version = @import("main.zig").harness_version },
- .instructions = "Delegate a small, self-contained task with run_task. Tasks run serially in the server launch directory with fresh context. Include scope and acceptance criteria; inspect the result and changes before integrating.",
+ .capabilities = capabilities,
+ .serverInfo = server_info,
+ .instructions = instructions,
});
}
- if (!self.ready) return failure(out, id, -32000, "Initialize the server first");
+ if (era == null and !self.ready) return failure(out, id, -32000, "Initialize the server first");
if (std.mem.eql(u8, method, "tools/list")) {
- const catalog = try app.catalog(a, tool_catalog, self.apps);
- return reply(out, id, catalog);
+ const catalog = try app.catalog(a, tool_catalog, apps);
+ return answer.send(catalog, true);
}
- if (std.mem.eql(u8, method, "resources/list")) return reply(out, id, .{ .resources = .{app.resource} });
- if (std.mem.eql(u8, method, "resources/templates/list")) return reply(out, id, .{ .resourceTemplates = [0]struct {}{} });
+ if (std.mem.eql(u8, method, "resources/list")) return answer.send(.{ .resources = .{app.resource} }, true);
+ if (std.mem.eql(u8, method, "resources/templates/list")) return answer.send(.{ .resourceTemplates = [0]struct {}{} }, true);
if (std.mem.eql(u8, method, "resources/read")) {
const uri = string(params, "uri") orelse return failure(out, id, -32602, "Resource URI is required");
if (!std.mem.eql(u8, uri, app.uri)) return failure(out, id, -32002, "Resource not found");
- return reply(out, id, app.contents());
+ return answer.send(app.contents(), true);
}
if (!std.mem.eql(u8, method, "tools/call")) return failure(out, id, -32601, "Method not found");
const name = string(params, "name") orelse return failure(out, id, -32602, "Tool name is required");
@@ -73,13 +90,30 @@ pub const Server = struct {
.text = try std.fmt.allocPrint(a, "Task could not run: {s}", .{@errorName(err)}),
.isError = true,
};
- return reply(out, id, .{ .content = .{.{ .type = "text", .text = result.text }}, .isError = result.isError, .structuredContent = .{
+ return answer.send(.{ .content = .{.{ .type = "text", .text = result.text }}, .isError = result.isError, .structuredContent = .{
.text = result.text,
.status = if (result.timed_out) "timed_out" else if (result.cancelled) "cancelled" else if (result.isError) "failed" else "completed",
.output_truncated = result.output_truncated,
.timeout_seconds = task.timeout_seconds,
.max_model_calls = task.max_model_calls,
- } });
+ } }, false);
+ }
+};
+
+const capabilities = .{ .tools = struct {}{}, .resources = struct {}{} };
+const server_info = .{ .name = "codegraff", .title = "Codegraff", .version = @import("main.zig").harness_version };
+const instructions = "Delegate a small, self-contained task with run_task. Tasks run serially in the server launch directory with fresh context. Include scope and acceptance criteria; inspect the result and changes before integrating.";
+
+/// One reply, in the requesting era's shape.
+const Answer = struct {
+ a: Allocator,
+ out: *Io.Writer,
+ id: Value,
+ modern: bool,
+
+ fn send(self: Answer, result: anytype, cacheable: bool) !void {
+ if (!self.modern) return reply(self.out, self.id, result);
+ return reply(self.out, self.id, try modern.envelope(self.a, result, cacheable));
}
};
diff --git a/src/mcp_server_http.zig b/src/mcp_server_http.zig
index 91260321..4188962a 100644
--- a/src/mcp_server_http.zig
+++ b/src/mcp_server_http.zig
@@ -2,6 +2,7 @@
const std = @import("std");
const Io = std.Io;
const mcp = @import("mcp_server.zig");
+const modern = @import("mcp_server_modern.zig");
const Value = std.json.Value;
const Session = struct { id: [32]u8, server: mcp.Server };
const State = struct {
@@ -62,6 +63,9 @@ fn handle(st: *State, req: *std.http.Server.Request) !void {
var host_ok = false;
var sid: ?[]const u8 = null;
var json_type = false;
+ var protocol_header: ?[]const u8 = null;
+ var method_header: ?[]const u8 = null;
+ var name_header: ?[]const u8 = null;
var headers = req.iterateHeaders();
while (headers.next()) |h| {
if (std.ascii.eqlIgnoreCase(h.name, "host")) host_ok = std.mem.eql(u8, h.value, host);
@@ -69,13 +73,28 @@ fn handle(st: *State, req: *std.http.Server.Request) !void {
if (std.ascii.eqlIgnoreCase(h.name, "authorization")) authorized = equalToken(h.value, bearer);
if (std.ascii.eqlIgnoreCase(h.name, "mcp-session-id")) sid = try a.dupe(u8, h.value);
if (std.ascii.eqlIgnoreCase(h.name, "content-type")) json_type = std.mem.eql(u8, h.value, "application/json") or std.mem.startsWith(u8, h.value, "application/json;");
- if (std.ascii.eqlIgnoreCase(h.name, "mcp-protocol-version") and !std.mem.eql(u8, h.value, "2025-06-18") and !std.mem.eql(u8, h.value, "2025-03-26") and !std.mem.eql(u8, h.value, "2024-11-05")) return respond(req, .bad_request, "{}", null);
+ if (std.ascii.eqlIgnoreCase(h.name, "mcp-protocol-version")) protocol_header = try a.dupe(u8, h.value);
+ if (std.ascii.eqlIgnoreCase(h.name, "mcp-method")) method_header = try a.dupe(u8, h.value);
+ if (std.ascii.eqlIgnoreCase(h.name, "mcp-name")) name_header = try a.dupe(u8, h.value);
}
if (!host_ok) return respond(req, .forbidden, "{}", null);
if (!authorized) return respond(req, .unauthorized, "{}", null);
if (req.head.method != .POST and req.head.method != .DELETE) return respond(req, .method_not_allowed, "{}", null);
+ if (protocol_header) |v| {
+ const known = for (modern.supported_versions) |s| {
+ if (std.mem.eql(u8, v, s)) break true;
+ } else false;
+ // A legacy client learns nothing from a JSON-RPC body here; a modern
+ // one reads -32022 and its supported list.
+ if (!known) return respondUnsupported(a, req, v);
+ }
try st.mutex.lock(st.io);
defer st.mutex.unlock(st.io);
+ var legacy_body: ?[]const u8 = null;
+ if (req.head.method == .POST and json_type) switch (try modernRequest(st, a, req, protocol_header, method_header, name_header)) {
+ .handled => return,
+ .legacy => |body| legacy_body = body,
+ };
var slot: ?*?Session = null;
if (sid) |id| {
for (&st.sessions) |*entry| if (entry.*) |s| {
@@ -91,12 +110,7 @@ fn handle(st: *State, req: *std.http.Server.Request) !void {
return respond(req, .no_content, "", null);
}
if (!json_type) return respond(req, .unsupported_media_type, "{}", null);
- if (req.head.content_length) |length| {
- if (length > 65536) return respond(req, .payload_too_large, "{}", null);
- }
- var buffer: [4096]u8 = undefined;
- const body_reader = try req.readerExpectContinue(&buffer);
- const body = body_reader.allocRemaining(a, .limited(65536)) catch return respond(req, .payload_too_large, "{}", null);
+ const body = legacy_body orelse return respond(req, .bad_request, "{}", null);
const value = std.json.parseFromSliceLeaky(Value, a, body, .{}) catch return respond(req, .bad_request, "{}", null);
if (value != .object) return respond(req, .bad_request, "{}", null);
const method = value.object.get("method") orelse return respond(req, .bad_request, "{}", null);
@@ -118,6 +132,53 @@ fn handle(st: *State, req: *std.http.Server.Request) !void {
return respond(req, if (output.written().len == 0) .accepted else .ok, output.written(), new_id);
}
+fn readBody(a: std.mem.Allocator, req: *std.http.Server.Request) !?[]const u8 {
+ if (req.head.content_length) |length| {
+ if (length > 65536) return null;
+ }
+ var buffer: [4096]u8 = undefined;
+ const body_reader = try req.readerExpectContinue(&buffer);
+ return body_reader.allocRemaining(a, .limited(65536)) catch null;
+}
+
+fn respondUnsupported(a: std.mem.Allocator, req: *std.http.Server.Request, requested: []const u8) !void {
+ var out: Io.Writer.Allocating = .init(a);
+ try modern.unsupported(&out.writer, .null, requested);
+ return respond(req, .bad_request, out.written(), null);
+}
+
+/// 2026-07-28 POSTs are stateless: no session, a fresh server per request,
+/// and headers that must agree with the body. The body is read here either
+/// way; a legacy one is handed back for the session path.
+const Routed = union(enum) { handled, legacy: []const u8 };
+
+fn modernRequest(st: *State, a: std.mem.Allocator, req: *std.http.Server.Request, protocol_header: ?[]const u8, method_header: ?[]const u8, name_header: ?[]const u8) !Routed {
+ const body = (try readBody(a, req)) orelse {
+ try respond(req, .payload_too_large, "{}", null);
+ return .handled;
+ };
+ const value = std.json.parseFromSliceLeaky(Value, a, body, .{}) catch return .{ .legacy = body };
+ if (value != .object) return .{ .legacy = body };
+ const params = value.object.get("params") orelse Value.null;
+ const requested = modern.requestedVersion(params) orelse return .{ .legacy = body };
+ const id = value.object.get("id") orelse Value.null;
+ var out: Io.Writer.Allocating = .init(a);
+ if (!modern.isSupported(requested)) {
+ try modern.unsupported(&out.writer, id, requested);
+ try respond(req, .bad_request, out.written(), null);
+ return .handled;
+ }
+ if (try modern.headerMismatch(a, value, protocol_header, method_header, name_header)) |why| {
+ try modern.mismatch(&out.writer, id, why);
+ try respond(req, .bad_request, out.written(), null);
+ return .handled;
+ }
+ var fresh = st.prototype;
+ try fresh.handle(a, &out.writer, body);
+ try respond(req, if (out.written().len == 0) .accepted else .ok, out.written(), null);
+ return .handled;
+}
+
pub fn equalToken(a: []const u8, b: []const u8) bool {
if (a.len != b.len) return false;
var diff: u8 = 0;
diff --git a/src/mcp_server_modern.zig b/src/mcp_server_modern.zig
new file mode 100644
index 00000000..bc9a618f
--- /dev/null
+++ b/src/mcp_server_modern.zig
@@ -0,0 +1,109 @@
+//! `graff mcp serve` as a 2026-07-28 (stateless) server, beside the legacy
+//! `initialize` path in mcp_server.zig.
+//!
+//! A request is modern when its `params._meta` names a protocol version. It
+//! needs no handshake: the version and client capabilities ride every
+//! request. Results carry `resultType`, and the cacheable ones (`server/
+//! discover`, the list methods, `resources/read`) carry `ttlMs` and
+//! `cacheScope`. An unknown version gets -32022 with `supported` and
+//! `requested`, which is also what tells a dual-era client this server is
+//! modern at all.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+const mcp_protocol = @import("mcp_protocol.zig");
+
+pub const version = mcp_protocol.modern_protocol;
+const version_key = "io.modelcontextprotocol/protocolVersion";
+const capabilities_key = "io.modelcontextprotocol/clientCapabilities";
+
+/// Every revision this server answers: the modern one, then the legacy
+/// `initialize` revisions in preference order.
+pub const supported_versions = [_][]const u8{ version, "2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05" };
+
+/// The catalog and the task-result view only change with the binary, and
+/// neither holds user data.
+pub const ttl_ms: u64 = 5 * 60 * 1000;
+
+pub const unsupported_code: i32 = -32022;
+pub const header_mismatch_code: i32 = -32020;
+
+fn meta(params: Value) ?std.json.ObjectMap {
+ if (params != .object) return null;
+ const m = params.object.get("_meta") orelse return null;
+ return if (m == .object) m.object else null;
+}
+
+/// The protocol version a modern request names, or null for a legacy one.
+pub fn requestedVersion(params: Value) ?[]const u8 {
+ const m = meta(params) orelse return null;
+ const v = m.get(version_key) orelse return null;
+ return if (v == .string) v.string else null;
+}
+
+pub fn isSupported(requested: []const u8) bool {
+ return std.mem.eql(u8, requested, version);
+}
+
+/// `{capabilities: <clientCapabilities>}` — the shape mcp_server_app.supported
+/// reads from a legacy `initialize`, so both eras share one check.
+pub fn capabilityParams(a: Allocator, params: Value) !Value {
+ var wrapped: std.json.ObjectMap = .empty;
+ if (meta(params)) |m| if (m.get(capabilities_key)) |caps| try wrapped.put(a, "capabilities", caps);
+ return .{ .object = wrapped };
+}
+
+/// `result` with the modern envelope fields added.
+pub fn envelope(a: Allocator, result: anytype, cacheable: bool) !Value {
+ const text = try std.json.Stringify.valueAlloc(a, result, .{});
+ var value = try std.json.parseFromSliceLeaky(Value, a, text, .{ .allocate = .alloc_always });
+ if (value != .object) return error.BadResult;
+ try value.object.put(a, "resultType", .{ .string = "complete" });
+ if (cacheable) {
+ try value.object.put(a, "ttlMs", .{ .integer = ttl_ms });
+ try value.object.put(a, "cacheScope", .{ .string = "public" });
+ }
+ return value;
+}
+
+pub fn unsupported(out: *Io.Writer, id: Value, requested: []const u8) !void {
+ var json: std.json.Stringify = .{ .writer = out };
+ try json.write(.{ .jsonrpc = "2.0", .id = id, .@"error" = .{
+ .code = unsupported_code,
+ .message = "Unsupported protocol version",
+ .data = .{ .supported = supported_versions, .requested = requested },
+ } });
+ try out.writeByte('\n');
+}
+
+/// Why a modern Streamable HTTP request's headers disagree with its body, or
+/// null when they agree. `protocol_header`, `method_header` and `name_header`
+/// are the raw header values (null when absent).
+pub fn headerMismatch(a: Allocator, body: Value, protocol_header: ?[]const u8, method_header: ?[]const u8, name_header: ?[]const u8) !?[]const u8 {
+ const params = if (body == .object) body.object.get("params") orelse Value.null else Value.null;
+ const requested = requestedVersion(params) orelse return null;
+ if (!std.mem.eql(u8, protocol_header orelse "", requested)) return "MCP-Protocol-Version header does not match _meta protocolVersion";
+ const method = if (body == .object) body.object.get("method") orelse Value.null else Value.null;
+ if (method != .string or !std.mem.eql(u8, method_header orelse "", method.string)) return "Mcp-Method header does not match the request method";
+ const name_field: ?[]const u8 = if (std.mem.eql(u8, method.string, "tools/call") or std.mem.eql(u8, method.string, "prompts/get"))
+ "name"
+ else if (std.mem.eql(u8, method.string, "resources/read")) "uri" else null;
+ const field = name_field orelse return null;
+ const v = if (params == .object) params.object.get(field) orelse Value.null else Value.null;
+ if (v != .string) return null; // the handler reports the missing argument
+ const expected = try mcp_protocol.headerValue(a, v.string);
+ if (!std.mem.eql(u8, name_header orelse "", expected)) return "Mcp-Name header does not match the request";
+ return null;
+}
+
+pub fn mismatch(out: *Io.Writer, id: Value, why: []const u8) !void {
+ var json: std.json.Stringify = .{ .writer = out };
+ try json.write(.{ .jsonrpc = "2.0", .id = id, .@"error" = .{ .code = header_mismatch_code, .message = why } });
+ try out.writeByte('\n');
+}
+
+test {
+ _ = @import("mcp_server_modern_tests.zig");
+}
diff --git a/src/mcp_server_modern_tests.zig b/src/mcp_server_modern_tests.zig
new file mode 100644
index 00000000..346fc958
--- /dev/null
+++ b/src/mcp_server_modern_tests.zig
@@ -0,0 +1,122 @@
+//! `graff mcp serve` speaking 2026-07-28 beside the legacy handshake.
+const std = @import("std");
+const Value = std.json.Value;
+const mcp = @import("mcp_server.zig");
+const modern = @import("mcp_server_modern.zig");
+
+const meta =
+ \\"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"probe","version":"1"},"io.modelcontextprotocol/clientCapabilities":{}}
+;
+
+fn fake(_: ?*anyopaque, _: std.mem.Allocator, task: mcp.Task) !mcp.Result {
+ return .{ .text = task.prompt };
+}
+
+fn run(a: std.mem.Allocator, input: []const u8) ![]const Value {
+ var source = std.Io.Reader.fixed(input);
+ var out: std.Io.Writer.Allocating = .init(a);
+ var server: mcp.Server = .{ .execute = fake };
+ try mcp.serve(a, &source, &out.writer, &server);
+ var replies: std.ArrayList(Value) = .empty;
+ var lines = std.mem.tokenizeScalar(u8, out.written(), '\n');
+ while (lines.next()) |line| try replies.append(a, try std.json.parseFromSliceLeaky(Value, a, line, .{}));
+ return replies.items;
+}
+
+fn result(reply: Value) std.json.ObjectMap {
+ return reply.object.get("result").?.object;
+}
+
+test "a 2026-07-28 client discovers, lists and calls with no initialize" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const replies = try run(a, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"server/discover\",\"params\":{" ++ meta ++ "}}\n" ++
+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{" ++ meta ++ "}}\n" ++
+ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{" ++ meta ++ ",\"name\":\"run_task\",\"arguments\":{\"prompt\":\"hi\"}}}\n");
+ try std.testing.expectEqual(@as(usize, 3), replies.len);
+
+ const discover = result(replies[0]);
+ try std.testing.expectEqualStrings("2026-07-28", discover.get("supportedVersions").?.array.items[0].string);
+ try std.testing.expectEqualStrings("codegraff", discover.get("serverInfo").?.object.get("name").?.string);
+ try std.testing.expect(discover.get("capabilities").?.object.get("tools") != null);
+ try std.testing.expectEqualStrings("complete", discover.get("resultType").?.string);
+ try std.testing.expectEqualStrings("public", discover.get("cacheScope").?.string);
+ try std.testing.expect(discover.get("ttlMs").?.integer >= 0);
+
+ const list = result(replies[1]);
+ try std.testing.expectEqualStrings("run_task", list.get("tools").?.array.items[0].object.get("name").?.string);
+ try std.testing.expectEqualStrings("complete", list.get("resultType").?.string);
+ try std.testing.expect(list.get("ttlMs") != null and list.get("cacheScope") != null);
+
+ const call = result(replies[2]);
+ try std.testing.expectEqualStrings("hi", call.get("content").?.array.items[0].object.get("text").?.string);
+ try std.testing.expectEqualStrings("complete", call.get("resultType").?.string);
+ try std.testing.expect(call.get("ttlMs") == null); // a tool call is not cacheable
+}
+
+test "an unknown modern version gets -32022 with supported and requested" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const replies = try run(a, "{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"tools/list\",\"params\":{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2099-01-01\"}}}\n");
+ const err = replies[0].object.get("error").?.object;
+ try std.testing.expectEqual(@as(i64, -32022), err.get("code").?.integer);
+ const data = err.get("data").?.object;
+ try std.testing.expectEqualStrings("2099-01-01", data.get("requested").?.string);
+ try std.testing.expectEqualStrings("2026-07-28", data.get("supported").?.array.items[0].string);
+ try std.testing.expectEqual(@as(i64, 7), replies[0].object.get("id").?.integer);
+}
+
+test "legacy clients: discover is method-not-found, initialize negotiates 2025-11-25" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ // No _meta: a dual-era client falls back to initialize on -32601.
+ const replies = try run(a, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"server/discover\"}\n" ++
+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\"}}\n" ++
+ "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n" ++
+ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/list\"}\n");
+ try std.testing.expectEqual(@as(i64, -32601), replies[0].object.get("error").?.object.get("code").?.integer);
+ try std.testing.expectEqualStrings("2025-11-25", result(replies[1]).get("protocolVersion").?.string);
+ const list = result(replies[2]);
+ try std.testing.expect(list.get("tools") != null);
+ try std.testing.expect(list.get("resultType") == null); // legacy results keep their old shape
+
+ const unknown = try run(a, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2030-01-01\"}}\n");
+ try std.testing.expectEqualStrings("2025-11-25", result(unknown[0]).get("protocolVersion").?.string);
+}
+
+test "MCP Apps is negotiated from the modern client capabilities" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const replies = try run(a, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientCapabilities\":{\"extensions\":{\"io.modelcontextprotocol/ui\":{\"mimeTypes\":[\"text/html;profile=mcp-app\"]}}}}}}\n" ++
+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{" ++ meta ++ "}}\n");
+ const with_ui = result(replies[0]).get("tools").?.array.items[0].object;
+ try std.testing.expectEqualStrings("ui://codegraff/task-result", with_ui.get("_meta").?.object.get("ui").?.object.get("resourceUri").?.string);
+ try std.testing.expect(result(replies[1]).get("tools").?.array.items[0].object.get("_meta") == null);
+}
+
+test "Streamable HTTP headers must agree with a modern body" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const call = try std.json.parseFromSliceLeaky(Value, a, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{" ++ meta ++ ",\"name\":\"run_task\",\"arguments\":{}}}", .{});
+ try std.testing.expect((try modern.headerMismatch(a, call, "2026-07-28", "tools/call", "run_task")) == null);
+ try std.testing.expect((try modern.headerMismatch(a, call, null, "tools/call", "run_task")) != null);
+ try std.testing.expect((try modern.headerMismatch(a, call, "2025-11-25", "tools/call", "run_task")) != null);
+ try std.testing.expect((try modern.headerMismatch(a, call, "2026-07-28", "tools/list", "run_task")) != null);
+ try std.testing.expect((try modern.headerMismatch(a, call, "2026-07-28", "tools/call", "other")) != null);
+ try std.testing.expect((try modern.headerMismatch(a, call, "2026-07-28", "tools/call", null)) != null);
+ const list = try std.json.parseFromSliceLeaky(Value, a, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{" ++ meta ++ "}}", .{});
+ try std.testing.expect((try modern.headerMismatch(a, list, "2026-07-28", "tools/list", null)) == null);
+ // A non-ASCII name travels base64-encoded; the encoded form matches.
+ const read = try std.json.parseFromSliceLeaky(Value, a, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"resources/read\",\"params\":{" ++ meta ++ ",\"uri\":\"ui://café\"}}", .{});
+ const encoded = try @import("mcp_protocol.zig").headerValue(a, "ui://café");
+ try std.testing.expect((try modern.headerMismatch(a, read, "2026-07-28", "resources/read", encoded)) == null);
+ try std.testing.expect((try modern.headerMismatch(a, read, "2026-07-28", "resources/read", "ui://café")) != null);
+ // A legacy body has nothing to check.
+ const legacy = try std.json.parseFromSliceLeaky(Value, a, "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/list\"}", .{});
+ try std.testing.expect((try modern.headerMismatch(a, legacy, null, null, null)) == null);
+}