graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(mcp): probe Streamable HTTP servers for 2026-07-28 before falling back
Rach Pradhanc8f7aed84c76
diff --git a/scripts/test-mcp-legacy-fallback.py b/scripts/test-mcp-legacy-fallback.pynew file mode 100644index 00000000..c4c961b8--- /dev/null+++ b/scripts/test-mcp-legacy-fallback.py@@ -0,0 +1,259 @@+#!/usr/bin/env python3+"""Offline end-to-end proof that graff's HTTP MCP client still falls back to+the pre-2026-07-28 handshake byte-for-byte. The fixture answers the modern+probe (an unadorned `tools/list`) with a 400 shaped like the real TS SDK's+pre-initialize rejection, then requires the legacy `initialize` ->+`notifications/initialized` -> `tools/list` sequence — each request must be+indistinguishable from what graff sent before this migration: no `_meta`,+no `Mcp-Method`/`Mcp-Name` header, and the negotiated `Mcp-Session-Id`+echoed once the fixture has minted one."""++from __future__ import annotations++import argparse+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import subprocess+import tempfile+import threading+from typing import Any+++LEGACY_PROTOCOL = "2025-11-25"+NEGOTIATED_PROTOCOL = "2025-06-18"+SESSION_ID = "graff-mcp-fixture-session"++# The real TS SDK's shape for "you didn't call initialize first" — id is+# null because the server never learned graff's request id.+MODERN_PROBE_REJECTION = json.dumps(+ {+ "jsonrpc": "2.0",+ "error": {"code": -32000, "message": "Bad Request: Server not initialized"},+ "id": None,+ },+ separators=(",", ":"),+).encode()+++class McpFixture(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"+ requests: list[dict[str, Any]] = []+ failure: BaseException | None = None+ lock = threading.Lock()++ def log_message(self, _format: str, *_args: object) -> None:+ pass++ def _respond(+ self,+ status: int,+ body: bytes = b"",+ content_type: str | None = None,+ session_id: str | None = None,+ ) -> None:+ self.send_response(status)+ self.send_header("Content-Length", str(len(body)))+ if content_type is not None:+ self.send_header("Content-Type", content_type)+ if session_id is not None:+ self.send_header("Mcp-Session-Id", session_id)+ self.end_headers()+ if body:+ self.wfile.write(body)++ def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API+ try:+ length = int(self.headers.get("Content-Length", "0"))+ raw = self.rfile.read(length)+ message = json.loads(raw)+ assert self.path == "/mcp"+ assert self.headers.get_content_type() == "application/json"+ accept = self.headers.get("Accept", "")+ assert "application/json" in accept+ assert "text/event-stream" in accept+ assert self.headers.get("Authorization") is None++ with self.lock:+ ordinal = len(self.requests) + 1+ self.requests.append(+ {+ "message": message,+ "protocol": self.headers.get("Mcp-Protocol-Version"),+ "method_header": self.headers.get("Mcp-Method"),+ "name_header": self.headers.get("Mcp-Name"),+ "session": self.headers.get("Mcp-Session-Id"),+ "raw": raw.decode("utf-8"),+ }+ )++ # Every legacy-shaped request (everything after the modern probe)+ # must carry neither Mcp-Method nor Mcp-Name — that pair only+ # exists in the stateless 2026-07-28 wire format.+ if ordinal > 1:+ assert self.headers.get("Mcp-Method") is None+ assert self.headers.get("Mcp-Name") is None+ assert "_meta" not in raw.decode("utf-8")++ if ordinal == 1:+ # The modern probe: an unadorned tools/list, no handshake.+ assert message["method"] == "tools/list"+ assert message["id"] == 1+ assert "_meta" in message["params"]+ assert self.headers.get("Mcp-Protocol-Version") == "2026-07-28"+ assert self.headers.get("Mcp-Method") == "tools/list"+ assert self.headers.get("Mcp-Session-Id") is None+ self._respond(400, MODERN_PROBE_REJECTION, "application/json")+ return++ if ordinal == 2:+ assert message["method"] == "initialize"+ assert message["id"] == 2+ assert message["params"]["protocolVersion"] == LEGACY_PROTOCOL+ assert self.headers.get("Mcp-Protocol-Version") == LEGACY_PROTOCOL+ # No session minted yet: nothing to echo on the request that+ # establishes one.+ assert self.headers.get("Mcp-Session-Id") is None+ body = json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 2,+ "result": {+ "protocolVersion": NEGOTIATED_PROTOCOL,+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "fixture", "version": "1"},+ },+ },+ separators=(",", ":"),+ ).encode()+ self._respond(200, body, "application/json", SESSION_ID)+ return++ assert self.headers.get("Mcp-Protocol-Version") == NEGOTIATED_PROTOCOL+ assert self.headers.get("Mcp-Session-Id") == SESSION_ID+ if ordinal == 3:+ assert message == {+ "jsonrpc": "2.0",+ "method": "notifications/initialized",+ "params": {},+ }+ self._respond(202)+ return++ assert ordinal == 4+ assert message["method"] == "tools/list"+ assert message["id"] == 3+ body = json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 3,+ "result": {+ "tools": [+ {+ "name": "fixture_search",+ "description": "Search public fixture docs.",+ "inputSchema": {"type": "object", "properties": {}},+ }+ ]+ },+ },+ separators=(",", ":"),+ ).encode()+ self._respond(200, body, "application/json")+ except BaseException as exc:+ self.failure = exc+ self._respond(500)+++def run(graff: Path) -> None:+ McpFixture.requests = []+ McpFixture.failure = None+ server = ThreadingHTTPServer(("127.0.0.1", 0), McpFixture)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ with tempfile.TemporaryDirectory(prefix="graff-mcp-legacy-") as temp:+ workspace = Path(temp)+ (workspace / ".mcp.json").write_text(+ json.dumps(+ {+ "mcpServers": {+ "fixture": {+ "url": f"http://127.0.0.1:{server.server_port}/mcp"+ }+ }+ },+ separators=(",", ":"),+ ),+ encoding="utf-8",+ )+ settings = workspace / ".harness" / "settings.json"+ settings.parent.mkdir(mode=0o700)+ settings.write_text(+ '{"skills":{"codedbpro":false,"muonry":false}}\n',+ encoding="utf-8",+ )+ env = os.environ.copy()+ env.update(+ {+ "ANTHROPIC_API_KEY": "fixture-not-used",+ "GRAFF_BEHAVIOR_TRACE": "0",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_SMOLIFY": "1",+ "GRAFF_NO_TELEMETRY": "1",+ }+ )+ completed = subprocess.run(+ [str(graff), "--json", "--yolo", "--model", "claude"],+ cwd=workspace,+ env=env,+ input="",+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=20,+ check=False,+ )+ if completed.returncode != 0:+ raise AssertionError(+ f"graff exited {completed.returncode}\n"+ f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}"+ )+ if McpFixture.failure is not None:+ raise AssertionError("MCP fixture rejected a request") from McpFixture.failure+ assert len(McpFixture.requests) == 4, McpFixture.requests+ assert (+ f"[mcp:fixture] connected (mcp {NEGOTIATED_PROTOCOL}) — 1 tool(s)"+ in completed.stderr+ ), completed.stderr+ # Byte-identity guard across the three legacy requests: no _meta+ # anywhere, and Mcp-Session-Id echoed once minted (requests 3-4;+ # request 2 is the one that establishes it, so it has none yet).+ for i, req in enumerate(McpFixture.requests[1:], start=2):+ assert "_meta" not in req["raw"], (i, req)+ if i >= 3:+ assert req["session"] == SESSION_ID, (i, req)+ serialized = json.dumps(McpFixture.requests, separators=(",", ":"))+ assert str(workspace) not in serialized+ assert "fixture-not-used" not in serialized+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--graff", type=Path, default=Path("zig-out/bin/graff"))+ args = parser.parse_args()+ graff = args.graff.resolve()+ if not graff.is_file():+ parser.error(f"graff binary not found: {graff}")+ run(graff)+ print("Legacy fallback MCP E2E passed")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/test-mcp-streamable-http.py b/scripts/test-mcp-streamable-http.pyindex 8cc9fe2b..a17afb68 100644--- a/scripts/test-mcp-streamable-http.py+++ b/scripts/test-mcp-streamable-http.py@@ -1,5 +1,9 @@#!/usr/bin/env python3-"""Offline end-to-end smoke for Graff's Streamable HTTP MCP handshake."""+"""Offline end-to-end smoke for Graff's modern (2026-07-28) Streamable HTTP+MCP probe: a server that answers the first, handshake-free `tools/list`+request costs exactly one POST — no `initialize`, no+`notifications/initialized`. See test-mcp-legacy-fallback.py for the+backward-compat proof (a server that rejects the modern probe)."""from __future__ import annotations@@ -14,9 +18,12 @@ import threadingfrom typing import Any-LATEST_PROTOCOL = "2025-11-25"-NEGOTIATED_PROTOCOL = "2025-06-18"-SESSION_ID = "graff-mcp-fixture-session"+MODERN_PROTOCOL = "2026-07-28"+RESERVED_META_KEYS = (+ "io.modelcontextprotocol/protocolVersion",+ "io.modelcontextprotocol/clientInfo",+ "io.modelcontextprotocol/clientCapabilities",+)class McpFixture(BaseHTTPRequestHandler):@@ -28,19 +35,11 @@ class McpFixture(BaseHTTPRequestHandler):def log_message(self, _format: str, *_args: object) -> None:pass- def _respond(- self,- status: int,- body: bytes = b"",- content_type: str | None = None,- session_id: str | None = None,- ) -> None:+ def _respond(self, status: int, body: bytes = b"", content_type: str | None = None) -> None:self.send_response(status)self.send_header("Content-Length", str(len(body)))if content_type is not None:self.send_header("Content-Type", content_type)- if session_id is not None:- self.send_header("Mcp-Session-Id", session_id)self.end_headers()if body:self.wfile.write(body)@@ -63,55 +62,28 @@ class McpFixture(BaseHTTPRequestHandler):{"message": message,"protocol": self.headers.get("Mcp-Protocol-Version"),+ "method_header": self.headers.get("Mcp-Method"),+ "name_header": self.headers.get("Mcp-Name"),"session": self.headers.get("Mcp-Session-Id"),"raw": raw.decode("utf-8"),})- if ordinal == 1:- assert message["method"] == "initialize"- assert message["id"] == 1- assert message["params"]["protocolVersion"] == LATEST_PROTOCOL- assert self.headers.get("Mcp-Protocol-Version") == LATEST_PROTOCOL- assert self.headers.get("Mcp-Session-Id") is None- progress = (- 'data: {"jsonrpc":"2.0","method":"notifications/progress",'- '"params":{"progressToken":"fixture","progress":1}}\r\n\r\n'- )- initialized = json.dumps(- {- "jsonrpc": "2.0",- "id": 1,- "result": {- "protocolVersion": NEGOTIATED_PROTOCOL,- "capabilities": {"tools": {}},- "serverInfo": {"name": "fixture", "version": "1"},- },- },- separators=(",", ":"),- )- body = (progress + f"data: {initialized}\r\n\r\n").encode()- self._respond(200, body, "text/event-stream", SESSION_ID)- return-- assert self.headers.get("Mcp-Protocol-Version") == NEGOTIATED_PROTOCOL- assert self.headers.get("Mcp-Session-Id") == SESSION_ID- if ordinal == 2:- assert message == {- "jsonrpc": "2.0",- "method": "notifications/initialized",- "params": {},- }- self._respond(202)- return-- assert ordinal == 3+ assert ordinal == 1, f"expected exactly one request, saw a {ordinal}th"assert message["method"] == "tools/list"- assert message["id"] == 2+ assert message["id"] == 1+ meta = message["params"]["_meta"]+ for key in RESERVED_META_KEYS:+ assert key in meta, f"missing reserved _meta key {key}"+ assert meta["io.modelcontextprotocol/protocolVersion"] == MODERN_PROTOCOL+ assert self.headers.get("Mcp-Protocol-Version") == MODERN_PROTOCOL+ assert self.headers.get("Mcp-Method") == "tools/list"+ assert self.headers.get("Mcp-Session-Id") is None+body = json.dumps({"jsonrpc": "2.0",- "id": 2,+ "id": 1,"result": {"tools": [{@@ -196,9 +168,9 @@ def run(graff: Path) -> None:)if McpFixture.failure is not None:raise AssertionError("MCP fixture rejected a request") from McpFixture.failure- assert len(McpFixture.requests) == 3, McpFixture.requests+ assert len(McpFixture.requests) == 1, McpFixture.requestsassert (- f"[mcp:fixture] connected (mcp {NEGOTIATED_PROTOCOL}) — 1 tool(s)"+ f"[mcp:fixture] connected (mcp {MODERN_PROTOCOL}) — 1 tool(s)"in completed.stderr), completed.stderrserialized = json.dumps(McpFixture.requests, separators=(",", ":"))diff --git a/src/mcp.zig b/src/mcp.zigindex b017434b..e08d75ee 100644--- a/src/mcp.zig+++ b/src/mcp.zig@@ -366,11 +366,14 @@ pub const Registry = struct {const tools_before = tools.items.len;errdefer tools.shrinkRetainingCapacity(tools_before);- // Handshake. The server's reply tells us which revision it picked;- // record it (we proceed regardless — see `legacy_protocol`).- try initializeServer(server, a, a);-- const listed = try request(server, a, "{}", "tools/list");+ // Probe-then-fallback for HTTP (mcp_rpc.connectHttp), the unchanged+ // legacy handshake for stdio (mcp_rpc.connectStdio) — 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 => try mcp_rpc.connectStdio(server, a, a),+ };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;@@ -441,12 +444,18 @@ 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());- const resp = request(server, response_alloc, pw.writer.buffered(), "tools/call") catch |err| switch (err) {+ const resp = request(server, response_alloc, pw.writer.buffered(), "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+ // place (mcp_http never sends/stores one for a modern request),+ // so this cannot structurally fire for one — the explicit guard+ // is defense-in-depth against a future refactor resurrecting a+ // re-handshake loop against a server that has no `initialize`.error.McpSessionExpired => retry: {+ if (server.era != .legacy) return err;try initializeServer(server, response_alloc, reg.arena());- break :retry try request(server, response_alloc, pw.writer.buffered(), "tools/call");+ break :retry try request(server, response_alloc, pw.writer.buffered(), "tools/call", tool.original_name);},else => return err,};@@ -478,6 +487,12 @@ pub const Registry = struct {if (result_val != .object)return .{ .text = try out_alloc.dupe(u8, "MCP response result was not an object"), .is_error = true };const result = result_val.object;+ // resultType absent MUST read as "complete" (every server graff has+ // ever talked to). MRTR (inputRequests/inputResponses) is not+ // implemented — surface a clear error instead of silently returning+ // "" with is_error=false, which is what fell through here before.+ if (!mcp_protocol.resultIsComplete(result))+ return .{ .text = try out_alloc.dupe(u8, "MCP server returned an input_required result (MRTR); codegraff does not implement it"), .is_error = true };const is_error = if (result.get("isError")) |v| (v == .bool and v.bool) else false;// result.content is an array of {type:"text", text:...} blocks.diff --git a/src/mcp_http.zig b/src/mcp_http.zigindex 01fc8436..dd3bf7ec 100644--- a/src/mcp_http.zig+++ b/src/mcp_http.zig@@ -148,26 +148,27 @@ fn readSseResponse(gpa: Allocator, reader: *Io.Reader, expected_id: ?i64) !?[]u8return null;}+/// Load the OAuth bearer token, if any, into `arena`.+fn loadBearer(http: *HttpTransport, arena: Allocator) ?[]const u8 {+ const home = http.oauth_home orelse return null;+ return mcp_oauth.loadAccessToken(http.client.io, http.client.allocator, arena, home, http.url);+}+/// Perform one bounded Streamable HTTP POST, retaining the MCP session ID from/// initialize and accepting both JSON and SSE responses. A 202 with no body is-/// the normal response to a notification.-fn httpPostUnwatched(http: *HttpTransport, body: []const u8, protocol_version: []const u8, expected_id: ?i64) !?[]u8 {+/// the normal response to a notification. Legacy-shaped error handling only+/// (401/403 always fail, a stale session 404s, any other non-2xx errors and+/// discards the body) — a probe that must see a non-2xx body to classify the+/// server's era uses `probe` (below) instead, which duplicates the send+/// rather than share a Request/Response across a function return: the Zig+/// std.http.Client types are not documented as safe to move by value across+/// a boundary like that, and this is exactly the kind of subtle bug that+/// would be invisible until a real flaky connection hit it.+fn httpPostUnwatched(http: *HttpTransport, body: []const u8, meta: RequestMeta, expected_id: ?i64) !?[]u8 {var oauth_arena_state = std.heap.ArenaAllocator.init(http.client.allocator);defer oauth_arena_state.deinit();- const oauth_arena = oauth_arena_state.allocator();-- var extra: std.ArrayList(std.http.Header) = .empty;- defer extra.deinit(http.client.allocator);- try extra.appendSlice(http.client.allocator, http.headers);- if (http.oauth_home) |home| if (mcp_oauth.loadAccessToken(http.client.io, http.client.allocator, oauth_arena, home, http.url)) |token| {- try extra.append(http.client.allocator, .{- .name = "authorization",- .value = try std.fmt.allocPrint(oauth_arena, "Bearer {s}", .{token}),- });- };- try extra.append(http.client.allocator, .{ .name = "accept", .value = "application/json, text/event-stream" });- try extra.append(http.client.allocator, .{ .name = "mcp-protocol-version", .value = protocol_version });- if (http.session_id) |session_id| try extra.append(http.client.allocator, .{ .name = "mcp-session-id", .value = session_id });+ const bearer = loadBearer(http, oauth_arena_state.allocator());+ const extra = try buildHeaders(oauth_arena_state.allocator(), http, meta, bearer);var req = try http.client.request(.POST, try std.Uri.parse(http.url), .{.redirect_behavior = .unhandled,@@ -176,7 +177,7 @@ fn httpPostUnwatched(http: *HttpTransport, body: []const u8, protocol_version: [.accept_encoding = .omit,.user_agent = .{ .override = "codegraff-mcp/1" },},- .extra_headers = extra.items,+ .extra_headers = extra,});defer req.deinit();errdefer {@@ -206,13 +207,19 @@ fn httpPostUnwatched(http: *HttpTransport, body: []const u8, protocol_version: [return error.McpHttpStatus;}- var header_it = response.head.iterateHeaders();- while (header_it.next()) |header| {- if (std.ascii.eqlIgnoreCase(header.name, "mcp-session-id")) {- if (http.session_id) |session_id| {- if (!std.mem.eql(u8, session_id, header.value)) return error.McpSessionChanged;- } else {- http.session_id = try http.client.allocator.dupe(u8, header.value);+ // A modern request never sent Mcp-Session-Id (see buildHeaders) and never+ // mints one either: the stateless wire format has no session concept, so+ // a stray header from a dual-era server must not leak a session into+ // requests this era never asked for one on.+ if (!meta.modern) {+ var header_it = response.head.iterateHeaders();+ while (header_it.next()) |header| {+ if (std.ascii.eqlIgnoreCase(header.name, "mcp-session-id")) {+ if (http.session_id) |session_id| {+ if (!std.mem.eql(u8, session_id, header.value)) return error.McpSessionChanged;+ } else {+ http.session_id = try http.client.allocator.dupe(u8, header.value);+ }}}}@@ -246,8 +253,8 @@ const HttpPostDone = union(enum) {timeout,};-fn httpPostTask(http: *HttpTransport, body: []const u8, protocol_version: []const u8, expected_id: ?i64) anyerror!?[]u8 {- return httpPostUnwatched(http, body, protocol_version, expected_id);+fn httpPostTask(http: *HttpTransport, body: []const u8, meta: RequestMeta, expected_id: ?i64) anyerror!?[]u8 {+ return httpPostUnwatched(http, body, meta, expected_id);}fn httpPostTimeout(io: Io) void {@@ -269,10 +276,10 @@ fn cancelHttpPost(select: *Io.Select(HttpPostDone), allocator: Allocator) void {/// Race network I/O against a hard deadline. Cancellation unwinds the request,/// whose errdefer poisons the connection so a timed-out socket is never pooled.-pub fn post(http: *HttpTransport, body: []const u8, protocol_version: []const u8, expected_id: ?i64) !?[]u8 {+pub fn post(http: *HttpTransport, body: []const u8, meta: RequestMeta, expected_id: ?i64) !?[]u8 {var done_buf: [2]HttpPostDone = undefined;var select: Io.Select(HttpPostDone) = .init(http.client.io, &done_buf);- select.concurrent(.posted, httpPostTask, .{ http, body, protocol_version, expected_id }) catch+ select.concurrent(.posted, httpPostTask, .{ http, body, meta, expected_id }) catchreturn error.McpRequestTimedOut;select.concurrent(.timeout, httpPostTimeout, .{http.client.io}) catch {const only = select.await() catch |err| {@@ -302,6 +309,135 @@ pub fn post(http: *HttpTransport, body: []const u8, protocol_version: []const u8}}+/// A probe reply: the raw status and (if any) body, on ANY status — unlike+/// `post`, a probe never errors on a non-2xx status, since the whole point+/// is to hand the caller the error body so `mcp_protocol.classifyProbe` can+/// read it. `body` is `http.client.allocator`-owned; callers must free it.+pub const ProbeReply = struct { status: u16, body: ?[]u8 };++fn probeUnwatched(http: *HttpTransport, body: []const u8, meta: RequestMeta) !ProbeReply {+ var oauth_arena_state = std.heap.ArenaAllocator.init(http.client.allocator);+ defer oauth_arena_state.deinit();+ const bearer = loadBearer(http, oauth_arena_state.allocator());+ const extra = try buildHeaders(oauth_arena_state.allocator(), http, meta, bearer);++ var req = try http.client.request(.POST, try std.Uri.parse(http.url), .{+ .redirect_behavior = .unhandled,+ .headers = .{+ .content_type = .{ .override = "application/json" },+ .accept_encoding = .omit,+ .user_agent = .{ .override = "codegraff-mcp/1" },+ },+ .extra_headers = extra,+ });+ defer req.deinit();+ errdefer {+ if (req.connection) |connection| connection.closing = true;+ }++ req.transfer_encoding = .{ .content_length = body.len };+ var body_writer = try req.sendBodyUnflushed(&.{});+ try body_writer.writer.writeAll(body);+ try body_writer.end();+ try req.connection.?.flush();+ var response = try req.receiveHead(&.{});++ const status = @intFromEnum(response.head.status);+ // Auth failures aren't a version signal either way — surface them exactly+ // like `post` does so the existing OAuth flow still triggers.+ if (status == 401 or status == 403) {+ if (req.connection) |connection| connection.closing = true;+ return error.McpAuthenticationRequired;+ }+ // A probe never carries a session id (buildHeaders never sends one for a+ // modern request), so the legacy session-expiry branch does not apply.+ if (status < 200 or status >= 300) {+ if (req.connection) |connection| connection.closing = true;+ }++ if (response.head.content_length == 0) return .{ .status = status, .body = null };+ const is_sse = if (response.head.content_type) |content_type|+ std.ascii.startsWithIgnoreCase(content_type, "text/event-stream")+ else+ false;+ var transfer_buf: [4096]u8 = undefined;+ const reader = response.reader(&transfer_buf);+ if (is_sse) return .{ .status = status, .body = try readSseResponse(http.client.allocator, reader, null) };++ const response_buf = try http.client.allocator.alloc(u8, max_http_response);+ errdefer http.client.allocator.free(response_buf);+ var fixed = Io.Writer.fixed(response_buf);+ _ = reader.streamRemaining(&fixed) catch |err| switch (err) {+ error.WriteFailed => return error.McpResponseTooLarge,+ else => return err,+ };+ const len = fixed.buffered().len;+ if (len == 0) {+ http.client.allocator.free(response_buf);+ return .{ .status = status, .body = null };+ }+ return .{ .status = status, .body = try http.client.allocator.realloc(response_buf, len) };+}++const ProbeDone = union(enum) {+ probed: anyerror!ProbeReply,+ timeout,+};++fn probeTask(http: *HttpTransport, body: []const u8, meta: RequestMeta) anyerror!ProbeReply {+ return probeUnwatched(http, body, meta);+}++fn freeLateProbe(allocator: Allocator, result: anyerror!ProbeReply) void {+ if (result) |reply| {+ if (reply.body) |bytes| allocator.free(bytes);+ } else |_| {}+}++fn cancelProbe(select: *Io.Select(ProbeDone), allocator: Allocator) void {+ while (select.cancel()) |late| switch (late) {+ .probed => |result| freeLateProbe(allocator, result),+ .timeout => {},+ };+}++/// Attempt one modern (2026-07-28) request, bounded by the same deadline as+/// `post`. On success or a recognized-modern error, this is the entire+/// connect cost; on anything else, the caller falls back to the legacy+/// handshake (see mcp_rpc.connectHttp).+pub fn probe(http: *HttpTransport, body: []const u8, meta: RequestMeta) !ProbeReply {+ var done_buf: [2]ProbeDone = undefined;+ var select: Io.Select(ProbeDone) = .init(http.client.io, &done_buf);+ select.concurrent(.probed, probeTask, .{ http, body, meta }) catch+ return error.McpRequestTimedOut;+ select.concurrent(.timeout, httpPostTimeout, .{http.client.io}) catch {+ const only = select.await() catch |err| {+ cancelProbe(&select, http.client.allocator);+ return err;+ };+ select.cancelDiscard();+ return only.probed;+ };++ const first = select.await() catch |err| {+ cancelProbe(&select, http.client.allocator);+ return err;+ };+ switch (first) {+ .probed => |result| {+ select.cancelDiscard();+ return result;+ },+ .timeout => {+ while (select.cancel()) |late| switch (late) {+ .probed => |result| freeLateProbe(http.client.allocator, result),+ .timeout => {},+ };+ return error.McpRequestTimedOut;+ },+ }+}+test "remote URLs require HTTPS except on loopback" {try std.testing.expect(validRemoteUrl("https://api.mobbin.com/mcp"));try std.testing.expect(validRemoteUrl("http://localhost:3000/mcp"));diff --git a/src/mcp_rpc.zig b/src/mcp_rpc.zigindex afd248b9..b8cb0c6d 100644--- a/src/mcp_rpc.zig+++ b/src/mcp_rpc.zig@@ -1,9 +1,9 @@//! MCP JSON-RPC transport plumbing, split out of mcp.zig to keep it under//! the repo's 600-line cap: the per-server transport union/state, the-//! legacy `initialize` handshake, and raw request/notify framing over-//! either stdio or Streamable HTTP. mcp.zig keeps the higher-level-//! `Registry` (server lifecycle, tool discovery, tool dispatch) and aliases-//! `Server`/`Transport` from here.+//! legacy `initialize` handshake, era detection, and raw request/notify+//! framing over either stdio or Streamable HTTP. mcp.zig keeps the+//! higher-level `Registry` (server lifecycle, tool discovery, tool+//! dispatch) and aliases `Server`/`Transport` from here.const std = @import("std");const Io = std.Io;@@ -15,6 +15,7 @@ const mcp_stdio = @import("mcp_stdio.zig");const mcp_teardown = @import("mcp_teardown.zig");const legacy_protocol = mcp_protocol.legacy_protocol;+const modern_protocol = mcp_protocol.modern_protocol;pub const StdioTransport = struct {child: std.process.Child,@@ -27,12 +28,18 @@ pub const Transport = union(enum) {http: mcp_http.HttpTransport,};+/// A property of the server, not the request (versioning § Backward+/// Compatibility): determined once at connect and cached for the process+/// lifetime, never re-probed per tool call.+pub const Era = enum { unknown, modern, legacy };+pub const Server = struct {name: []const u8,transport: Transport,next_id: i64 = 1,initialized: bool = true,- /// Revision the server negotiated in its validated `initialize` response,+ era: Era = .unknown,+ /// Revision the server negotiated (legacy) or `modern_protocol` (modern),/// shown in `/mcp` so version skew is visible.protocol_version: []const u8 = "?",};@@ -53,7 +60,7 @@ pub fn initializeServer(server: *Server, response_alloc: Allocator, session_allo\\{"protocolVersion":"++ legacy_protocol ++\\","capabilities":{},"clientInfo":{"name":"simple-harness","version":"0.1"}}- , "initialize");+ , "initialize", null);const protocol_transport: mcp_protocol.Transport = switch (server.transport) {.stdio => .stdio,.http => .streamable_http,@@ -62,20 +69,30 @@ pub fn initializeServer(server: *Server, response_alloc: Allocator, session_alloserver.protocol_version = try session_alloc.dupe(u8, protocol_version);try notify(server, response_alloc, "notifications/initialized");server.initialized = true;+ server.era = .legacy;}/// JSON-RPC request/response over either transport. `params` is a raw JSON-/// object string. Result Values use `response_alloc`.-pub fn request(server: *Server, response_alloc: Allocator, params: []const u8, method: []const u8) !Value {+/// object string; `name` is the tool name for a `tools/call` (rendered as+/// `Mcp-Name` on a modern request) and null for everything else. Result+/// Values use `response_alloc`.+///+/// LOAD-BEARING: when `server.era != .modern`, `mcp_protocol.buildRequest`'s+/// `modern=false` path reproduces the exact pre-migration bytes — no `_meta`,+/// nothing added — so this is byte-identical to the client graff shipped+/// before 2026-07-28 for every server that has not been probed into the+/// modern era (today, that is every server).+pub fn request(server: *Server, response_alloc: Allocator, params: []const u8, method: []const u8, name: ?[]const u8) !Value {const id = server.next_id;server.next_id += 1;+ const modern = server.era == .modern;+ const body = try mcp_protocol.buildRequest(response_alloc, id, method, params, modern);switch (server.transport) {.stdio => |*stdio| {const w = &stdio.stdin_writer.interface;- try w.print(- \\{{"jsonrpc":"2.0","id":{d},"method":"{s}","params":{s}}}- ++ "\n", .{ id, method, params });+ try w.writeAll(body);+ try w.writeByte('\n');try w.flush();const r = &stdio.stdout_reader.interface;@@ -85,18 +102,22 @@ pub fn request(server: *Server, response_alloc: Allocator, params: []const u8, m}},.http => |*http| {- const body = try std.fmt.allocPrint(response_alloc,- \\{{"jsonrpc":"2.0","id":{d},"method":"{s}","params":{s}}}- , .{ id, method, params });- const protocol_version = if (std.mem.eql(u8, method, "initialize")) legacy_protocol else server.protocol_version;- const response_body = (try mcp_http.post(http, body, protocol_version, id)) orelse return error.BadMcpResponse;+ const protocol_version = if (modern) modern_protocol else if (std.mem.eql(u8, method, "initialize")) legacy_protocol else server.protocol_version;+ const response_body = (try mcp_http.post(http, body, .{+ .protocol_version = protocol_version,+ .method = method,+ .name = name,+ .modern = modern,+ }, id)) orelse return error.BadMcpResponse;defer http.client.allocator.free(response_body);return mcp_http.parseHttpResponse(response_alloc, response_body, id) orelse error.BadMcpResponse;},}}-/// Fire-and-forget JSON-RPC notification (no id, no response).+/// Fire-and-forget JSON-RPC notification (no id, no response). Only ever+/// sent on the legacy `initialize` handshake — the modern wire format has no+/// notifications/initialized to send.pub fn notify(server: *Server, response_alloc: Allocator, method: []const u8) !void {switch (server.transport) {.stdio => |*stdio| {@@ -110,9 +131,86 @@ pub fn notify(server: *Server, response_alloc: Allocator, method: []const u8) !vconst body = try std.fmt.allocPrint(response_alloc,\\{{"jsonrpc":"2.0","method":"{s}","params":{{}}}}, .{method});- if (try mcp_http.post(http, body, server.protocol_version, null)) |response_body| {+ if (try mcp_http.post(http, body, .{+ .protocol_version = server.protocol_version,+ .method = method,+ .modern = false,+ }, null)) |response_body| {http.client.allocator.free(response_body);}},}}++fn connectLegacy(server: *Server, a: Allocator, session_alloc: Allocator) !Value {+ try initializeServer(server, a, session_alloc); // sets server.era = .legacy+ return request(server, a, "{}", "tools/list", null);+}++/// Connect a stdio server. Always legacy today — the `server/discover`+/// probe lands gated behind `GRAFF_MCP_PROBE` in a later commit; with the+/// gate off (the default), this is byte-identical to graff's pre-migration+/// behavior.+pub fn connectStdio(server: *Server, a: Allocator, session_alloc: Allocator) !Value {+ return connectLegacy(server, a, session_alloc);+}++/// Connect a Streamable HTTP server: attempt a modern (2026-07-28)+/// `tools/list` first — it doubles as the discovery call graff needs+/// anyway, so a modern server costs one POST where the legacy handshake+/// costs three. Falls back to the legacy `initialize` ->+/// `notifications/initialized` -> `tools/list` handshake on anything that+/// is not a recognized modern error (versioning § Backward Compatibility).+/// See mcp_protocol.classifyProbe for the exact classification rules.+pub fn connectHttp(server: *Server, a: Allocator, session_alloc: Allocator) !Value {+ return connectHttpAttempt(server, a, session_alloc, false);+}++fn connectHttpAttempt(server: *Server, a: Allocator, session_alloc: Allocator, retried: bool) !Value {+ const http = &server.transport.http;+ const probe_id = server.next_id;+ server.next_id += 1;+ const probe_body = try mcp_protocol.buildRequest(a, probe_id, "tools/list", "{}", true);+ const reply = try mcp_http.probe(http, probe_body, .{+ .protocol_version = modern_protocol,+ .method = "tools/list",+ .modern = true,+ });+ defer if (reply.body) |b| http.client.allocator.free(b);++ if (reply.status >= 200 and reply.status < 300) {+ const parsed = (if (reply.body) |b| mcp_http.parseHttpResponse(a, b, probe_id) else null) orelse return error.BadMcpResponse;+ server.era = .modern;+ server.protocol_version = try session_alloc.dupe(u8, modern_protocol);+ server.initialized = true;+ return parsed;+ }++ switch (mcp_protocol.classifyProbe(a, reply.body orelse &.{})) {+ .legacy => return connectLegacy(server, a, session_alloc),+ // -32020/-32021: graff's own request was malformed. That is a graff+ // bug, not a version mismatch — surface it loudly rather than+ // falling back and hiding it behind a legacy handshake that will+ // just fail differently.+ .modern => return error.McpModernRequestRejected,+ .incompatible => return error.McpIncompatibleProtocolVersion,+ .unsupported_version => |supported| {+ var has_modern = false;+ for (supported) |v| if (v == .string and std.mem.eql(u8, v.string, modern_protocol)) {+ has_modern = true;+ };+ if (has_modern) {+ // We asked for modern_protocol and the server both rejected+ // it AND claims to support it — contradictory, but retry+ // once (single-shot: this is idempotent, so a second+ // identical answer means give up, not loop).+ if (!retried) return connectHttpAttempt(server, a, session_alloc, true);+ return error.McpIncompatibleProtocolVersion;+ }+ // No overlap with modern_protocol, but classifyProbe only+ // returns this variant when `supported` overlaps something we+ // speak — so it must be a legacy revision: dual-era server.+ return connectLegacy(server, a, session_alloc);+ },+ }+}