Skip to content

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

Python

Fix MCP authorization review blockers

yxlyx1f33ba754949
diff --git a/src/agent.zig b/src/agent.zig
index 7bbe573d..c4e3966b 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -652,7 +652,7 @@ test "lazy root tool catalogs preserve MCP tools across provider formats" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
- var registry = mcp.Registry.empty(std.testing.allocator, std.testing.io, "");
+ var registry = mcp.Registry.empty(std.testing.allocator, std.testing.io);
defer registry.deinit();
var connected = [_]mcp.Tool{.{
.server_index = 0,
diff --git a/src/main.zig b/src/main.zig
index 0d2cd2b1..951a7eb4 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -545,146 +545,7 @@ const workflow = @import("workflow.zig");
const exec = @import("exec.zig");
// ── Unit tests (`zig build test`) ──────────────────────────────────────────
-test "incremental markdown streaming renders like renderMdLine" {
- // style is the empty default in tests, so styled output == de-marked text.
- var aw: Io.Writer.Allocating = .init(std.testing.allocator);
- defer aw.deinit();
- var a: Agent = .{
- .gpa = std.testing.allocator,
- .arena = std.testing.allocator,
- .io = undefined,
- .client = undefined,
- .provider = undefined,
- .messages = undefined,
- .sub = false,
- .label = "test",
- .out = &aw.writer,
- };
- defer a.md_buf.deinit(std.testing.allocator);
- defer a.md_word.deinit(std.testing.allocator);
- defer {
- for (a.md_table.items) |r| std.testing.allocator.free(r);
- a.md_table.deinit(std.testing.allocator);
- }
-
- // Prose is visible word-by-word, before any newline arrives (the
- // word in flight is held for wrap decisions).
- a.streamMarkdown("Hey! I'm her");
- try std.testing.expectEqualStrings("Hey! I'm ", aw.writer.buffered());
- a.streamMarkdown("e and ready\n");
- try std.testing.expectEqualStrings("Hey! I'm here and ready\n", aw.writer.buffered());
- aw.clearRetainingCapacity();
-
- // Bullets stream too: marker styled up front, text word-by-word, and a
- // split **bold** span styles eagerly (markers dropped as in renderInline).
- a.streamMarkdown("- has **bo");
- try std.testing.expectEqualStrings("• has ", aw.writer.buffered());
- a.streamMarkdown("ld** spans\n");
- try std.testing.expectEqualStrings("• has bold spans\n", aw.writer.buffered());
- aw.clearRetainingCapacity();
-
- // Numbered/task/nested items, headings, quotes, and inline code.
- a.streamMarkdown("12) **Immediately:** point\n## Title\nuse `zig build` here\n- [ ] ship it\n - nested\n> warning\n");
- try std.testing.expectEqualStrings("12) Immediately: point\n◆ Title\nuse zig build here\n☐ ship it\n ◦ nested\n│ warning\n", aw.writer.buffered());
- aw.clearRetainingCapacity();
-
- // Fences: open/close render as labeled dim rules, body streams unprefixed.
- a.streamMarkdown("```zig\nconst x = 1;\n```\nafter\n");
- try std.testing.expectEqualStrings("── zig " ++ util.repeatBytes("─", 33) ++ "\nconst x = 1;\n" ++ util.repeatBytes("─", 40) ++ "\nafter\n", aw.writer.buffered());
- try std.testing.expect(!a.md_fence);
- aw.clearRetainingCapacity();
-
- // Horizontal rule renders at line end.
- a.streamMarkdown("---\n");
- try std.testing.expectEqualStrings("────────────\n", aw.writer.buffered());
- aw.clearRetainingCapacity();
-
- // Tables buffer until the first non-row line, then render aligned:
- // column widths from the widest cell, header above a ─┼─ rule.
- a.streamMarkdown("| Item | Desc |\n| --- | --- |\n| 1 | Inspect files |\n");
- try std.testing.expectEqualStrings("", aw.writer.buffered()); // still buffering
- a.streamMarkdown("| 22 | Edit |\ndone\n");
- try std.testing.expectEqualStrings("Item │ Desc\n" ++
- "─────┼──────────────\n" ++
- "1 │ Inspect files\n" ++
- "22 │ Edit\n" ++
- "done\n", aw.writer.buffered());
- aw.clearRetainingCapacity();
-
- // A table pending at stream end flushes from the tail path.
- a.streamMarkdown("| x | y |");
- a.flushStreamTail();
- try std.testing.expectEqualStrings("x │ y\n", aw.writer.buffered());
- aw.clearRetainingCapacity();
-
- // Stream tail: a partial prose line flushes whatever is pending.
- a.streamMarkdown("tail without newline");
- a.flushStreamTail();
- try std.testing.expectEqualStrings("tail without newline", aw.writer.buffered());
- aw.clearRetainingCapacity();
-
- // Long lines wrap at the terminal edge on word boundaries; bullet
- // continuations align under the text (hanging indent).
- a.md_width = 12; // pinned for the line — mdFinishLine re-reads after
- a.streamMarkdown("- alpha beta gamma\n");
- try std.testing.expectEqualStrings("• alpha beta\n gamma\n", aw.writer.buffered());
- aw.clearRetainingCapacity();
-
- // Plain prose wraps at column 0; the break replaces the joining space.
- a.md_width = 10;
- a.streamMarkdown("word1 word2 word3\n");
- try std.testing.expectEqualStrings("word1 \nword2 \nword3\n", aw.writer.buffered());
- aw.clearRetainingCapacity();
-
- // A word too wide for any line is not torn — the terminal wraps it.
- a.md_width = 6;
- a.streamMarkdown("abc defghijklm\n");
- try std.testing.expectEqualStrings("abc defghijklm\n", aw.writer.buffered());
-}
-
test { // pull in tests from imported modules (mcp.zig)
_ = mcp;
-}
-
-test "/bash slash command runs the bash tool and frees its gpa-allocated result" {
- // Regression guard for PR #38: the /bash slash handler routes through execTool, whose result.text is gpa-owned (NOT arena-owned — every other
- // caller frees it). Forgetting `defer root.gpa.free(result.text)` in handleCommand leaks on every /bash call; std.testing.allocator catches it here.
- const gpa = std.testing.allocator;
- const io = std.testing.io;
-
- var arena_state = std.heap.ArenaAllocator.init(gpa);
- defer arena_state.deinit();
- const arena = arena_state.allocator();
-
- var client: std.http.Client = .{ .allocator = gpa, .io = io };
- defer client.deinit();
- prewarmCaBundle(&client, gpa, io);
-
- var root: Agent = .{
- .gpa = gpa,
- .arena = arena,
- .io = io,
- .client = &client,
- .provider = .{
- .id = "test",
- .kind = .openai,
- .auth = .bearer,
- .url = "",
- .api_key = "",
- .model = "m",
- .context = 100_000,
- },
- .messages = std.json.Array.init(arena),
- .sub = false,
- .label = "test",
- .out = null,
- };
- var keys: Keys = .{ .values = @splat(null) };
- var aw: Io.Writer.Allocating = .init(gpa);
- defer aw.deinit();
- defer root.tools_used.deinit(gpa);
- try handleCommand(&root, &keys, arena, "/bash echo leak-guard-XYZ", &aw.writer);
-
- const written = aw.writer.buffered();
- try std.testing.expect(std.mem.indexOf(u8, written, "leak-guard-XYZ") != null);
+ _ = @import("main_test.zig");
}
diff --git a/src/main_test.zig b/src/main_test.zig
new file mode 100644
index 00000000..6bff93a3
--- /dev/null
+++ b/src/main_test.zig
@@ -0,0 +1,154 @@
+//! Focused regressions for incremental markdown streaming and `/bash` result ownership.
+
+const std = @import("std");
+const Io = std.Io;
+const Agent = @import("agent.zig").Agent;
+const Keys = @import("provider.zig").Keys;
+const util = @import("util.zig");
+const handleCommand = @import("main.zig").handleCommand;
+
+fn prewarmCaBundle(client: *std.http.Client, gpa: std.mem.Allocator, io: Io) void {
+ const now = Io.Clock.real.now(io);
+ client.ca_bundle.rescan(gpa, io, now) catch return;
+ client.now = now;
+}
+
+test "incremental markdown streaming renders like renderMdLine" {
+ // style is the empty default in tests, so styled output == de-marked text.
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = std.testing.allocator,
+ .io = undefined,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = &aw.writer,
+ };
+ defer a.md_buf.deinit(std.testing.allocator);
+ defer a.md_word.deinit(std.testing.allocator);
+ defer {
+ for (a.md_table.items) |r| std.testing.allocator.free(r);
+ a.md_table.deinit(std.testing.allocator);
+ }
+
+ // Prose is visible word-by-word, before any newline arrives (the
+ // word in flight is held for wrap decisions).
+ a.streamMarkdown("Hey! I'm her");
+ try std.testing.expectEqualStrings("Hey! I'm ", aw.writer.buffered());
+ a.streamMarkdown("e and ready\n");
+ try std.testing.expectEqualStrings("Hey! I'm here and ready\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // Bullets stream too: marker styled up front, text word-by-word, and a
+ // split **bold** span styles eagerly (markers dropped as in renderInline).
+ a.streamMarkdown("- has **bo");
+ try std.testing.expectEqualStrings("• has ", aw.writer.buffered());
+ a.streamMarkdown("ld** spans\n");
+ try std.testing.expectEqualStrings("• has bold spans\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // Numbered/task/nested items, headings, quotes, and inline code.
+ a.streamMarkdown("12) **Immediately:** point\n## Title\nuse `zig build` here\n- [ ] ship it\n - nested\n> warning\n");
+ try std.testing.expectEqualStrings("12) Immediately: point\n◆ Title\nuse zig build here\n☐ ship it\n ◦ nested\n│ warning\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // Fences: open/close render as labeled dim rules, body streams unprefixed.
+ a.streamMarkdown("```zig\nconst x = 1;\n```\nafter\n");
+ try std.testing.expectEqualStrings("── zig " ++ util.repeatBytes("─", 33) ++ "\nconst x = 1;\n" ++ util.repeatBytes("─", 40) ++ "\nafter\n", aw.writer.buffered());
+ try std.testing.expect(!a.md_fence);
+ aw.clearRetainingCapacity();
+
+ // Horizontal rule renders at line end.
+ a.streamMarkdown("---\n");
+ try std.testing.expectEqualStrings("────────────\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // Tables buffer until the first non-row line, then render aligned:
+ // column widths from the widest cell, header above a ─┼─ rule.
+ a.streamMarkdown("| Item | Desc |\n| --- | --- |\n| 1 | Inspect files |\n");
+ try std.testing.expectEqualStrings("", aw.writer.buffered()); // still buffering
+ a.streamMarkdown("| 22 | Edit |\ndone\n");
+ try std.testing.expectEqualStrings("Item │ Desc\n" ++
+ "─────┼──────────────\n" ++
+ "1 │ Inspect files\n" ++
+ "22 │ Edit\n" ++
+ "done\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // A table pending at stream end flushes from the tail path.
+ a.streamMarkdown("| x | y |");
+ a.flushStreamTail();
+ try std.testing.expectEqualStrings("x │ y\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // Stream tail: a partial prose line flushes whatever is pending.
+ a.streamMarkdown("tail without newline");
+ a.flushStreamTail();
+ try std.testing.expectEqualStrings("tail without newline", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // Long lines wrap at the terminal edge on word boundaries; bullet
+ // continuations align under the text (hanging indent).
+ a.md_width = 12; // pinned for the line — mdFinishLine re-reads after
+ a.streamMarkdown("- alpha beta gamma\n");
+ try std.testing.expectEqualStrings("• alpha beta\n gamma\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // Plain prose wraps at column 0; the break replaces the joining space.
+ a.md_width = 10;
+ a.streamMarkdown("word1 word2 word3\n");
+ try std.testing.expectEqualStrings("word1 \nword2 \nword3\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // A word too wide for any line is not torn — the terminal wraps it.
+ a.md_width = 6;
+ a.streamMarkdown("abc defghijklm\n");
+ try std.testing.expectEqualStrings("abc defghijklm\n", aw.writer.buffered());
+}
+
+test "/bash slash command runs the bash tool and frees its gpa-allocated result" {
+ // Regression guard for PR #38: the /bash slash handler routes through execTool, whose result.text is gpa-owned (NOT arena-owned — every other
+ // caller frees it). Forgetting `defer root.gpa.free(result.text)` in handleCommand leaks on every /bash call; std.testing.allocator catches it here.
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ prewarmCaBundle(&client, gpa, io);
+
+ var root: Agent = .{
+ .gpa = gpa,
+ .arena = arena,
+ .io = io,
+ .client = &client,
+ .provider = .{
+ .id = "test",
+ .kind = .openai,
+ .auth = .bearer,
+ .url = "",
+ .api_key = "",
+ .model = "m",
+ .context = 100_000,
+ },
+ .messages = std.json.Array.init(arena),
+ .sub = false,
+ .label = "test",
+ .out = null,
+ };
+ var keys: Keys = .{ .values = @splat(null) };
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ defer root.tools_used.deinit(gpa);
+ try handleCommand(&root, &keys, arena, "/bash echo leak-guard-XYZ", &aw.writer);
+
+ const written = aw.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, written, "leak-guard-XYZ") != null);
+}
diff --git a/src/mcp.zig b/src/mcp.zig
index f01200c0..da57c84a 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -11,11 +11,17 @@
//! registry-wide serialization is fine.
const std = @import("std");
-const builtin = @import("builtin");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
-const mcp_oauth = @import("mcp_oauth.zig");
+const mcp_http = @import("mcp_http.zig");
+const mcp_protocol = @import("mcp_protocol.zig");
+const mcp_stdio = @import("mcp_stdio.zig");
+
+const latest_protocol = mcp_protocol.latest_protocol;
+const rewriteOneOf = mcp_protocol.rewriteOneOf;
+const HttpTransport = mcp_http.HttpTransport;
+pub const validRemoteUrl = mcp_http.validRemoteUrl;
pub const Tool = struct {
server_index: usize,
@@ -24,135 +30,25 @@ pub const Tool = struct {
description: []const u8,
input_schema: Value, // arena-owned parsed JSON Schema
};
-
-/// Recursively rewrite the JSON Schema keyword `oneOf` to `anyOf` (graff's
-/// rewrite_one_of_to_any_of). OpenAI's tool-schema validator — including the
-/// chatgpt.com /codex/responses endpoint — rejects `oneOf` outright with
-/// "'oneOf' is not permitted"; `anyOf` is accepted by both OpenAI and
-/// Anthropic and is equivalent for the discriminated unions MCP servers emit
-/// in practice. When both keywords are present (rare, ambiguous to merge),
-/// the existing `anyOf` wins and `oneOf` is dropped. Runs once per tool at
-/// discovery, so the rendered tools JSON stays KV-cache-stable.
-fn rewriteOneOf(a: Allocator, v: *Value) Allocator.Error!void {
- switch (v.*) {
- .object => |*obj| {
- if (obj.get("oneOf")) |branches| {
- if (obj.get("anyOf") == null) try obj.put(a, "anyOf", branches);
- _ = obj.swapRemove("oneOf");
- }
- var it = obj.iterator();
- while (it.next()) |e| try rewriteOneOf(a, e.value_ptr);
- },
- .array => |*arr| for (arr.items) |*item| try rewriteOneOf(a, item),
- else => {},
- }
-}
-/// Latest MCP revision we advertise in `initialize`. MCP versions are dated
-/// (there is no "MCP 2.0"); negotiation is built in: the client sends the
-/// newest revision it supports and the server answers with that version or
-/// the newest *it* supports — we accept whatever it picks because the entire
-/// surface we use (initialize / notifications/initialized / tools/list /
-/// tools/call with text content blocks) is identical from 2024-11-05 through
-/// 2025-11-25. Everything 2025-11-25 added (tasks, extensions, URL-mode
-/// elicitation, sampling tool-calls) is opt-in via capabilities, and we
-/// declare `capabilities:{}`, so servers can't expect any of it from us.
-/// Streamable HTTP additionally carries this revision in each request after
-/// initialization. Responses may be JSON or one or more SSE `data:` events.
-const latest_protocol = "2025-11-25";
-const max_http_response = 1 << 20;
pub const smolify_url = "https://app.smol.ly/mcp";
-const shutdown_grace = std.Io.Duration.fromMilliseconds(100);
-
-fn waitChild(child: *std.process.Child, io: Io) std.process.Child.WaitError!std.process.Child.Term {
- return child.wait(io);
-}
-
-fn shutdownDeadline(io: Io) void {
- io.sleep(shutdown_grace, .awake) catch {};
-}
-
-/// Signal a normal stdio-server shutdown with EOF, but never let a server's
-/// SIGTERM handler stall the CLI. A child that does not exit within the grace
-/// window is force-killed and reaped so one-shot/SDK callers do not inherit
-/// teardown latency or zombies.
-fn stopChild(io: Io, child: *std.process.Child) void {
- if (child.id == null) return;
- if (child.stdin) |stdin| {
- stdin.close(io);
- child.stdin = null;
- }
-
- const Done = union(enum) { exited: std.process.Child.WaitError!std.process.Child.Term, deadline: void };
- var done_buf: [2]Done = undefined;
- var sel: Io.Select(Done) = .init(io, &done_buf);
- sel.concurrent(.exited, waitChild, .{ child, io }) catch {
- child.kill(io);
- return;
- };
- sel.concurrent(.deadline, shutdownDeadline, .{io}) catch {
- _ = sel.await() catch {};
- sel.cancelDiscard();
- return;
- };
- const first = sel.await() catch {
- sel.cancelDiscard();
- child.kill(io);
- return;
- };
- sel.cancelDiscard();
- if (first == .exited or child.id == null) return;
-
- switch (builtin.os.tag) {
- .windows => child.kill(io),
- .wasi => unreachable,
- else => {
- std.posix.kill(child.id.?, .KILL) catch {};
- _ = child.wait(io) catch child.kill(io);
- },
- }
-}
-
const StdioTransport = struct {
child: std.process.Child,
stdin_writer: Io.File.Writer,
stdout_reader: Io.File.Reader,
};
-const HttpTransport = struct {
- url: []const u8,
- client: std.http.Client,
- headers: []const std.http.Header = &.{},
- oauth_home: ?[]const u8 = null,
- session_id: ?[]const u8 = null,
-};
-
const Transport = union(enum) {
stdio: StdioTransport,
http: HttpTransport,
};
-fn validRemoteUri(uri: std.Uri) bool {
- if (uri.host == null) return false;
- if (std.ascii.eqlIgnoreCase(uri.scheme, "https")) return true;
- if (!std.ascii.eqlIgnoreCase(uri.scheme, "http")) return false;
- const host = uri.host.?.percent_encoded;
- return std.ascii.eqlIgnoreCase(host, "localhost") or
- std.mem.eql(u8, host, "127.0.0.1") or
- std.mem.eql(u8, host, "[::1]") or
- std.mem.eql(u8, host, "::1");
-}
-
-pub fn validRemoteUrl(url: []const u8) bool {
- return validRemoteUri(std.Uri.parse(url) catch return false);
-}
-
const Server = struct {
name: []const u8,
transport: Transport,
next_id: i64 = 1,
- /// Revision the server negotiated in its `initialize` response ("?" if
- /// it didn't say) — shown in `/mcp` so version skew is visible.
+ /// Revision the server negotiated in its validated `initialize` response,
+ /// shown in `/mcp` so version skew is visible.
protocol_version: []const u8 = "?",
};
@@ -214,7 +110,12 @@ pub const Registry = struct {
/// An empty registry (no config file present), so the harness can still
/// accept servers added at runtime via `addServer`.
- pub fn empty(gpa: Allocator, io: Io, home: []const u8) Registry {
+ pub fn empty(gpa: Allocator, io: Io) Registry {
+ return emptyWithOAuthHome(gpa, io, "");
+ }
+
+ /// An empty registry that can load OAuth tokens rooted under `home`.
+ pub fn emptyWithOAuthHome(gpa: Allocator, io: Io, home: []const u8) Registry {
return .{ .gpa = gpa, .io = io, .home = home, .arena_state = std.heap.ArenaAllocator.init(gpa) };
}
@@ -372,8 +273,7 @@ pub const Registry = struct {
const server = try a.create(Server);
if (url_v) |url| {
if (url != .string) return error.BadMcpConfig;
- const uri = std.Uri.parse(url.string) catch return error.BadMcpUrl;
- if (!validRemoteUri(uri)) return error.BadMcpUrl;
+ if (!validRemoteUrl(url.string)) return error.BadMcpUrl;
var headers: std.ArrayList(std.http.Header) = .empty;
var has_authorization = false;
@@ -433,7 +333,7 @@ pub const Registry = struct {
});
var server_owns_child = false;
errdefer if (!server_owns_child) {
- stopChild(reg.io, &child);
+ mcp_stdio.stopChild(reg.io, &child);
};
const in_buf = try a.alloc(u8, 64 * 1024);
const out_buf = try a.alloc(u8, 1 << 20);
@@ -589,7 +489,7 @@ pub const Registry = struct {
fn deinitServer(server: *Server, io: Io) void {
switch (server.transport) {
- .stdio => |*stdio| stopChild(io, &stdio.child),
+ .stdio => |*stdio| mcp_stdio.stopChild(io, &stdio.child),
.http => |*http| {
if (http.session_id) |session_id| http.client.allocator.free(session_id);
http.client.deinit();
@@ -603,11 +503,8 @@ fn initializeServer(server: *Server, response_alloc: Allocator, session_alloc: A
++ latest_protocol ++
\\","capabilities":{},"clientInfo":{"name":"simple-harness","version":"0.1"}}
, "initialize");
- if (init_resp.object.get("result")) |res| if (res == .object) {
- if (res.object.get("protocolVersion")) |pv| if (pv == .string) {
- server.protocol_version = try session_alloc.dupe(u8, pv.string);
- };
- };
+ const protocol_version = try mcp_protocol.negotiatedProtocol(init_resp);
+ server.protocol_version = try session_alloc.dupe(u8, protocol_version);
try notify(server, response_alloc, "notifications/initialized");
}
@@ -628,7 +525,7 @@ fn request(server: *Server, response_alloc: Allocator, params: []const u8, metho
const r = &stdio.stdout_reader.interface;
while (true) {
const line = (try r.takeDelimiter('\n')) orelse return error.McpClosed;
- if (matchingResponse(response_alloc, line, id)) |parsed| return parsed;
+ if (mcp_http.matchingResponse(response_alloc, line, id)) |parsed| return parsed;
}
},
.http => |*http| {
@@ -636,9 +533,9 @@ fn request(server: *Server, response_alloc: Allocator, params: []const u8, metho
\\{{"jsonrpc":"2.0","id":{d},"method":"{s}","params":{s}}}
, .{ id, method, params });
const protocol_version = if (std.mem.eql(u8, method, "initialize")) latest_protocol else server.protocol_version;
- const response_body = (try httpPost(http, body, protocol_version, id)) orelse return error.BadMcpResponse;
+ const response_body = (try mcp_http.post(http, body, protocol_version, id)) orelse return error.BadMcpResponse;
defer http.client.allocator.free(response_body);
- return parseHttpResponse(response_alloc, response_body, id) orelse error.BadMcpResponse;
+ return mcp_http.parseHttpResponse(response_alloc, response_body, id) orelse error.BadMcpResponse;
},
}
}
@@ -657,315 +554,9 @@ fn notify(server: *Server, response_alloc: Allocator, method: []const u8) !void
const body = try std.fmt.allocPrint(response_alloc,
\\{{"jsonrpc":"2.0","method":"{s}","params":{{}}}}
, .{method});
- if (try httpPost(http, body, server.protocol_version, null)) |response_body| {
+ if (try mcp_http.post(http, body, server.protocol_version, null)) |response_body| {
http.client.allocator.free(response_body);
}
},
}
}
-
-fn matchingResponse(a: Allocator, bytes: []const u8, id: i64) ?Value {
- const trimmed = std.mem.trim(u8, bytes, " \t\r\n");
- if (trimmed.len == 0) return null;
- const parsed = std.json.parseFromSliceLeaky(Value, a, trimmed, .{ .allocate = .alloc_always }) catch return null;
- if (parsed != .object) return null;
- const got = parsed.object.get("id") orelse return null;
- if (got != .integer or got.integer != id) return null;
- return parsed;
-}
-
-/// Streamable HTTP permits either a plain application/json body or an SSE
-/// response. MCP JSON-RPC payloads are compact one-line `data:` events; ignore
-/// comments/notifications and return the event matching our request id.
-fn parseHttpResponse(a: Allocator, body: []const u8, id: i64) ?Value {
- if (matchingResponse(a, body, id)) |parsed| return parsed;
- var lines = std.mem.splitScalar(u8, body, '\n');
- while (lines.next()) |raw_line| {
- const line = std.mem.trimEnd(u8, raw_line, "\r");
- if (!std.mem.startsWith(u8, line, "data:")) continue;
- if (matchingResponse(a, std.mem.trimStart(u8, line["data:".len..], " \t"), id)) |parsed| return parsed;
- }
- return null;
-}
-
-fn jsonResponseMatches(gpa: Allocator, bytes: []const u8, expected_id: i64) bool {
- const parsed = std.json.parseFromSlice(Value, gpa, bytes, .{}) catch return false;
- defer parsed.deinit();
- if (parsed.value != .object) return false;
- const id = parsed.value.object.get("id") orelse return false;
- return id == .integer and id.integer == expected_id;
-}
-
-/// Read SSE one event at a time and return as soon as the matching JSON-RPC
-/// response arrives. This is important for servers that keep the POST stream
-/// open after emitting the response. Multiple `data:` fields are joined with
-/// newlines per the SSE specification.
-fn readSseResponse(gpa: Allocator, reader: *Io.Reader, expected_id: ?i64) !?[]u8 {
- const line_buf = try gpa.alloc(u8, max_http_response);
- defer gpa.free(line_buf);
- var event_data: std.ArrayList(u8) = .empty;
- defer event_data.deinit(gpa);
- var consumed: usize = 0;
-
- while (consumed < max_http_response) {
- var line_writer = Io.Writer.fixed(line_buf);
- const remaining = max_http_response - consumed;
- const n = reader.streamDelimiterLimit(&line_writer, '\n', .limited(remaining)) catch |err| switch (err) {
- error.StreamTooLong, error.WriteFailed => return error.McpResponseTooLarge,
- else => return err,
- };
- consumed += n;
- const line = std.mem.trimEnd(u8, line_writer.buffered(), "\r");
-
- var at_eof = false;
- const delimiter = reader.takeByte() catch |err| switch (err) {
- error.EndOfStream => blk: {
- at_eof = true;
- break :blk 0;
- },
- else => return err,
- };
- if (!at_eof) {
- std.debug.assert(delimiter == '\n');
- consumed += 1;
- }
-
- if (std.mem.startsWith(u8, line, "data:")) {
- const data = std.mem.trimStart(u8, line["data:".len..], " \t");
- if (event_data.items.len > 0) try event_data.append(gpa, '\n');
- if (event_data.items.len + data.len > max_http_response) return error.McpResponseTooLarge;
- try event_data.appendSlice(gpa, data);
- }
-
- if (line.len == 0 or at_eof) {
- if (event_data.items.len > 0) {
- const matches = if (expected_id) |id| jsonResponseMatches(gpa, event_data.items, id) else true;
- if (matches) return try gpa.dupe(u8, event_data.items);
- event_data.clearRetainingCapacity();
- }
- }
- if (at_eof) break;
- }
- if (consumed >= max_http_response) return error.McpResponseTooLarge;
- return null;
-}
-
-/// 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 {
- 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 });
-
- 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.items,
- });
- 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);
- if (status == 401 or status == 403) {
- if (req.connection) |connection| connection.closing = true;
- return error.McpAuthenticationRequired;
- }
- if (status == 404 and http.session_id != null) {
- if (req.connection) |connection| connection.closing = true;
- http.client.allocator.free(http.session_id.?);
- http.session_id = null;
- return error.McpSessionExpired;
- }
- if (status < 200 or status >= 300) {
- if (req.connection) |connection| connection.closing = true;
- 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);
- }
- }
- }
-
- 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);
-}
-
-const HttpPostDone = union(enum) {
- posted: anyerror!?[]u8,
- 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 httpPostTimeout(io: Io) void {
- io.sleep(.fromSeconds(15), .awake) catch {};
-}
-
-fn freeLateHttpPost(allocator: Allocator, result: anyerror!?[]u8) void {
- if (result) |body| {
- if (body) |bytes| allocator.free(bytes);
- } else |_| {}
-}
-
-fn cancelHttpPost(select: *Io.Select(HttpPostDone), allocator: Allocator) void {
- while (select.cancel()) |late| switch (late) {
- .posted => |result| freeLateHttpPost(allocator, result),
- .timeout => {},
- };
-}
-
-/// 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.
-fn httpPost(http: *HttpTransport, body: []const u8, protocol_version: []const u8, 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
- return error.McpRequestTimedOut;
- select.concurrent(.timeout, httpPostTimeout, .{http.client.io}) catch {
- const only = select.await() catch |err| {
- cancelHttpPost(&select, http.client.allocator);
- return err;
- };
- select.cancelDiscard();
- return only.posted;
- };
-
- const first = select.await() catch |err| {
- cancelHttpPost(&select, http.client.allocator);
- return err;
- };
- switch (first) {
- .posted => |result| {
- select.cancelDiscard();
- return result;
- },
- .timeout => {
- while (select.cancel()) |late| switch (late) {
- .posted => |result| freeLateHttpPost(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"));
- try std.testing.expect(validRemoteUrl("http://127.0.0.1:3000/mcp"));
- try std.testing.expect(validRemoteUrl("http://[::1]:3000/mcp"));
- try std.testing.expect(!validRemoteUrl("http://api.mobbin.com/mcp"));
- try std.testing.expect(!validRemoteUrl("ftp://localhost/mcp"));
- try std.testing.expect(!validRemoteUrl("not a URL"));
-}
-
-test "parseHttpResponse accepts JSON and Streamable HTTP SSE" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
-
- const json = parseHttpResponse(a, "{\"jsonrpc\":\"2.0\",\"id\":7,\"result\":{}}", 7).?;
- try std.testing.expect(json.object.get("result") != null);
-
- const sse = "event: message\r\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}\r\n\r\n" ++
- "event: message\r\ndata: {\"jsonrpc\":\"2.0\",\"id\":8,\"result\":{\"tools\":[]}}\r\n\r\n";
- const event = parseHttpResponse(a, sse, 8).?;
- try std.testing.expectEqual(@as(i64, 8), event.object.get("id").?.integer);
- try std.testing.expect(parseHttpResponse(a, sse, 9) == null);
-}
-
-test "rewriteOneOf: converts oneOf to anyOf, recursively" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var v = try std.json.parseFromSliceLeaky(Value, a,
- \\{"oneOf":[{"type":"string"}],"properties":{"x":{"oneOf":[{"type":"number"},{"type":"null"}]}}}
- , .{});
- try rewriteOneOf(a, &v);
- try std.testing.expect(v.object.get("oneOf") == null);
- try std.testing.expectEqual(@as(usize, 1), v.object.get("anyOf").?.array.items.len);
- const x = v.object.get("properties").?.object.get("x").?;
- try std.testing.expect(x.object.get("oneOf") == null);
- try std.testing.expectEqual(@as(usize, 2), x.object.get("anyOf").?.array.items.len);
-}
-
-test "rewriteOneOf: existing anyOf wins when both are present" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var v = try std.json.parseFromSliceLeaky(Value, a,
- \\{"anyOf":[{"type":"string"}],"oneOf":[{"type":"number"},{"type":"boolean"}]}
- , .{});
- try rewriteOneOf(a, &v);
- try std.testing.expect(v.object.get("oneOf") == null);
- // the pre-existing single-branch anyOf survives, the oneOf is dropped
- try std.testing.expectEqual(@as(usize, 1), v.object.get("anyOf").?.array.items.len);
-}
-
-test "rewriteOneOf: arrays and scalars pass through untouched" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- var v = try std.json.parseFromSliceLeaky(Value, a,
- \\{"items":[{"oneOf":[1,2]},"plain",42]}
- , .{});
- try rewriteOneOf(a, &v);
- const first = v.object.get("items").?.array.items[0];
- try std.testing.expect(first.object.get("oneOf") == null);
- try std.testing.expect(first.object.get("anyOf") != null);
-}
diff --git a/src/mcp_http.zig b/src/mcp_http.zig
new file mode 100644
index 00000000..ac86bd03
--- /dev/null
+++ b/src/mcp_http.zig
@@ -0,0 +1,297 @@
+//! MCP Streamable HTTP transport.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+const mcp_oauth = @import("mcp_oauth.zig");
+
+const max_http_response = 1 << 20;
+
+pub const HttpTransport = struct {
+ url: []const u8,
+ client: std.http.Client,
+ headers: []const std.http.Header = &.{},
+ oauth_home: ?[]const u8 = null,
+ session_id: ?[]const u8 = null,
+};
+
+fn validRemoteUri(uri: std.Uri) bool {
+ if (uri.host == null) return false;
+ if (std.ascii.eqlIgnoreCase(uri.scheme, "https")) return true;
+ if (!std.ascii.eqlIgnoreCase(uri.scheme, "http")) return false;
+ const host = uri.host.?.percent_encoded;
+ return std.ascii.eqlIgnoreCase(host, "localhost") or
+ std.mem.eql(u8, host, "127.0.0.1") or
+ std.mem.eql(u8, host, "[::1]") or
+ std.mem.eql(u8, host, "::1");
+}
+
+pub fn validRemoteUrl(url: []const u8) bool {
+ return validRemoteUri(std.Uri.parse(url) catch return false);
+}
+
+pub fn matchingResponse(a: Allocator, bytes: []const u8, id: i64) ?Value {
+ const trimmed = std.mem.trim(u8, bytes, " \t\r\n");
+ if (trimmed.len == 0) return null;
+ const parsed = std.json.parseFromSliceLeaky(Value, a, trimmed, .{ .allocate = .alloc_always }) catch return null;
+ if (parsed != .object) return null;
+ const got = parsed.object.get("id") orelse return null;
+ if (got != .integer or got.integer != id) return null;
+ return parsed;
+}
+
+/// Streamable HTTP permits either a plain application/json body or an SSE
+/// response. MCP JSON-RPC payloads are compact one-line `data:` events; ignore
+/// comments/notifications and return the event matching our request id.
+pub fn parseHttpResponse(a: Allocator, body: []const u8, id: i64) ?Value {
+ if (matchingResponse(a, body, id)) |parsed| return parsed;
+ var lines = std.mem.splitScalar(u8, body, '\n');
+ while (lines.next()) |raw_line| {
+ const line = std.mem.trimEnd(u8, raw_line, "\r");
+ if (!std.mem.startsWith(u8, line, "data:")) continue;
+ if (matchingResponse(a, std.mem.trimStart(u8, line["data:".len..], " \t"), id)) |parsed| return parsed;
+ }
+ return null;
+}
+
+fn jsonResponseMatches(gpa: Allocator, bytes: []const u8, expected_id: i64) bool {
+ const parsed = std.json.parseFromSlice(Value, gpa, bytes, .{}) catch return false;
+ defer parsed.deinit();
+ if (parsed.value != .object) return false;
+ const id = parsed.value.object.get("id") orelse return false;
+ return id == .integer and id.integer == expected_id;
+}
+
+/// Read SSE one event at a time and return as soon as the matching JSON-RPC
+/// response arrives. This is important for servers that keep the POST stream
+/// open after emitting the response. Multiple `data:` fields are joined with
+/// newlines per the SSE specification.
+fn readSseResponse(gpa: Allocator, reader: *Io.Reader, expected_id: ?i64) !?[]u8 {
+ const line_buf = try gpa.alloc(u8, max_http_response);
+ defer gpa.free(line_buf);
+ var event_data: std.ArrayList(u8) = .empty;
+ defer event_data.deinit(gpa);
+ var consumed: usize = 0;
+
+ while (consumed < max_http_response) {
+ var line_writer = Io.Writer.fixed(line_buf);
+ const remaining = max_http_response - consumed;
+ const n = reader.streamDelimiterLimit(&line_writer, '\n', .limited(remaining)) catch |err| switch (err) {
+ error.StreamTooLong, error.WriteFailed => return error.McpResponseTooLarge,
+ else => return err,
+ };
+ consumed += n;
+ const line = std.mem.trimEnd(u8, line_writer.buffered(), "\r");
+
+ var at_eof = false;
+ const delimiter = reader.takeByte() catch |err| switch (err) {
+ error.EndOfStream => blk: {
+ at_eof = true;
+ break :blk 0;
+ },
+ else => return err,
+ };
+ if (!at_eof) {
+ std.debug.assert(delimiter == '\n');
+ consumed += 1;
+ }
+
+ if (std.mem.startsWith(u8, line, "data:")) {
+ const data = std.mem.trimStart(u8, line["data:".len..], " \t");
+ if (event_data.items.len > 0) try event_data.append(gpa, '\n');
+ if (event_data.items.len + data.len > max_http_response) return error.McpResponseTooLarge;
+ try event_data.appendSlice(gpa, data);
+ }
+
+ if (line.len == 0 or at_eof) {
+ if (event_data.items.len > 0) {
+ const matches = if (expected_id) |id| jsonResponseMatches(gpa, event_data.items, id) else true;
+ if (matches) return try gpa.dupe(u8, event_data.items);
+ event_data.clearRetainingCapacity();
+ }
+ }
+ if (at_eof) break;
+ }
+ if (consumed >= max_http_response) return error.McpResponseTooLarge;
+ return null;
+}
+
+/// 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 {
+ 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 });
+
+ 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.items,
+ });
+ 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);
+ if (status == 401 or status == 403) {
+ if (req.connection) |connection| connection.closing = true;
+ return error.McpAuthenticationRequired;
+ }
+ if (status == 404 and http.session_id != null) {
+ if (req.connection) |connection| connection.closing = true;
+ http.client.allocator.free(http.session_id.?);
+ http.session_id = null;
+ return error.McpSessionExpired;
+ }
+ if (status < 200 or status >= 300) {
+ if (req.connection) |connection| connection.closing = true;
+ 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);
+ }
+ }
+ }
+
+ 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);
+}
+
+const HttpPostDone = union(enum) {
+ posted: anyerror!?[]u8,
+ 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 httpPostTimeout(io: Io) void {
+ io.sleep(.fromSeconds(15), .awake) catch {};
+}
+
+fn freeLateHttpPost(allocator: Allocator, result: anyerror!?[]u8) void {
+ if (result) |body| {
+ if (body) |bytes| allocator.free(bytes);
+ } else |_| {}
+}
+
+fn cancelHttpPost(select: *Io.Select(HttpPostDone), allocator: Allocator) void {
+ while (select.cancel()) |late| switch (late) {
+ .posted => |result| freeLateHttpPost(allocator, result),
+ .timeout => {},
+ };
+}
+
+/// 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 {
+ 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
+ return error.McpRequestTimedOut;
+ select.concurrent(.timeout, httpPostTimeout, .{http.client.io}) catch {
+ const only = select.await() catch |err| {
+ cancelHttpPost(&select, http.client.allocator);
+ return err;
+ };
+ select.cancelDiscard();
+ return only.posted;
+ };
+
+ const first = select.await() catch |err| {
+ cancelHttpPost(&select, http.client.allocator);
+ return err;
+ };
+ switch (first) {
+ .posted => |result| {
+ select.cancelDiscard();
+ return result;
+ },
+ .timeout => {
+ while (select.cancel()) |late| switch (late) {
+ .posted => |result| freeLateHttpPost(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"));
+ try std.testing.expect(validRemoteUrl("http://127.0.0.1:3000/mcp"));
+ try std.testing.expect(validRemoteUrl("http://[::1]:3000/mcp"));
+ try std.testing.expect(!validRemoteUrl("http://api.mobbin.com/mcp"));
+ try std.testing.expect(!validRemoteUrl("ftp://localhost/mcp"));
+ try std.testing.expect(!validRemoteUrl("not a URL"));
+}
+
+test "parseHttpResponse accepts JSON and Streamable HTTP SSE" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const json = parseHttpResponse(a, "{\"jsonrpc\":\"2.0\",\"id\":7,\"result\":{}}", 7).?;
+ try std.testing.expect(json.object.get("result") != null);
+
+ const sse = "event: message\r\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}\r\n\r\n" ++
+ "event: message\r\ndata: {\"jsonrpc\":\"2.0\",\"id\":8,\"result\":{\"tools\":[]}}\r\n\r\n";
+ const event = parseHttpResponse(a, sse, 8).?;
+ try std.testing.expectEqual(@as(i64, 8), event.object.get("id").?.integer);
+ try std.testing.expect(parseHttpResponse(a, sse, 9) == null);
+}
diff --git a/src/mcp_oauth.zig b/src/mcp_oauth.zig
index 2cce0407..cda0d787 100644
--- a/src/mcp_oauth.zig
+++ b/src/mcp_oauth.zig
@@ -4,6 +4,7 @@
const std = @import("std");
const builtin = @import("builtin");
const util = @import("util.zig");
+const discovery = @import("mcp_oauth_discovery.zig");
const Io = std.Io;
const Allocator = std.mem.Allocator;
@@ -32,53 +33,7 @@ const TokenSet = struct {
expires_at_ms: i64,
};
-fn requireHttps(url: []const u8) !void {
- if (!std.mem.startsWith(u8, url, "https://")) return error.InsecureOAuthEndpoint;
- const rest = url["https://".len..];
- if (rest.len == 0 or rest[0] == '/' or std.mem.indexOfScalar(u8, rest, '@') != null)
- return error.InvalidOAuthUrl;
-}
-
-fn splitOrigin(url: []const u8) !struct { origin: []const u8, path: []const u8 } {
- try requireHttps(url);
- const authority_start = "https://".len;
- var authority_end = url.len;
- for (url[authority_start..], authority_start..) |c, i| {
- if (c == '/' or c == '?' or c == '#') {
- authority_end = i;
- break;
- }
- }
- if (authority_end == authority_start) return error.InvalidOAuthUrl;
- const tail = url[authority_end..];
- const path_end = std.mem.indexOfAny(u8, tail, "?#") orelse tail.len;
- const path = if (path_end == 0 or tail[0] != '/') "/" else tail[0..path_end];
- return .{ .origin = url[0..authority_end], .path = path };
-}
-
-/// RFC 9728 section 3.1: insert the well-known name between the origin and the
-/// protected resource's path.
-fn protectedMetadataUrl(arena: Allocator, resource_url: []const u8) ![]const u8 {
- const p = try splitOrigin(resource_url);
- return std.fmt.allocPrint(arena, "{s}/.well-known/oauth-protected-resource{s}", .{
- p.origin,
- if (std.mem.eql(u8, p.path, "/")) "" else p.path,
- });
-}
-
-/// RFC 8414 section 3: issuer paths follow the well-known component.
-fn authorizationMetadataUrl(arena: Allocator, issuer: []const u8) ![]const u8 {
- const p = try splitOrigin(issuer);
- return std.fmt.allocPrint(arena, "{s}/.well-known/oauth-authorization-server{s}", .{
- p.origin,
- if (std.mem.eql(u8, p.path, "/")) "" else p.path,
- });
-}
-
-fn oidcMetadataUrl(arena: Allocator, issuer: []const u8) ![]const u8 {
- try requireHttps(issuer);
- return std.fmt.allocPrint(arena, "{s}/.well-known/openid-configuration", .{std.mem.trimEnd(u8, issuer, "/")});
-}
+const requireHttps = discovery.requireHttps;
fn writePercentEncoded(w: *Io.Writer, value: []const u8) !void {
const hex = "0123456789ABCDEF";
@@ -188,10 +143,38 @@ fn postForm(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, payload:
return jsonObject(writer.buffered(), arena);
}
+fn authorizationEndpoints(io: Io, gpa: Allocator, arena: Allocator, issuer: []const u8, metadata_url: []const u8) !EndpointSet {
+ const metadata = try fetchJson(io, gpa, arena, metadata_url);
+ const advertised_issuer = stringField(metadata, "issuer") orelse return error.AuthorizationServerMismatch;
+ if (!std.mem.eql(u8, advertised_issuer, issuer)) return error.AuthorizationServerMismatch;
+ if (!discovery.supportsS256(metadata)) return error.PkceS256Unsupported;
+
+ const authorization = stringField(metadata, "authorization_endpoint") orelse return error.BadOAuthResponse;
+ const token = stringField(metadata, "token_endpoint") orelse return error.BadOAuthResponse;
+ const registration = stringField(metadata, "registration_endpoint") orelse return error.DynamicRegistrationUnsupported;
+ try requireHttps(authorization);
+ try requireHttps(token);
+ try requireHttps(registration);
+ return .{
+ .issuer = issuer,
+ .authorization = authorization,
+ .token = token,
+ .registration = registration,
+ .scope = try supportedScopes(arena, metadata),
+ };
+}
+
fn discover(io: Io, gpa: Allocator, arena: Allocator, resource_url: []const u8) !EndpointSet {
- const resource_metadata = try fetchJson(io, gpa, arena, try protectedMetadataUrl(arena, resource_url));
- if (stringField(resource_metadata, "resource")) |advertised|
- if (!std.mem.eql(u8, advertised, resource_url)) return error.ResourceMetadataMismatch;
+ // RFC 9728 challenges are authoritative hints and must be obtained before
+ // attempting either protected-resource well-known location.
+ const challenge = try discovery.probe(io, gpa, arena, resource_url);
+ const resource_metadata = if (challenge.resource_metadata) |url|
+ try fetchJson(io, gpa, arena, url)
+ else
+ fetchJson(io, gpa, arena, try discovery.protectedMetadataUrl(arena, resource_url)) catch
+ try fetchJson(io, gpa, arena, try discovery.rootProtectedMetadataUrl(arena, resource_url));
+ const advertised_resource = stringField(resource_metadata, "resource") orelse return error.ResourceMetadataMismatch;
+ if (!std.mem.eql(u8, advertised_resource, resource_url)) return error.ResourceMetadataMismatch;
const servers = resource_metadata.get("authorization_servers") orelse return error.MissingAuthorizationServer;
if (servers != .array or servers.array.items.len == 0) return error.MissingAuthorizationServer;
@@ -204,30 +187,29 @@ fn discover(io: Io, gpa: Allocator, arena: Allocator, resource_url: []const u8)
}
const selected = issuer orelse return error.InsecureOAuthEndpoint;
- const metadata = fetchJson(io, gpa, arena, try authorizationMetadataUrl(arena, selected)) catch
- try fetchJson(io, gpa, arena, try oidcMetadataUrl(arena, selected));
- if (stringField(metadata, "issuer")) |advertised|
- if (!std.mem.eql(u8, std.mem.trimEnd(u8, advertised, "/"), std.mem.trimEnd(u8, selected, "/")))
- return error.AuthorizationServerMismatch;
-
- const authorization = stringField(metadata, "authorization_endpoint") orelse return error.BadOAuthResponse;
- const token = stringField(metadata, "token_endpoint") orelse return error.BadOAuthResponse;
- const registration = stringField(metadata, "registration_endpoint") orelse return error.DynamicRegistrationUnsupported;
- try requireHttps(authorization);
- try requireHttps(token);
- try requireHttps(registration);
- var scope = try supportedScopes(arena, resource_metadata);
- if (scope.len == 0) scope = try supportedScopes(arena, metadata);
- // Core Smolify is a documentation reader. Do not request its advertised
- // contribution/publication capabilities merely because they exist.
- if (std.mem.eql(u8, resource_url, smolify_resource)) scope = smolify_read_scopes;
- return .{
- .issuer = selected,
- .authorization = authorization,
- .token = token,
- .registration = registration,
- .scope = scope,
- };
+ var endpoints = authorizationEndpoints(io, gpa, arena, selected, try discovery.authorizationMetadataUrl(arena, selected)) catch
+ authorizationEndpoints(io, gpa, arena, selected, try discovery.oidcInsertedMetadataUrl(arena, selected)) catch
+ try authorizationEndpoints(io, gpa, arena, selected, try discovery.oidcAppendedMetadataUrl(arena, selected));
+ var scope = discovery.preferredScope(
+ challenge.scope,
+ try supportedScopes(arena, resource_metadata),
+ endpoints.scope,
+ );
+ // Core Smolify remains read-only. An explicit challenge is authoritative,
+ // but fail closed if it requests permissions outside the pinned allowlist.
+ if (std.mem.eql(u8, resource_url, smolify_resource)) {
+ if (challenge.scope) |challenged| {
+ if (challenged.len == 0) {
+ scope = smolify_read_scopes;
+ } else if (!discovery.scopeSubsetOf(challenged, smolify_read_scopes)) {
+ return error.SmolifyScopeNotReadOnly;
+ }
+ } else {
+ scope = smolify_read_scopes;
+ }
+ }
+ endpoints.scope = scope;
+ return endpoints;
}
fn registerClient(io: Io, gpa: Allocator, arena: Allocator, endpoint: []const u8, server_name: []const u8) !ClientInfo {
@@ -542,16 +524,6 @@ pub fn loadAccessToken(io: Io, gpa: Allocator, arena: Allocator, home: []const u
return tokens.access;
}
-test "RFC 9728 and RFC 8414 metadata URL construction" {
- const arena = std.testing.allocator;
- const protected = try protectedMetadataUrl(arena, "https://mcp.example:8443/a/b?x=1");
- defer arena.free(protected);
- try std.testing.expectEqualStrings("https://mcp.example:8443/.well-known/oauth-protected-resource/a/b", protected);
- const auth = try authorizationMetadataUrl(arena, "https://login.example/tenant");
- defer arena.free(auth);
- try std.testing.expectEqualStrings("https://login.example/.well-known/oauth-authorization-server/tenant", auth);
-}
-
test "form encoding uses RFC 3986 percent encoding" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/mcp_oauth_discovery.zig b/src/mcp_oauth_discovery.zig
new file mode 100644
index 00000000..ef2a5ab7
--- /dev/null
+++ b/src/mcp_oauth_discovery.zig
@@ -0,0 +1,281 @@
+const std = @import("std");
+
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const mcp_protocol = @import("mcp_protocol.zig");
+
+pub const Challenge = struct {
+ resource_metadata: ?[]const u8 = null,
+ scope: ?[]const u8 = null,
+};
+
+pub fn requireHttps(url: []const u8) !void {
+ const uri = std.Uri.parse(url) catch return error.InvalidOAuthUrl;
+ if (!std.ascii.eqlIgnoreCase(uri.scheme, "https")) return error.InsecureOAuthEndpoint;
+ if (uri.host == null or uri.user != null or uri.password != null or uri.fragment != null)
+ return error.InvalidOAuthUrl;
+}
+
+fn splitOrigin(url: []const u8) !struct { origin: []const u8, path: []const u8 } {
+ try requireHttps(url);
+ const authority_start = "https://".len;
+ var authority_end = url.len;
+ for (url[authority_start..], authority_start..) |c, i| {
+ if (c == '/' or c == '?' or c == '#') {
+ authority_end = i;
+ break;
+ }
+ }
+ if (authority_end == authority_start) return error.InvalidOAuthUrl;
+ const tail = url[authority_end..];
+ const path_end = std.mem.indexOfAny(u8, tail, "?#") orelse tail.len;
+ const path = if (path_end == 0 or tail[0] != '/') "/" else tail[0..path_end];
+ return .{ .origin = url[0..authority_end], .path = path };
+}
+
+/// RFC 9728 section 3.1: insert the well-known name between the origin and the
+/// protected resource's path.
+pub fn protectedMetadataUrl(arena: Allocator, resource_url: []const u8) ![]const u8 {
+ const p = try splitOrigin(resource_url);
+ return std.fmt.allocPrint(arena, "{s}/.well-known/oauth-protected-resource{s}", .{
+ p.origin,
+ if (std.mem.eql(u8, p.path, "/")) "" else p.path,
+ });
+}
+
+pub fn rootProtectedMetadataUrl(arena: Allocator, resource_url: []const u8) ![]const u8 {
+ const p = try splitOrigin(resource_url);
+ return std.fmt.allocPrint(arena, "{s}/.well-known/oauth-protected-resource", .{p.origin});
+}
+
+/// RFC 8414 section 3: issuer paths follow the well-known component.
+pub fn authorizationMetadataUrl(arena: Allocator, issuer: []const u8) ![]const u8 {
+ const p = try splitOrigin(issuer);
+ return std.fmt.allocPrint(arena, "{s}/.well-known/oauth-authorization-server{s}", .{
+ p.origin,
+ if (std.mem.eql(u8, p.path, "/")) "" else p.path,
+ });
+}
+
+pub fn oidcInsertedMetadataUrl(arena: Allocator, issuer: []const u8) ![]const u8 {
+ const p = try splitOrigin(issuer);
+ return std.fmt.allocPrint(arena, "{s}/.well-known/openid-configuration{s}", .{
+ p.origin,
+ if (std.mem.eql(u8, p.path, "/")) "" else p.path,
+ });
+}
+
+pub fn oidcAppendedMetadataUrl(arena: Allocator, issuer: []const u8) ![]const u8 {
+ try requireHttps(issuer);
+ return std.fmt.allocPrint(arena, "{s}/.well-known/openid-configuration", .{std.mem.trimEnd(u8, issuer, "/")});
+}
+
+fn skipOws(value: []const u8, pos: *usize) void {
+ while (pos.* < value.len and (value[pos.*] == ' ' or value[pos.*] == '\t')) pos.* += 1;
+}
+
+fn tokenEnd(value: []const u8, start: usize) usize {
+ var end = start;
+ while (end < value.len and std.ascii.isAlphanumeric(value[end]) or
+ (end < value.len and std.mem.indexOfScalar(u8, "!#$%&'*+-.^_`|~", value[end]) != null)) end += 1;
+ return end;
+}
+
+fn parseValue(arena: Allocator, value: []const u8, pos: *usize) !?[]const u8 {
+ if (pos.* >= value.len) return null;
+ if (value[pos.*] != '"') {
+ const end = tokenEnd(value, pos.*);
+ if (end == pos.*) return null;
+ const result = value[pos.*..end];
+ pos.* = end;
+ return result;
+ }
+ pos.* += 1;
+ var result: std.ArrayList(u8) = .empty;
+ while (pos.* < value.len) {
+ const c = value[pos.*];
+ pos.* += 1;
+ if (c == '"') return try result.toOwnedSlice(arena);
+ if (c == '\\') {
+ if (pos.* >= value.len) return error.InvalidAuthenticationChallenge;
+ try result.append(arena, value[pos.*]);
+ pos.* += 1;
+ } else {
+ if (c == '\r' or c == '\n') return error.InvalidAuthenticationChallenge;
+ try result.append(arena, c);
+ }
+ }
+ return error.InvalidAuthenticationChallenge;
+}
+
+/// Parse a WWW-Authenticate field value, including multiple challenges and
+/// quoted-string escaping, and return the first Bearer challenge with MCP params.
+pub fn parseChallenge(arena: Allocator, value: []const u8) !Challenge {
+ var pos: usize = 0;
+ while (pos < value.len) {
+ skipOws(value, &pos);
+ while (pos < value.len and value[pos] == ',') {
+ pos += 1;
+ skipOws(value, &pos);
+ }
+ const scheme_end = tokenEnd(value, pos);
+ if (scheme_end == pos) break;
+ const bearer = std.ascii.eqlIgnoreCase(value[pos..scheme_end], "Bearer");
+ pos = scheme_end;
+ var found: Challenge = .{};
+ while (pos < value.len) {
+ skipOws(value, &pos);
+ if (pos >= value.len) break;
+ if (value[pos] == ',') {
+ pos += 1;
+ skipOws(value, &pos);
+ }
+ const name_start = pos;
+ const name_end = tokenEnd(value, pos);
+ if (name_end == pos) break;
+ pos = name_end;
+ skipOws(value, &pos);
+ if (pos >= value.len or value[pos] != '=') {
+ pos = name_start;
+ break;
+ }
+ pos += 1;
+ skipOws(value, &pos);
+ const param_value = (try parseValue(arena, value, &pos)) orelse break;
+ if (bearer and std.ascii.eqlIgnoreCase(value[name_start..name_end], "resource_metadata"))
+ found.resource_metadata = param_value;
+ if (bearer and std.ascii.eqlIgnoreCase(value[name_start..name_end], "scope"))
+ found.scope = param_value;
+ }
+ if (bearer and (found.resource_metadata != null or found.scope != null)) return found;
+ }
+ return .{};
+}
+
+pub fn probe(io: Io, gpa: Allocator, arena: Allocator, resource_url: []const u8) !Challenge {
+ try requireHttps(resource_url);
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ const body =
+ \\{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"
+ ++ mcp_protocol.latest_protocol ++
+ \\","capabilities":{},"clientInfo":{"name":"codegraff-mcp-login","version":"1"}}}
+ ;
+ const extra_headers = [_]std.http.Header{
+ .{ .name = "accept", .value = "application/json, text/event-stream" },
+ .{ .name = "mcp-protocol-version", .value = mcp_protocol.latest_protocol },
+ };
+ var request = try client.request(.POST, try std.Uri.parse(resource_url), .{
+ .redirect_behavior = .unhandled,
+ .headers = .{
+ .content_type = .{ .override = "application/json" },
+ .accept_encoding = .omit,
+ .user_agent = .{ .override = "codegraff-mcp/1" },
+ },
+ .extra_headers = &extra_headers,
+ });
+ defer request.deinit();
+ errdefer {
+ if (request.connection) |connection| connection.closing = true;
+ }
+ request.transfer_encoding = .{ .content_length = body.len };
+ var body_writer = try request.sendBodyUnflushed(&.{});
+ try body_writer.writer.writeAll(body);
+ try body_writer.end();
+ try request.connection.?.flush();
+ const response = try request.receiveHead(&.{});
+ if (request.connection) |connection| connection.closing = true;
+
+ var challenge: Challenge = .{};
+ var headers = response.head.iterateHeaders();
+ while (headers.next()) |header| {
+ if (!std.ascii.eqlIgnoreCase(header.name, "WWW-Authenticate")) continue;
+ const parsed = try parseChallenge(arena, header.value);
+ if (challenge.resource_metadata == null) challenge.resource_metadata = parsed.resource_metadata;
+ if (challenge.scope == null) challenge.scope = parsed.scope;
+ }
+ return challenge;
+}
+
+pub fn preferredScope(challenge: ?[]const u8, resource: []const u8, authorization_server: []const u8) []const u8 {
+ if (challenge) |scope| if (scope.len != 0) return scope;
+ if (resource.len != 0) return resource;
+ return authorization_server;
+}
+
+pub fn scopeSubsetOf(scope: []const u8, allowed: []const u8) bool {
+ var requested = std.mem.tokenizeScalar(u8, scope, ' ');
+ while (requested.next()) |item| {
+ var candidates = std.mem.tokenizeScalar(u8, allowed, ' ');
+ while (candidates.next()) |candidate| {
+ if (std.mem.eql(u8, item, candidate)) break;
+ } else return false;
+ }
+ return true;
+}
+
+pub fn supportsS256(metadata: std.json.ObjectMap) bool {
+ const methods = metadata.get("code_challenge_methods_supported") orelse return false;
+ if (methods != .array) return false;
+ for (methods.array.items) |method|
+ if (method == .string and std.mem.eql(u8, method.string, "S256")) return true;
+ return false;
+}
+
+test "OAuth URLs require a parsed HTTPS URI without userinfo or fragments" {
+ try requireHttps("HTTPS://login.example/token?audience=mcp");
+ try std.testing.expectError(error.InsecureOAuthEndpoint, requireHttps("http://login.example/token"));
+ try std.testing.expectError(error.InvalidOAuthUrl, requireHttps("https://[email protected]/token"));
+ try std.testing.expectError(error.InvalidOAuthUrl, requireHttps("https://login.example/token#fragment"));
+ try std.testing.expectError(error.InvalidOAuthUrl, requireHttps("https:///missing-host"));
+}
+
+test "metadata URL construction covers RFC and OIDC issuer paths" {
+ const allocator = std.testing.allocator;
+ const protected = try protectedMetadataUrl(allocator, "https://mcp.example:8443/a/b?x=1");
+ defer allocator.free(protected);
+ try std.testing.expectEqualStrings("https://mcp.example:8443/.well-known/oauth-protected-resource/a/b", protected);
+ const root = try rootProtectedMetadataUrl(allocator, "https://mcp.example:8443/a/b");
+ defer allocator.free(root);
+ try std.testing.expectEqualStrings("https://mcp.example:8443/.well-known/oauth-protected-resource", root);
+ const rfc = try authorizationMetadataUrl(allocator, "https://login.example/tenant");
+ defer allocator.free(rfc);
+ try std.testing.expectEqualStrings("https://login.example/.well-known/oauth-authorization-server/tenant", rfc);
+ const inserted = try oidcInsertedMetadataUrl(allocator, "https://login.example/tenant");
+ defer allocator.free(inserted);
+ try std.testing.expectEqualStrings("https://login.example/.well-known/openid-configuration/tenant", inserted);
+ const appended = try oidcAppendedMetadataUrl(allocator, "https://login.example/tenant/");
+ defer allocator.free(appended);
+ try std.testing.expectEqualStrings("https://login.example/tenant/.well-known/openid-configuration", appended);
+}
+
+test "Bearer challenge parsing handles other challenges and quoted escapes" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const challenge = try parseChallenge(arena_state.allocator(), "Bearer realm=\"old\", Basic realm=\"legacy\", Bearer resource_metadata=\"https://mcp.example/meta\\?v=1\", scope=\"docs:read profile\", Digest realm=\"later\"");
+ try std.testing.expectEqualStrings("https://mcp.example/meta?v=1", challenge.resource_metadata.?);
+ try std.testing.expectEqualStrings("docs:read profile", challenge.scope.?);
+}
+
+test "challenge scope takes priority over metadata scopes" {
+ try std.testing.expectEqualStrings("challenge:read", preferredScope("challenge:read", "resource:write", "server:write"));
+ try std.testing.expectEqualStrings("resource:read", preferredScope(null, "resource:read", "server:write"));
+ try std.testing.expectEqualStrings("server:read", preferredScope(null, "", "server:read"));
+}
+
+test "scope subset rejects unapproved challenge permissions" {
+ try std.testing.expect(scopeSubsetOf("docs:read profile", "profile email docs:read"));
+ try std.testing.expect(!scopeSubsetOf("docs:read docs:write", "profile email docs:read"));
+}
+
+test "PKCE metadata requires exact S256 array member" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const good = (try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"code_challenge_methods_supported\":[\"plain\",\"S256\"]}", .{})).object;
+ const wrong_case = (try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"code_challenge_methods_supported\":[\"s256\"]}", .{})).object;
+ const wrong_type = (try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"code_challenge_methods_supported\":\"S256\"}", .{})).object;
+ try std.testing.expect(supportsS256(good));
+ try std.testing.expect(!supportsS256(wrong_case));
+ try std.testing.expect(!supportsS256(wrong_type));
+}
diff --git a/src/mcp_protocol.zig b/src/mcp_protocol.zig
new file mode 100644
index 00000000..0181b0c6
--- /dev/null
+++ b/src/mcp_protocol.zig
@@ -0,0 +1,120 @@
+//! MCP protocol negotiation and tool JSON Schema normalization.
+
+const std = @import("std");
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+/// Recursively rewrite the JSON Schema keyword `oneOf` to `anyOf` (graff's
+/// rewrite_one_of_to_any_of). OpenAI's tool-schema validator — including the
+/// chatgpt.com /codex/responses endpoint — rejects `oneOf` outright with
+/// "'oneOf' is not permitted"; `anyOf` is accepted by both OpenAI and
+/// Anthropic and is equivalent for the discriminated unions MCP servers emit
+/// in practice. When both keywords are present (rare, ambiguous to merge),
+/// the existing `anyOf` wins and `oneOf` is dropped. Runs once per tool at
+/// discovery, so the rendered tools JSON stays KV-cache-stable.
+pub fn rewriteOneOf(a: Allocator, v: *Value) Allocator.Error!void {
+ switch (v.*) {
+ .object => |*obj| {
+ if (obj.get("oneOf")) |branches| {
+ if (obj.get("anyOf") == null) try obj.put(a, "anyOf", branches);
+ _ = obj.swapRemove("oneOf");
+ }
+ var it = obj.iterator();
+ while (it.next()) |e| try rewriteOneOf(a, e.value_ptr);
+ },
+ .array => |*arr| for (arr.items) |*item| try rewriteOneOf(a, item),
+ else => {},
+ }
+}
+
+/// Latest MCP revision advertised during initialization.
+pub const latest_protocol = "2025-11-25";
+
+/// Revisions whose initialize, tools, and content schemas are compatible with
+/// the subset implemented by this client.
+pub const supported_protocols = [_][]const u8{
+ latest_protocol,
+ "2025-06-18",
+ "2025-03-26",
+ "2024-11-05",
+};
+
+pub fn negotiatedProtocol(response: Value) ![]const u8 {
+ if (response != .object) return error.BadMcpInitializeResponse;
+ const result = response.object.get("result") orelse return error.BadMcpInitializeResponse;
+ if (result != .object) return error.BadMcpInitializeResponse;
+ const version = result.object.get("protocolVersion") orelse return error.MissingMcpProtocolVersion;
+ if (version != .string) return error.InvalidMcpProtocolVersion;
+ for (supported_protocols) |supported| {
+ if (std.mem.eql(u8, version.string, supported)) return version.string;
+ }
+ return error.UnsupportedMcpProtocolVersion;
+}
+
+test "rewriteOneOf: converts oneOf to anyOf, recursively" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var v = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"oneOf":[{"type":"string"}],"properties":{"x":{"oneOf":[{"type":"number"},{"type":"null"}]}}}
+ , .{});
+ try rewriteOneOf(a, &v);
+ try std.testing.expect(v.object.get("oneOf") == null);
+ try std.testing.expectEqual(@as(usize, 1), v.object.get("anyOf").?.array.items.len);
+ const x = v.object.get("properties").?.object.get("x").?;
+ try std.testing.expect(x.object.get("oneOf") == null);
+ try std.testing.expectEqual(@as(usize, 2), x.object.get("anyOf").?.array.items.len);
+}
+
+test "rewriteOneOf: existing anyOf wins when both are present" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var v = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"anyOf":[{"type":"string"}],"oneOf":[{"type":"number"},{"type":"boolean"}]}
+ , .{});
+ try rewriteOneOf(a, &v);
+ try std.testing.expect(v.object.get("oneOf") == null);
+ // the pre-existing single-branch anyOf survives, the oneOf is dropped
+ try std.testing.expectEqual(@as(usize, 1), v.object.get("anyOf").?.array.items.len);
+}
+
+test "rewriteOneOf: arrays and scalars pass through untouched" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var v = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"items":[{"oneOf":[1,2]},"plain",42]}
+ , .{});
+ try rewriteOneOf(a, &v);
+ const first = v.object.get("items").?.array.items[0];
+ try std.testing.expect(first.object.get("oneOf") == null);
+ try std.testing.expect(first.object.get("anyOf") != null);
+}
+
+test "initialize negotiation accepts supported protocol versions" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ for (supported_protocols) |version| {
+ const json = try std.fmt.allocPrint(a,
+ \\{{"jsonrpc":"2.0","id":1,"result":{{"protocolVersion":"{s}"}}}}
+ , .{version});
+ const response = try std.json.parseFromSliceLeaky(Value, a, json, .{});
+ try std.testing.expectEqualStrings(version, try negotiatedProtocol(response));
+ }
+}
+
+test "initialize negotiation rejects missing, non-string, and unsupported versions" {
+ const cases = [_]struct { json: []const u8, expected: anyerror }{
+ .{ .json = "{\"result\":{}}", .expected = error.MissingMcpProtocolVersion },
+ .{ .json = "{\"result\":{\"protocolVersion\":20251125}}", .expected = error.InvalidMcpProtocolVersion },
+ .{ .json = "{\"result\":{\"protocolVersion\":\"2099-01-01\"}}", .expected = error.UnsupportedMcpProtocolVersion },
+ };
+ for (cases) |case| {
+ var parsed = try std.json.parseFromSlice(Value, std.testing.allocator, case.json, .{});
+ defer parsed.deinit();
+ try std.testing.expectError(case.expected, negotiatedProtocol(parsed.value));
+ }
+}
diff --git a/src/mcp_stdio.zig b/src/mcp_stdio.zig
new file mode 100644
index 00000000..7f91193f
--- /dev/null
+++ b/src/mcp_stdio.zig
@@ -0,0 +1,56 @@
+//! MCP stdio child-process shutdown.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+
+const shutdown_grace = std.Io.Duration.fromMilliseconds(100);
+
+fn waitChild(child: *std.process.Child, io: Io) std.process.Child.WaitError!std.process.Child.Term {
+ return child.wait(io);
+}
+
+fn shutdownDeadline(io: Io) void {
+ io.sleep(shutdown_grace, .awake) catch {};
+}
+
+/// Signal a normal stdio-server shutdown with EOF, but never let a server's
+/// SIGTERM handler stall the CLI. A child that does not exit within the grace
+/// window is force-killed and reaped so one-shot/SDK callers do not inherit
+/// teardown latency or zombies.
+pub fn stopChild(io: Io, child: *std.process.Child) void {
+ if (child.id == null) return;
+ if (child.stdin) |stdin| {
+ stdin.close(io);
+ child.stdin = null;
+ }
+
+ const Done = union(enum) { exited: std.process.Child.WaitError!std.process.Child.Term, deadline: void };
+ var done_buf: [2]Done = undefined;
+ var sel: Io.Select(Done) = .init(io, &done_buf);
+ sel.concurrent(.exited, waitChild, .{ child, io }) catch {
+ child.kill(io);
+ return;
+ };
+ sel.concurrent(.deadline, shutdownDeadline, .{io}) catch {
+ _ = sel.await() catch {};
+ sel.cancelDiscard();
+ return;
+ };
+ const first = sel.await() catch {
+ sel.cancelDiscard();
+ child.kill(io);
+ return;
+ };
+ sel.cancelDiscard();
+ if (first == .exited or child.id == null) return;
+
+ switch (builtin.os.tag) {
+ .windows => child.kill(io),
+ .wasi => unreachable,
+ else => {
+ std.posix.kill(child.id.?, .KILL) catch {};
+ _ = child.wait(io) catch child.kill(io);
+ },
+ }
+}
diff --git a/src/session_start.zig b/src/session_start.zig
index 324cb213..13a62342 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -259,9 +259,9 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wr
try out.print("[mcp] init failed: {t} — continuing without MCP\n", .{err});
if (telemetry.g_telem) |t| t.errorEvent("mcp", @errorName(err));
break :inner null;
- }) orelse mcp.Registry.empty(gpa, io, home)) else outer: {
+ }) orelse mcp.Registry.emptyWithOAuthHome(gpa, io, home)) else outer: {
if (mcp_count > 0) try out.print("{s}skipped {d} workspace MCP server(s) — /mcp trust to connect them now (or re-run with --yolo){s}\n", .{ ansi.style.dim, mcp_count, ansi.style.reset });
- break :outer mcp.Registry.empty(gpa, io, home);
+ break :outer mcp.Registry.emptyWithOAuthHome(gpa, io, home);
};
}
diff --git a/src/startup.zig b/src/startup.zig
index 07a92f97..21981f9e 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -408,9 +408,9 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
return true;
}
- // `harness mcp add <name> -- <command> [args...]`: write workspace MCP config.
+ // MCP list/add only use workspace config; OAuth login validates HOME itself.
if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "mcp")) {
- const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});
+ const home = keys_cli.homeEnv(init.environ_map) orelse "";
try mcp_cli.mcpCommand(io, gpa, arena, home, flags.positionals.items[1..]);
return true;
}