graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Accept gzip on MCP HTTP so catalogs shrink on the wire
Cursor Agent4589a70c188e
diff --git a/docs/adr/0043-reuse-warmed-tls-on-known-networks.md b/docs/adr/0043-reuse-warmed-tls-on-known-networks.mdindex b7835aea..f33fd21c 100644--- a/docs/adr/0043-reuse-warmed-tls-on-known-networks.md+++ b/docs/adr/0043-reuse-warmed-tls-on-known-networks.md@@ -27,10 +27,15 @@ ADR 0002 (xAI WS full-resend), 0009/0011/0028 (prompt-cache keys), and 0035- WS→SSE fallback keeps the Agent's prewarmed HTTP pool (`postStream`). Do notintroduce a fresh client on that latch: WS never used the HTTP pool, and anew TLS would be strictly more expensive.+- MCP Streamable HTTP advertises the std client's default Accept-Encoding+ (gzip/deflate) and decompresses Content-Encoding. Do not omit it: a tools/list+ catalog is the fat payload on that network, and provider POST already accepts+ compression.## ConsequencesA modern MCP connect plus the next list is one TCP accept on keep-alive.-WSS reconnects skip the CA disk walk. Revisit only if a shared `std.http.Client`-is shown unsafe for the concurrent initialized+list pair, or if a host CA-rotation must be picked up mid-process without restart.+WSS reconnects skip the CA disk walk. MCP catalogs can travel gzip-compressed.+Revisit only if a shared `std.http.Client` is shown unsafe for the concurrent+initialized+list pair, a host CA rotation must be picked up mid-process without+restart, or a server is broken by Accept-Encoding.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex d5bfacfa..13abb757 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -52,7 +52,7 @@ record only when you need the evidence or the edge cases.| [0039](0039-local-tools-are-project-scripts.md) | Agent-authored local tools are project scripts under `.graff/tools/`; skills stay instructions. Runtime catalog extras, not `schema.effectiveRootSpecs`. || [0040](0040-codedb-stays-when-licensed.md) | Ordinary reads use native `codedb` / `read_file`; codedb-pro is extra search, not the default reader. || [0041](0041-tui-is-an-acp-client.md) | The fullscreen TUI is an in-process ACP client: session/prompt in, session/update thought/tool/text out. No child `graff acp`. |-| [0043](0043-reuse-warmed-tls-on-known-networks.md) | Reuse warmed TLS: MCP probe/initialized stay on the persistent HTTP client; WSS CA is scanned once per process; WS→SSE keeps the prewarmed pool. |+| [0043](0043-reuse-warmed-tls-on-known-networks.md) | Reuse warmed TLS: MCP probe/initialized stay on the persistent HTTP client; WSS CA is scanned once per process; WS→SSE keeps the prewarmed pool; MCP HTTP accepts gzip. |## When to write onediff --git a/src/mcp_http.zig b/src/mcp_http.zigindex dd3bf7ec..80489e7d 100644--- a/src/mcp_http.zig+++ b/src/mcp_http.zig@@ -174,7 +174,6 @@ fn httpPostUnwatched(http: *HttpTransport, body: []const u8, meta: RequestMeta,.redirect_behavior = .unhandled,.headers = .{.content_type = .{ .override = "application/json" },- .accept_encoding = .omit,.user_agent = .{ .override = "codegraff-mcp/1" },},.extra_headers = extra,@@ -224,28 +223,7 @@ fn httpPostUnwatched(http: *HttpTransport, body: []const u8, meta: RequestMeta,}}- if (response.head.content_length == 0) return 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 readSseResponse(http.client.allocator, reader, expected_id);-- 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 null;- }- return try http.client.allocator.realloc(response_buf, len);+ return readResponseBody(http.client.allocator, &response, expected_id);}const HttpPostDone = union(enum) {@@ -325,7 +303,6 @@ fn probeUnwatched(http: *HttpTransport, body: []const u8, meta: RequestMeta) !Pr.redirect_behavior = .unhandled,.headers = .{.content_type = .{ .override = "application/json" },- .accept_encoding = .omit,.user_agent = .{ .override = "codegraff-mcp/1" },},.extra_headers = extra,@@ -355,17 +332,35 @@ fn probeUnwatched(http: *HttpTransport, body: []const u8, meta: RequestMeta) !Prif (req.connection) |connection| connection.closing = true;}- if (response.head.content_length == 0) return .{ .status = status, .body = null };+ return .{ .status = status, .body = try readResponseBody(http.client.allocator, &response, null) };+}++fn decompressWindow(gpa: Allocator, encoding: std.http.ContentEncoding) ![]u8 {+ return switch (encoding) {+ .identity => &.{},+ .zstd => gpa.alloc(u8, std.compress.zstd.default_window_len),+ .deflate, .gzip => gpa.alloc(u8, std.compress.flate.max_window_len),+ .compress => error.UnsupportedCompressionMethod,+ };+}++/// Decode the HTTP body, honoring Content-Encoding (gzip/deflate/zstd).+/// Callers used to omit Accept-Encoding so catalogs crossed the wire raw.+fn readResponseBody(gpa: Allocator, response: *std.http.Client.Response, expected_id: ?i64) !?[]u8 {+ if (response.head.content_length == 0) return null;const is_sse = if (response.head.content_type) |content_type|std.ascii.startsWithIgnoreCase(content_type, "text/event-stream")elsefalse;+ const window = try decompressWindow(gpa, response.head.content_encoding);+ defer if (window.len > 0) gpa.free(window);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) };+ var decompress: std.http.Decompress = undefined;+ const reader = response.readerDecompressing(&transfer_buf, &decompress, window);+ if (is_sse) return readSseResponse(gpa, reader, expected_id);- const response_buf = try http.client.allocator.alloc(u8, max_http_response);- errdefer http.client.allocator.free(response_buf);+ const response_buf = try gpa.alloc(u8, max_http_response);+ errdefer gpa.free(response_buf);var fixed = Io.Writer.fixed(response_buf);_ = reader.streamRemaining(&fixed) catch |err| switch (err) {error.WriteFailed => return error.McpResponseTooLarge,@@ -373,10 +368,10 @@ fn probeUnwatched(http: *HttpTransport, body: []const u8, meta: RequestMeta) !Pr};const len = fixed.buffered().len;if (len == 0) {- http.client.allocator.free(response_buf);- return .{ .status = status, .body = null };+ gpa.free(response_buf);+ return null;}- return .{ .status = status, .body = try http.client.allocator.realloc(response_buf, len) };+ return try gpa.realloc(response_buf, len);}const ProbeDone = union(enum) {diff --git a/src/net_efficiency_test.zig b/src/net_efficiency_test.zigindex 7524dab8..c7f401a9 100644--- a/src/net_efficiency_test.zig+++ b/src/net_efficiency_test.zig@@ -7,7 +7,9 @@ const builtin = @import("builtin");const Io = std.Io;const http_warm = @import("http_warm.zig");+const mcp_http = @import("mcp_http.zig");const mcp_lifecycle = @import("mcp_lifecycle.zig");+const mcp_protocol = @import("mcp_protocol.zig");const mcp_rpc = @import("mcp_rpc.zig");test "WSS CA bundle is scanned from disk at most once per process" {@@ -131,3 +133,112 @@ test "MCP modern connect + next list reuse one TCP connection" {try std.testing.expectEqual(@as(u8, 1), accepts.load(.monotonic));try std.testing.expectEqual(@as(u8, 2), posts.load(.monotonic));}++test "MCP HTTP advertises gzip and decompresses a smaller wire body" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const gpa = std.testing.allocator;+ const io = std.testing.io;++ var plain_w: Io.Writer.Allocating = .init(gpa);+ defer plain_w.deinit();+ try plain_w.writer.writeAll("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"tools\":[");+ for (0..40) |i| {+ if (i != 0) try plain_w.writer.writeByte(',');+ try plain_w.writer.print(+ "{{\"name\":\"tool_{d}\",\"description\":\"search the workspace and return matching files\",\"inputSchema\":{{\"type\":\"object\",\"properties\":{{\"q\":{{\"type\":\"string\"}}}}}}}}",+ .{i},+ );+ }+ try plain_w.writer.writeAll("],\"supportedVersions\":[\"2026-07-28\"]}}");+ const plain = plain_w.writer.buffered();++ const gz = try gzipAlloc(gpa, plain);+ defer gpa.free(gz);+ try std.testing.expect(gz.len < plain.len);++ var saw_accept_gzip = std.atomic.Value(bool).init(false);+ var wire_len = std.atomic.Value(usize).init(0);++ var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");+ var listener = try std.Io.net.IpAddress.listen(&addr, io, .{});+ defer listener.deinit(io);+ const Srv = struct {+ fn run(+ io_: Io,+ listener_: *std.Io.net.Server,+ gz_: []const u8,+ saw: *std.atomic.Value(bool),+ wire: *std.atomic.Value(usize),+ ) void {+ const stream = listener_.accept(io_) catch return;+ defer stream.close(io_);+ var rbuf: [4096]u8 = undefined;+ var rd = std.Io.net.Stream.Reader.init(stream, io_, &rbuf);+ const r = &rd.interface;+ var content_len: usize = 0;+ var accept_enc: bool = false;+ while (true) {+ const line = (r.takeDelimiter('\n') catch return) orelse return;+ if (line.len == 0 or (line.len == 1 and line[0] == '\r')) break;+ if (std.ascii.startsWithIgnoreCase(line, "accept-encoding:") and+ std.mem.indexOf(u8, line, "gzip") != null) accept_enc = true;+ if (std.ascii.startsWithIgnoreCase(line, "content-length:")) {+ const raw = if (line[line.len - 1] == '\r') line[0 .. line.len - 1] else line;+ content_len = std.fmt.parseInt(usize, std.mem.trim(u8, raw["content-length:".len..], " \t"), 10) catch 0;+ }+ }+ if (content_len > 0) _ = r.take(content_len) catch {};+ saw.store(accept_enc, .release);+ wire.store(gz_.len, .release);+ var wbuf: [1024]u8 = undefined;+ var wr = std.Io.net.Stream.Writer.init(stream, io_, &wbuf);+ wr.interface.print(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Encoding: gzip\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n",+ .{gz_.len},+ ) catch return;+ wr.interface.writeAll(gz_) catch return;+ wr.interface.flush() catch {};+ }+ };+ var fut = io.async(Srv.run, .{ io, &listener, gz, &saw_accept_gzip, &wire_len });+ defer fut.await(io);++ var url_buf: [64]u8 = undefined;+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/mcp", .{listener.socket.address.getPort()});+ var http: mcp_http.HttpTransport = .{+ .url = url,+ .client = .{ .allocator = gpa, .io = io },+ };+ defer http.client.deinit();+ const body = (try mcp_http.post(&http, "{}", .{+ .protocol_version = mcp_protocol.modern_protocol,+ .method = "tools/list",+ .modern = true,+ }, 1)) orelse return error.TestUnexpectedResult;+ defer gpa.free(body);++ try std.testing.expect(saw_accept_gzip.load(.acquire));+ try std.testing.expectEqual(gz.len, wire_len.load(.acquire));+ try std.testing.expect(wire_len.load(.acquire) < plain.len);+ try std.testing.expectEqualStrings(plain, body);+}++test "MCP HTTP no longer omits Accept-Encoding" {+ const src = @embedFile("mcp_http.zig");+ const omit = "accept_encoding = " ++ ".omit";+ try std.testing.expect(std.mem.indexOf(u8, src, omit) == null);+ try std.testing.expect(std.mem.indexOf(u8, src, "readerDecompressing") != null);+}++fn gzipAlloc(gpa: std.mem.Allocator, plain: []const u8) ![]u8 {+ var out_buf: [4096]u8 = undefined;+ var out: Io.Writer = .fixed(&out_buf);+ const window = try gpa.alloc(u8, std.compress.flate.max_window_len);+ defer gpa.free(window);+ const c = try gpa.create(std.compress.flate.Compress);+ defer gpa.destroy(c);+ c.* = try std.compress.flate.Compress.init(&out, window, .gzip, .default);+ try c.writer.writeAll(plain);+ try c.finish();+ return gpa.dupe(u8, out.buffered());+}