Skip to content

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

Python

Add Streamable HTTP OAuth and core Smolify MCP

yxlyx83277d367af4
diff --git a/README.md b/README.md
index 403f30ee..4d9764b6 100644
--- a/README.md
+++ b/README.md
@@ -450,6 +450,36 @@ turns it back on, and `/goal status` shows the objective and its current state.
blocked, cancelled, or exhausted) once the work is done, you step in, or a safety
limit is hit, instead of pausing for confirmation between routine steps.
+### MCP servers
+
+Graff speaks both MCP transports directly: local stdio servers and remote
+Streamable HTTP servers. Smolify (`https://app.smol.ly/mcp`) is connected as a
+core, anonymous documentation service; it needs no Node bridge or project
+configuration. This performs discovery requests at startup and tool queries may
+be sent to the hosted service; set `GRAFF_NO_SMOLIFY=1` for offline or
+privacy-sensitive sessions. Other servers can be added from the shell or during
+a session:
+
+```sh
+graff mcp add context7 -- npx -y @upstash/context7-mcp
+graff mcp add mobbin --url https://api.mobbin.com/mcp
+graff mcp login mobbin # OAuth discovery + browser PKCE flow
+graff mcp login smolify # optional access to authenticated Smolify tools
+# In the REPL: /mcp add mobbin --url https://api.mobbin.com/mcp
+```
+
+The equivalent `.mcp.json` URL entry is
+`{"mcpServers":{"mobbin":{"url":"https://api.mobbin.com/mcp"}}}`. Remote
+responses may use either `application/json` or `text/event-stream`; Graff keeps
+`Mcp-Session-Id` state and sends `MCP-Protocol-Version` on requests.
+For OAuth-protected endpoints, `graff mcp login <name>` performs protected
+resource and authorization-server discovery, dynamic client registration, and
+a browser PKCE flow. Tokens are stored outside the repository under
+`~/.simple-harness-mcp` with user-only permissions and refreshed automatically.
+Static HTTP headers can alternatively be added with
+`--header 'Authorization=Bearer TOKEN'` (they are stored in `.mcp.json`, so
+prefer a restricted token and do not commit that file).
+
The line editor supports ↑/↓ history (persisted to `~/.simple-harness-history`),
Tab completion (commands, and model names after `/model `), and emacs-style
editing (Ctrl-A/E/W/U/K, Option+Delete, word moves). The selected model is
diff --git a/src/agent.zig b/src/agent.zig
index c4e3966b..7bbe573d 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/cli.zig b/src/cli.zig
index 1eb61247..b554e5bc 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -61,7 +61,9 @@ pub const usage_text =
\\ graff key set <provider> <key> store a key (macOS Keychain, else 0600 file)
\\ graff key list show which providers have keys
\\ graff models [refresh] list the live catalog; refresh Codex + models.dev metadata
- \\ graff mcp add <name> -- <cmd> add an MCP server to .mcp.json
+ \\ graff mcp add <name> -- <cmd> add a stdio MCP server to .mcp.json
+ \\ graff mcp add <name> --url <url> add a Streamable HTTP MCP server
+ \\ graff mcp login <name> OAuth login for a remote MCP server
\\ graff mcp list configured MCP servers
\\ graff worktree list list the per-tab worktrees created by -w
\\ graff worktree merge <name> squash-land worktree-<name> onto the current branch + clean up
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 8b6029ee..3e386e87 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -41,6 +41,7 @@ const serde = @import("serde.zig");
const mcp_cli = @import("mcp_cli.zig");
const persistMcpServer = mcp_cli.persistMcpServer;
+const persistMcpUrl = mcp_cli.persistMcpUrl;
const skills = @import("skills.zig");
const mcp_notes = skills.mcp_notes;
@@ -183,22 +184,31 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
const arg = std.mem.trim(u8, line["/mcp".len..], " \t");
const reg = root.registry.?; // always present now
if (std.mem.startsWith(u8, arg, "add")) {
- // /mcp add <name> <command> [args...]
+ // /mcp add <name> <command> [args...] or <name> --url <URL>
var it = std.mem.tokenizeAny(u8, arg["add".len..], " \t");
const name = it.next() orelse {
- try out.writeAll("usage: /mcp add <name> <command> [args...] e.g. /mcp add fs npx -y @modelcontextprotocol/server-filesystem .\n");
+ try out.writeAll("usage: /mcp add <name> <command> [args...] | /mcp add <name> --url <URL>\n");
try out.flush();
return true;
};
const command = it.next() orelse {
- try out.writeAll("usage: /mcp add <name> <command> [args...]\n");
+ try out.writeAll("usage: /mcp add <name> <command> [args...] | /mcp add <name> --url <URL>\n");
try out.flush();
return true;
};
var args: std.ArrayList([]const u8) = .empty;
defer args.deinit(arena);
while (it.next()) |a| try args.append(arena, a);
- const added = reg.addServer(name, command, args.items) catch |err| {
+ const is_remote = std.mem.eql(u8, command, "--url");
+ if (is_remote and args.items.len != 1) {
+ try out.writeAll("usage: /mcp add <name> --url <URL>\n");
+ try out.flush();
+ return true;
+ }
+ const added = (if (is_remote)
+ reg.addRemoteServer(name, args.items[0], &.{})
+ else
+ reg.addServer(name, command, args.items)) catch |err| {
try out.print("{s}✗ failed to add MCP server '{s}': {t}{s}\n", .{ style.red, name, err, style.reset });
try out.flush();
return true;
@@ -208,7 +218,10 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
root.invalidateRootTools();
try root.ensureRootTools(root.provider.kind);
root.rebaseContextMeter();
- const persisted = persistMcpServer(root.io, arena, name, command, args.items);
+ const persisted = if (is_remote)
+ persistMcpUrl(root.io, arena, name, args.items[0], &.{})
+ else
+ persistMcpServer(root.io, arena, name, command, args.items);
var has_note = false;
for (mcp_notes) |mn| if (std.mem.eql(u8, mn.server, name)) {
has_note = true;
diff --git a/src/main.zig b/src/main.zig
index ceec6047..0d2cd2b1 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -375,7 +375,8 @@ pub fn main(init: std.process.Init) !void {
// MCP servers from .mcp.json. SECURITY: a workspace .mcp.json launches arbitrary local commands, so opening an untrusted repo could run them —
// auto-connect only with --yolo (trusted) or explicit per-session consent; otherwise start with an empty (but live) registry so `/mcp add`
// still works.
- var registry_storage = try session_start.initRegistryConsent(io, gpa, arena, out, in, flags, mcp_config_path, use_color, json_mode);
+ const mcp_home = homeEnv(init.environ_map) orelse "";
+ var registry_storage = try session_start.initRegistryConsent(io, gpa, arena, out, in, flags, mcp_config_path, mcp_home, use_color, json_mode);
boot.mark(io, "MCP registry");
defer registry_storage.deinit();
const registry: ?*mcp.Registry = &registry_storage;
@@ -392,7 +393,8 @@ pub fn main(init: std.process.Init) !void {
};
if (theme_setup.should_exit) return;
boot.mark(io, "settings/theme");
- try session_start.connectCompanion(io, &registry_storage, flags, out, json_mode);
+ const smolify_enabled = init.environ_map.get("GRAFF_NO_SMOLIFY") == null;
+ try session_start.connectCompanion(io, &registry_storage, flags, out, json_mode, smolify_enabled);
const mcp_tools: []const mcp.Tool = registry_storage.tools;
// If the metered companion connected, probe its license once so the note below can lean into paid tools (vs the conservative free-codedb note).
if (mcpServerConnected(mcp_tools, "codedbpro")) g_codedbpro_licensed = probeCodedbproLicensed(gpa, io);
diff --git a/src/mcp.zig b/src/mcp.zig
index cc357666..f01200c0 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -1,20 +1,21 @@
-//! Minimal MCP (Model Context Protocol) client over the stdio transport.
+//! Minimal MCP (Model Context Protocol) client over stdio and Streamable HTTP.
//!
-//! For each server in .mcp.json we spawn the configured command, speak
-//! newline-delimited JSON-RPC 2.0 over its stdin/stdout, run the
-//! initialize -> initialized -> tools/list handshake, and expose the
-//! discovered tools to the agent. Tool calls are routed back via tools/call.
+//! A .mcp.json entry may contain either `command`/`args` (a child process using
+//! newline-delimited JSON-RPC on stdio) or `url` (JSON-RPC POSTs using MCP's
+//! Streamable HTTP transport). Both run the initialize -> initialized ->
+//! tools/list handshake and expose discovered tools to the agent.
//!
-//! Concurrency: tool calls arrive from agent pool threads, but a single
-//! server is one bidirectional pipe — so every request/response round trip
-//! holds `mutex`, serializing access per registry. MCP calls are rare and
-//! fast relative to LLM calls, so global serialization is fine.
+//! Concurrency: tool calls arrive from agent pool threads, but transport state
+//! (stdio pipes, HTTP session IDs) is sequential, so every request/response
+//! round trip holds `mutex`. MCP calls are rare relative to LLM calls, so
+//! 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");
pub const Tool = struct {
server_index: usize,
@@ -55,9 +56,11 @@ fn rewriteOneOf(a: Allocator, v: *Value) Allocator.Error!void {
/// 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.
-/// The HTTP-only parts of the spec (MCP-Protocol-Version header, the
-/// HTTP+SSE removal) don't apply to this stdio-only client.
+/// 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);
@@ -110,11 +113,43 @@ fn stopChild(io: Io, child: *std.process.Child) void {
}
}
-const Server = struct {
- name: []const u8,
+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.
@@ -124,6 +159,7 @@ const Server = struct {
pub const Registry = struct {
gpa: Allocator,
io: Io,
+ home: []const u8,
arena_state: std.heap.ArenaAllocator,
mutex: Io.Mutex = .init,
servers: []*Server = &.{},
@@ -133,10 +169,11 @@ pub const Registry = struct {
return self.arena_state.allocator();
}
- /// Load .mcp.json (`{"mcpServers": {"name": {"command","args","env"}}}`),
- /// spawn each server, handshake, and collect their tools. Returns null
+ /// Load .mcp.json entries containing either `command`/`args`/`env` or a
+ /// Streamable HTTP `url`, handshake each server, and collect their tools.
+ /// Returns null
/// (no error) when the config file is absent — MCP is optional.
- pub fn init(gpa: Allocator, io: Io, config_path: []const u8) !?Registry {
+ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, home: []const u8) !?Registry {
const text = Io.Dir.cwd().readFileAlloc(io, config_path, gpa, .limited(1 << 20)) catch |err| switch (err) {
error.FileNotFound => return null,
else => return err,
@@ -146,6 +183,7 @@ pub const Registry = struct {
var reg: Registry = .{
.gpa = gpa,
.io = io,
+ .home = home,
.arena_state = std.heap.ArenaAllocator.init(gpa),
};
errdefer reg.deinit();
@@ -159,6 +197,9 @@ pub const Registry = struct {
var it = servers_obj.iterator();
while (it.next()) |entry| {
+ // The core Smolify name is pinned below and cannot be shadowed by
+ // repository configuration.
+ if (std.mem.eql(u8, entry.key_ptr.*, "smolify")) continue;
const name = try a.dupe(u8, entry.key_ptr.*);
const cfg = entry.value_ptr.*.object;
reg.startServer(a, &servers, &tools, name, cfg) catch |err| {
@@ -173,8 +214,8 @@ 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) Registry {
- return .{ .gpa = gpa, .io = io, .arena_state = std.heap.ArenaAllocator.init(gpa) };
+ pub fn empty(gpa: Allocator, io: Io, home: []const u8) Registry {
+ return .{ .gpa = gpa, .io = io, .home = home, .arena_state = std.heap.ArenaAllocator.init(gpa) };
}
/// Spawn + handshake a server at runtime and append its tools. Returns the
@@ -182,6 +223,8 @@ pub const Registry = struct {
/// callers must re-render their tool list afterward. Run between turns only
/// (no tool calls in flight).
pub fn addServer(reg: *Registry, name: []const u8, command: []const u8, args: []const []const u8) !usize {
+ for (reg.servers) |server| if (std.mem.eql(u8, server.name, name)) return error.McpServerAlreadyConnected;
+ if (std.mem.eql(u8, name, "smolify")) return error.ReservedMcpServerName;
const a = reg.arena();
var servers: std.ArrayList(*Server) = .empty;
try servers.appendSlice(a, reg.servers);
@@ -201,6 +244,40 @@ pub const Registry = struct {
return tools.items.len - before;
}
+ /// Connect a Streamable HTTP server at runtime. `headers` are copied into
+ /// registry storage and sent on every request (for example Authorization).
+ pub fn addRemoteServer(reg: *Registry, name: []const u8, url: []const u8, headers: []const std.http.Header) !usize {
+ for (reg.servers) |server| if (std.mem.eql(u8, server.name, name)) return error.McpServerAlreadyConnected;
+ if (std.mem.eql(u8, name, "smolify") and (!std.mem.eql(u8, url, smolify_url) or headers.len != 0)) return error.ReservedMcpServerName;
+ const a = reg.arena();
+ var servers: std.ArrayList(*Server) = .empty;
+ try servers.appendSlice(a, reg.servers);
+ var tools: std.ArrayList(Tool) = .empty;
+ try tools.appendSlice(a, reg.tools);
+ const before = tools.items.len;
+
+ var cfg: std.json.ObjectMap = .empty;
+ try cfg.put(a, "url", .{ .string = try a.dupe(u8, url) });
+ if (headers.len > 0) {
+ var header_obj: std.json.ObjectMap = .empty;
+ for (headers) |header| try header_obj.put(a, try a.dupe(u8, header.name), .{ .string = try a.dupe(u8, header.value) });
+ try cfg.put(a, "headers", .{ .object = header_obj });
+ }
+
+ try reg.startServer(a, &servers, &tools, try a.dupe(u8, name), cfg);
+ reg.servers = try a.dupe(*Server, servers.items);
+ reg.tools = try a.dupe(Tool, tools.items);
+ return tools.items.len - before;
+ }
+
+ /// Connect Smolify's public documentation MCP as a core service. It is a
+ /// stateless Streamable HTTP endpoint, so no helper process or Node runtime
+ /// is required. Public search/read tools work anonymously.
+ pub fn connectSmolify(reg: *Registry) !usize {
+ for (reg.servers) |server| if (std.mem.eql(u8, server.name, "smolify")) return 0;
+ return reg.addRemoteServer("smolify", smolify_url, &.{});
+ }
+
/// Connect any workspace `.mcp.json` servers not already running — the
/// in-session equivalent of having started with `--yolo`, so a user who
/// declined the startup consent prompt can opt in later without a restart.
@@ -229,6 +306,7 @@ pub const Registry = struct {
var it = servers_v.object.iterator();
while (it.next()) |entry| {
const name = entry.key_ptr.*;
+ if (std.mem.eql(u8, name, "smolify")) continue;
if (entry.value_ptr.* != .object) continue;
// Already connected (auto-activated muonry, or a prior /mcp trust)? skip.
var present = false;
@@ -259,6 +337,7 @@ pub const Registry = struct {
var n: usize = 0;
var it = servers_v.object.iterator();
while (it.next()) |entry| {
+ if (std.mem.eql(u8, entry.key_ptr.*, "smolify")) continue;
if (entry.value_ptr.* != .object) continue;
var present = false;
for (reg.servers) |s| if (std.mem.eql(u8, s.name, entry.key_ptr.*)) {
@@ -286,66 +365,98 @@ pub const Registry = struct {
name: []const u8,
cfg: std.json.ObjectMap,
) !void {
- const command = if (cfg.get("command")) |c| (if (c == .string) c.string else return error.BadMcpConfig) else return error.BadMcpConfig;
- var argv: std.ArrayList([]const u8) = .empty;
- try argv.append(a, command);
- if (cfg.get("args")) |args| if (args == .array) {
- for (args.array.items) |arg| if (arg == .string) try argv.append(a, arg.string);
- };
+ const command_v = cfg.get("command");
+ const url_v = cfg.get("url");
+ if ((command_v == null) == (url_v == null)) return error.BadMcpConfig;
- // Optional per-server env overlaid on the parent environment.
- var env_map: ?*std.process.Environ.Map = null;
- if (cfg.get("env")) |env| if (env == .object) {
- const m = try a.create(std.process.Environ.Map);
- m.* = std.process.Environ.Map.init(reg.gpa);
- var env_it = env.object.iterator();
- while (env_it.next()) |e| try m.put(e.key_ptr.*, e.value_ptr.*.string);
- env_map = m;
- };
+ 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;
+
+ var headers: std.ArrayList(std.http.Header) = .empty;
+ var has_authorization = false;
+ if (cfg.get("headers")) |headers_v| {
+ if (headers_v != .object) return error.BadMcpConfig;
+ var header_it = headers_v.object.iterator();
+ while (header_it.next()) |entry| {
+ if (entry.value_ptr.* != .string) return error.BadMcpConfig;
+ if (std.ascii.eqlIgnoreCase(entry.key_ptr.*, "authorization")) has_authorization = true;
+ try headers.append(a, .{
+ .name = try a.dupe(u8, entry.key_ptr.*),
+ .value = try a.dupe(u8, entry.value_ptr.*.string),
+ });
+ }
+ }
+ server.* = .{
+ .name = name,
+ .transport = .{ .http = .{
+ .url = try a.dupe(u8, url.string),
+ .client = .{ .allocator = reg.gpa, .io = reg.io },
+ .headers = try a.dupe(std.http.Header, headers.items),
+ .oauth_home = if (!has_authorization and reg.home.len != 0) try a.dupe(u8, reg.home) else null,
+ } },
+ };
+ } else {
+ const command = if (command_v.? == .string) command_v.?.string else return error.BadMcpConfig;
+ var argv: std.ArrayList([]const u8) = .empty;
+ try argv.append(a, command);
+ if (cfg.get("args")) |args| {
+ if (args != .array) return error.BadMcpConfig;
+ for (args.array.items) |arg| {
+ if (arg != .string) return error.BadMcpConfig;
+ try argv.append(a, arg.string);
+ }
+ }
- var child = try std.process.spawn(reg.io, .{
- .argv = argv.items,
- .stdin = .pipe,
- .stdout = .pipe,
- .stderr = .ignore, // server logs/banners stay off our JSON channel
- .environ_map = env_map,
- });
- // Until the server is appended below, we own the child and must kill
- // it on any error path. Once it's in `reg.servers`, `deinit` becomes
- // the sole owner: killing here *and* there would reap the pid twice,
- // and the second kill panics on ESRCH in debug builds (a server whose
- // handshake fails — McpClosed — has an already-dead child).
- var registry_owns_child = false;
- errdefer if (!registry_owns_child) {
- stopChild(reg.io, &child);
- };
+ // Optional per-server env overlaid on the parent environment.
+ var env_map: ?*std.process.Environ.Map = null;
+ if (cfg.get("env")) |env| {
+ if (env != .object) return error.BadMcpConfig;
+ const m = try a.create(std.process.Environ.Map);
+ m.* = std.process.Environ.Map.init(reg.gpa);
+ var env_it = env.object.iterator();
+ while (env_it.next()) |entry| {
+ if (entry.value_ptr.* != .string) return error.BadMcpConfig;
+ try m.put(entry.key_ptr.*, entry.value_ptr.*.string);
+ }
+ env_map = m;
+ }
- const server = try a.create(Server);
- const in_buf = try a.alloc(u8, 64 * 1024);
- const out_buf = try a.alloc(u8, 1 << 20);
- server.* = .{
- .name = name,
- .child = child,
- .stdin_writer = child.stdin.?.writerStreaming(reg.io, in_buf),
- .stdout_reader = child.stdout.?.readerStreaming(reg.io, out_buf),
- };
+ var child = try std.process.spawn(reg.io, .{
+ .argv = argv.items,
+ .stdin = .pipe,
+ .stdout = .pipe,
+ .stderr = .ignore,
+ .environ_map = env_map,
+ });
+ var server_owns_child = false;
+ errdefer if (!server_owns_child) {
+ stopChild(reg.io, &child);
+ };
+ const in_buf = try a.alloc(u8, 64 * 1024);
+ const out_buf = try a.alloc(u8, 1 << 20);
+ server.* = .{
+ .name = name,
+ .transport = .{ .stdio = .{
+ .child = child,
+ .stdin_writer = child.stdin.?.writerStreaming(reg.io, in_buf),
+ .stdout_reader = child.stdout.?.readerStreaming(reg.io, out_buf),
+ } },
+ };
+ server_owns_child = true;
+ }
+
+ var registry_owns_server = false;
+ errdefer if (!registry_owns_server) deinitServer(server, reg.io);
const server_index = servers.items.len;
- try servers.append(a, server);
- registry_owns_child = true; // deinit now owns the child; don't double-kill
+ 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 `latest_protocol`).
- const init_resp = try request(server, a,
- \\{"protocolVersion":"
- ++ 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 a.dupe(u8, pv.string);
- };
- };
- try notify(server, "notifications/initialized");
+ try initializeServer(server, a, a);
const listed = try request(server, a, "{}", "tools/list");
const result_v = listed.object.get("result") orelse return error.BadMcpResponse;
@@ -371,11 +482,13 @@ pub const Registry = struct {
.input_schema = schema,
});
}
+ try servers.append(a, server);
+ registry_owns_server = true;
std.debug.print(" [mcp:{s}] connected (mcp {s}) — {d} tool(s)\n", .{ name, server.protocol_version, tools_v.array.items.len });
}
pub fn deinit(reg: *Registry) void {
- for (reg.servers) |server| stopChild(reg.io, &server.child);
+ for (reg.servers) |server| deinitServer(server, reg.io);
reg.arena_state.deinit();
}
@@ -407,16 +520,34 @@ pub const Registry = struct {
reg.mutex.lockUncancelable(reg.io);
defer reg.mutex.unlock(reg.io);
- const a = reg.arena(); // response Values; freed at session end
- const resp = try request(server, a, pw.writer.buffered(), "tools/call");
+ // Tool responses can be large and numerous; keep them out of the
+ // session arena. Only the returned text is copied to `out_alloc`.
+ var response_arena_state = std.heap.ArenaAllocator.init(reg.gpa);
+ defer response_arena_state.deinit();
+ const response_alloc = response_arena_state.allocator();
+ const resp = request(server, response_alloc, pw.writer.buffered(), "tools/call") 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.
+ error.McpSessionExpired => retry: {
+ try initializeServer(server, response_alloc, reg.arena());
+ break :retry try request(server, response_alloc, pw.writer.buffered(), "tools/call");
+ },
+ else => return err,
+ };
if (resp.object.get("error")) |e| {
// Protocol-level failure (unknown tool, invalid args, server
// crash) — distinct from a tool that ran and *returned* an error
// (isError below). Keep the JSON-RPC code: models retry better
// when they can tell -32602 bad-params from a tool-side failure.
- const msg = if (e.object.get("message")) |m| m.string else "MCP error";
- const code: i64 = if (e.object.get("code")) |c| (if (c == .integer) c.integer else 0) else 0;
+ const msg = if (e == .object) blk: {
+ const m = e.object.get("message") orelse break :blk "MCP error";
+ break :blk if (m == .string) m.string else "MCP error";
+ } else "MCP error";
+ const code: i64 = if (e == .object) blk: {
+ const c = e.object.get("code") orelse break :blk 0;
+ break :blk if (c == .integer) c.integer else 0;
+ } else 0;
const text = if (code != 0)
try std.fmt.allocPrint(out_alloc, "MCP error {d}: {s}", .{ code, msg })
else
@@ -456,37 +587,346 @@ pub const Registry = struct {
}
};
-/// JSON-RPC request/response over one server's stdio pipe. `params` is a raw
-/// JSON object string. Skips interleaved notifications (messages without our
-/// id) until the matching response arrives. Result Values are arena-owned.
-fn request(server: *Server, a: Allocator, params: []const u8, method: []const u8) !Value {
+fn deinitServer(server: *Server, io: Io) void {
+ switch (server.transport) {
+ .stdio => |*stdio| stopChild(io, &stdio.child),
+ .http => |*http| {
+ if (http.session_id) |session_id| http.client.allocator.free(session_id);
+ http.client.deinit();
+ },
+ }
+}
+
+fn initializeServer(server: *Server, response_alloc: Allocator, session_alloc: Allocator) !void {
+ const init_resp = try request(server, response_alloc,
+ \\{"protocolVersion":"
+ ++ 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);
+ };
+ };
+ try notify(server, response_alloc, "notifications/initialized");
+}
+
+/// JSON-RPC request/response over either transport. `params` is a raw JSON
+/// object string. Result Values use `response_alloc`.
+fn request(server: *Server, response_alloc: Allocator, params: []const u8, method: []const u8) !Value {
const id = server.next_id;
server.next_id += 1;
- const w = &server.stdin_writer.interface;
- try w.print(
- \\{{"jsonrpc":"2.0","id":{d},"method":"{s}","params":{s}}}
- ++ "\n", .{ id, method, params });
- try w.flush();
-
- const r = &server.stdout_reader.interface;
- while (true) {
- const line = (try r.takeDelimiter('\n')) orelse return error.McpClosed;
- if (line.len == 0) continue;
- const parsed = std.json.parseFromSliceLeaky(Value, a, line, .{ .allocate = .alloc_always }) catch continue;
- if (parsed != .object) continue;
- const got = parsed.object.get("id") orelse continue; // notification
- if (got == .integer and got.integer == id) return parsed;
+ 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.flush();
+
+ 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;
+ }
+ },
+ .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")) latest_protocol else server.protocol_version;
+ const response_body = (try httpPost(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;
+ },
}
}
/// Fire-and-forget JSON-RPC notification (no id, no response).
-fn notify(server: *Server, method: []const u8) !void {
- const w = &server.stdin_writer.interface;
- try w.print(
- \\{{"jsonrpc":"2.0","method":"{s}","params":{{}}}}
- ++ "\n", .{method});
- try w.flush();
+fn notify(server: *Server, response_alloc: Allocator, method: []const u8) !void {
+ switch (server.transport) {
+ .stdio => |*stdio| {
+ const w = &stdio.stdin_writer.interface;
+ try w.print(
+ \\{{"jsonrpc":"2.0","method":"{s}","params":{{}}}}
+ ++ "\n", .{method});
+ try w.flush();
+ },
+ .http => |*http| {
+ 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| {
+ 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" {
diff --git a/src/mcp_cli.zig b/src/mcp_cli.zig
index 0ce0d90d..8e6cafe1 100644
--- a/src/mcp_cli.zig
+++ b/src/mcp_cli.zig
@@ -11,6 +11,8 @@ const Allocator = std.mem.Allocator;
const root = @import("main.zig");
const skills = @import("skills.zig");
+const mcp = @import("mcp.zig");
+const mcp_oauth = @import("mcp_oauth.zig");
const mcp_config_path = root.mcp_config_path;
const companion_servers = skills.companion_servers;
@@ -41,6 +43,9 @@ pub fn countMcpServers(io: Io, arena: Allocator) usize {
var n: usize = 0;
var it = servers.object.iterator();
while (it.next()) |entry| {
+ // `smolify` is a reserved core server; workspace entries cannot shadow
+ // its pinned endpoint and therefore need no workspace consent.
+ if (std.mem.eql(u8, entry.key_ptr.*, "smolify")) continue;
if (!trustedMcpEntry(entry.key_ptr.*, entry.value_ptr.*)) n += 1;
}
return n;
@@ -49,6 +54,7 @@ pub fn countMcpServers(io: Io, arena: Allocator) usize {
/// Best-effort write of a server entry into .mcp.json (so `/mcp add` survives
/// a restart). Merges into any existing config. Returns false on any error.
const McpEnvPair = struct { key: []const u8, value: []const u8 };
+pub const McpHeaderPair = struct { key: []const u8, value: []const u8 };
pub fn persistMcpServer(io: Io, arena: Allocator, name: []const u8, command: []const u8, args: []const []const u8) bool {
return persistMcpServerWithEnv(io, arena, name, command, args, &.{});
@@ -92,14 +98,56 @@ fn persistMcpServerWithEnv(io: Io, arena: Allocator, name: []const u8, command:
return true;
}
+/// Persist a native Streamable HTTP entry. Headers are optional and intended
+/// for static bearer/API tokens; OAuth-capable servers can remain anonymous
+/// until an authorization flow is configured.
+pub fn persistMcpUrl(io: Io, arena: Allocator, name: []const u8, url: []const u8, headers: []const McpHeaderPair) bool {
+ var root_obj: std.json.ObjectMap = .empty;
+ if (Io.Dir.cwd().readFileAlloc(io, mcp_config_path, arena, .limited(1 << 20))) |text| {
+ if (std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always })) |v| {
+ if (v == .object) root_obj = v.object;
+ } else |_| {}
+ } else |_| {}
+
+ var servers: std.json.ObjectMap = .empty;
+ if (root_obj.get("mcpServers")) |m| if (m == .object) {
+ servers = m.object;
+ };
+ var entry: std.json.ObjectMap = .empty;
+ entry.put(arena, "url", .{ .string = url }) catch return false;
+ if (headers.len > 0) {
+ var header_obj: std.json.ObjectMap = .empty;
+ for (headers) |header| header_obj.put(arena, header.key, .{ .string = header.value }) catch return false;
+ entry.put(arena, "headers", .{ .object = header_obj }) catch return false;
+ }
+ servers.put(arena, name, .{ .object = entry }) catch return false;
+ root_obj.put(arena, "mcpServers", .{ .object = servers }) catch return false;
+
+ var aw: Io.Writer.Allocating = .init(arena);
+ var stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ stringify.write(Value{ .object = root_obj }) catch return false;
+ const file = Io.Dir.cwd().createFile(io, mcp_config_path, .{}) catch return false;
+ defer file.close(io);
+ var buffer: [4096]u8 = undefined;
+ var writer = file.writer(io, &buffer);
+ writer.interface.writeAll(aw.writer.buffered()) catch return false;
+ writer.interface.flush() catch return false;
+ return true;
+}
+
fn mcpCliUsage(w: *Io.Writer) !void {
try w.writeAll(
\\usage:
\\ graff mcp list servers in .mcp.json
+ \\ graff mcp add <name> --url <https://...> [--header KEY=VALUE ...]
+ \\ graff mcp login <name> OAuth login for a remote server
\\ graff mcp add <name> [--env KEY=VALUE ...] -- <command> [args...]
\\ graff mcp add <name> <command> [args...]
\\
\\examples:
+ \\ graff mcp add mobbin --url https://api.mobbin.com/mcp
+ \\ graff mcp login mobbin
+ \\ graff mcp login smolify
\\ graff mcp add context7 -- npx -y @upstash/context7-mcp
\\ graff mcp add playwright -- npx -y @playwright/mcp
\\ graff mcp add sentry --env SENTRY_AUTH_TOKEN=... -- npx -y @sentry/mcp-server
@@ -107,7 +155,7 @@ fn mcpCliUsage(w: *Io.Writer) !void {
);
}
-pub fn mcpCommand(io: Io, arena: Allocator, args: []const []const u8) !void {
+pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, args: []const []const u8) !void {
var obuf: [4096]u8 = undefined;
var out = Io.File.stdout().writer(io, &obuf);
@@ -134,11 +182,15 @@ pub fn mcpCommand(io: Io, arena: Allocator, args: []const []const u8) !void {
while (it.next()) |entry| {
const cfg = entry.value_ptr.*;
if (cfg != .object) continue;
- const command = if (cfg.object.get("command")) |c| if (c == .string) c.string else "?" else "?";
- try out.interface.print(" {s}: {s}", .{ entry.key_ptr.*, command });
- if (cfg.object.get("args")) |argv| if (argv == .array) for (argv.array.items) |a| {
- if (a == .string) try out.interface.print(" {s}", .{a.string});
- };
+ if (cfg.object.get("url")) |url| {
+ try out.interface.print(" {s}: {s}", .{ entry.key_ptr.*, if (url == .string) url.string else "?" });
+ } else {
+ const command = if (cfg.object.get("command")) |c| if (c == .string) c.string else "?" else "?";
+ try out.interface.print(" {s}: {s}", .{ entry.key_ptr.*, command });
+ if (cfg.object.get("args")) |argv| if (argv == .array) for (argv.array.items) |arg| {
+ if (arg == .string) try out.interface.print(" {s}", .{arg.string});
+ };
+ }
try out.interface.writeByte('\n');
}
}
@@ -152,6 +204,33 @@ pub fn mcpCommand(io: Io, arena: Allocator, args: []const []const u8) !void {
return;
}
+ if (std.mem.eql(u8, args[0], "login")) {
+ if (args.len != 2) {
+ try out.interface.writeAll("usage: graff mcp login <name>\n");
+ try out.interface.flush();
+ return;
+ }
+ const name = args[1];
+ const url = if (std.mem.eql(u8, name, "smolify"))
+ mcp.smolify_url
+ else url: {
+ const data = Io.Dir.cwd().readFileAlloc(io, mcp_config_path, arena, .limited(1 << 20)) catch
+ std.process.fatal("mcp login: no .mcp.json; add the remote server first", .{});
+ const config = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch
+ std.process.fatal("mcp login: .mcp.json is not valid JSON", .{});
+ if (config != .object) std.process.fatal("mcp login: .mcp.json is not an object", .{});
+ const servers = config.object.get("mcpServers") orelse std.process.fatal("mcp login: server '{s}' is not configured", .{name});
+ if (servers != .object) std.process.fatal("mcp login: mcpServers is not an object", .{});
+ const entry = servers.object.get(name) orelse std.process.fatal("mcp login: server '{s}' is not configured", .{name});
+ if (entry != .object) std.process.fatal("mcp login: server '{s}' has invalid config", .{name});
+ const remote = entry.object.get("url") orelse std.process.fatal("mcp login: server '{s}' is not a remote URL server", .{name});
+ if (remote != .string or !mcp.validRemoteUrl(remote.string)) std.process.fatal("mcp login: server '{s}' has an invalid URL", .{name});
+ break :url remote.string;
+ };
+ try mcp_oauth.login(io, gpa, arena, home, name, url);
+ return;
+ }
+
if (!std.mem.eql(u8, args[0], "add")) {
try mcpCliUsage(&out.interface);
try out.interface.flush();
@@ -164,6 +243,36 @@ pub fn mcpCommand(io: Io, arena: Allocator, args: []const []const u8) !void {
}
const name = args[1];
+ if (std.mem.eql(u8, name, "smolify")) std.process.fatal("mcp add: 'smolify' is a reserved core server", .{});
+ if (std.mem.eql(u8, args[2], "--url") or std.mem.startsWith(u8, args[2], "--url=")) {
+ const url = if (std.mem.eql(u8, args[2], "--url")) blk: {
+ if (args.len < 4) std.process.fatal("mcp add: --url needs an HTTP(S) URL", .{});
+ break :blk args[3];
+ } else args[2]["--url=".len..];
+ if (!mcp.validRemoteUrl(url)) std.process.fatal("mcp add: URL must use HTTPS (HTTP is allowed only for localhost)", .{});
+ const first_option: usize = if (std.mem.eql(u8, args[2], "--url")) 4 else 3;
+ var headers: std.ArrayList(McpHeaderPair) = .empty;
+ defer headers.deinit(arena);
+ var j = first_option;
+ while (j < args.len) : (j += 1) {
+ const arg = args[j];
+ const raw = if (std.mem.eql(u8, arg, "--header")) value: {
+ j += 1;
+ if (j >= args.len) std.process.fatal("mcp add: --header needs KEY=VALUE", .{});
+ break :value args[j];
+ } else if (std.mem.startsWith(u8, arg, "--header="))
+ arg["--header=".len..]
+ else
+ std.process.fatal("mcp add: unexpected URL option '{s}'", .{arg});
+ const eq = std.mem.indexOfScalar(u8, raw, '=') orelse std.process.fatal("mcp add: --header expects KEY=VALUE", .{});
+ try headers.append(arena, .{ .key = raw[0..eq], .value = raw[eq + 1 ..] });
+ }
+ if (!persistMcpUrl(io, arena, name, url, headers.items)) std.process.fatal("could not write .mcp.json", .{});
+ try out.interface.print("saved Streamable HTTP MCP server '{s}' to .mcp.json\n", .{name});
+ try out.interface.flush();
+ return;
+ }
+
var env_pairs: std.ArrayList(McpEnvPair) = .empty;
defer env_pairs.deinit(arena);
var command_index: ?usize = null;
@@ -217,4 +326,10 @@ test "trustedMcpEntry: only the exact companion shape skips the consent gate" {
try std.testing.expect(!trustedMcpEntry("muonry", parse(a, "{\"command\":\"muonry\",\"args\":[\"--mcp\",\"--evil\"]}")));
try std.testing.expect(!trustedMcpEntry("muonry", parse(a, "{\"command\":\"./muonry\",\"args\":[\"--mcp\"]}")));
try std.testing.expect(!trustedMcpEntry("other", parse(a, "{\"command\":\"muonry\"}")));
+ // Workspace remote servers cross a network/data boundary and need consent
+ // just like local commands.
+ try std.testing.expect(!trustedMcpEntry("remote", parse(a, "{\"url\":\"https://example.com/mcp\"}")));
+ try std.testing.expect(!trustedMcpEntry("local-http", parse(a, "{\"url\":\"http://127.0.0.1:3000/mcp\"}")));
+ try std.testing.expect(!trustedMcpEntry("remote", parse(a, "{\"url\":\"file:///tmp/mcp\"}")));
+ try std.testing.expect(!trustedMcpEntry("remote", parse(a, "{\"url\":\"https://example.com/mcp\",\"command\":\"evil\"}")));
}
diff --git a/src/mcp_oauth.zig b/src/mcp_oauth.zig
new file mode 100644
index 00000000..2cce0407
--- /dev/null
+++ b/src/mcp_oauth.zig
@@ -0,0 +1,580 @@
+//! OAuth 2.1 support for remote MCP servers. This is deliberately a leaf
+//! module: callers supply all allocators, I/O, and the user's home directory.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const util = @import("util.zig");
+
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+const max_response = 1024 * 1024;
+const redirect_uri = "http://127.0.0.1:1456/callback";
+const smolify_resource = "https://app.smol.ly/mcp";
+const smolify_read_scopes = "profile email offline_access projects:read docs:read";
+
+const EndpointSet = struct {
+ issuer: []const u8,
+ authorization: []const u8,
+ token: []const u8,
+ registration: []const u8,
+ scope: []const u8 = "",
+};
+
+const ClientInfo = struct {
+ id: []const u8,
+ secret: []const u8 = "",
+};
+
+const TokenSet = struct {
+ access: []const u8,
+ refresh: []const u8 = "",
+ 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, "/")});
+}
+
+fn writePercentEncoded(w: *Io.Writer, value: []const u8) !void {
+ const hex = "0123456789ABCDEF";
+ for (value) |c| {
+ if (std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~') {
+ try w.writeByte(c);
+ } else {
+ try w.writeAll(&.{ '%', hex[c >> 4], hex[c & 15] });
+ }
+ }
+}
+
+fn formEncode(arena: Allocator, fields: []const struct { []const u8, []const u8 }) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ for (fields, 0..) |field, i| {
+ if (i != 0) try aw.writer.writeByte('&');
+ try writePercentEncoded(&aw.writer, field[0]);
+ try aw.writer.writeByte('=');
+ try writePercentEncoded(&aw.writer, field[1]);
+ }
+ return aw.writer.buffered();
+}
+
+fn jsonObject(body: []const u8, arena: Allocator) !std.json.ObjectMap {
+ const v = try std.json.parseFromSliceLeaky(Value, arena, body, .{ .allocate = .alloc_always });
+ if (v != .object) return error.BadOAuthResponse;
+ return v.object;
+}
+
+fn stringField(obj: std.json.ObjectMap, name: []const u8) ?[]const u8 {
+ const v = obj.get(name) orelse return null;
+ return if (v == .string) v.string else null;
+}
+
+fn integerField(obj: std.json.ObjectMap, name: []const u8) ?i64 {
+ const v = obj.get(name) orelse return null;
+ return if (v == .integer) v.integer else null;
+}
+
+fn supportedScopes(arena: Allocator, metadata: std.json.ObjectMap) ![]const u8 {
+ const scopes = metadata.get("scopes_supported") orelse return "";
+ if (scopes != .array) return error.BadOAuthResponse;
+ var aw: Io.Writer.Allocating = .init(arena);
+ for (scopes.array.items) |scope| {
+ if (scope != .string) return error.BadOAuthResponse;
+ if (aw.writer.buffered().len != 0) try aw.writer.writeByte(' ');
+ try aw.writer.writeAll(scope.string);
+ }
+ return aw.writer.buffered();
+}
+
+fn fetchJson(io: Io, gpa: Allocator, arena: Allocator, url: []const u8) !std.json.ObjectMap {
+ try requireHttps(url);
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ const storage = try arena.alloc(u8, max_response);
+ var writer: Io.Writer = .fixed(storage);
+ const headers = [_]std.http.Header{.{ .name = "Accept", .value = "application/json" }};
+ const res = try client.fetch(.{
+ .location = .{ .url = url },
+ .method = .GET,
+ .response_writer = &writer,
+ .redirect_behavior = .not_allowed,
+ .extra_headers = &headers,
+ });
+ if (@intFromEnum(res.status) < 200 or @intFromEnum(res.status) >= 300) return error.OAuthHttpFailure;
+ return jsonObject(writer.buffered(), arena);
+}
+
+fn postJson(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, payload: []const u8) !std.json.ObjectMap {
+ try requireHttps(url);
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ const storage = try arena.alloc(u8, max_response);
+ var writer: Io.Writer = .fixed(storage);
+ const headers = [_]std.http.Header{.{ .name = "Accept", .value = "application/json" }};
+ const res = try client.fetch(.{
+ .location = .{ .url = url },
+ .method = .POST,
+ .payload = payload,
+ .response_writer = &writer,
+ .redirect_behavior = .not_allowed,
+ .headers = .{ .content_type = .{ .override = "application/json" } },
+ .extra_headers = &headers,
+ });
+ if (@intFromEnum(res.status) < 200 or @intFromEnum(res.status) >= 300) return error.OAuthHttpFailure;
+ return jsonObject(writer.buffered(), arena);
+}
+
+fn postForm(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, payload: []const u8) !std.json.ObjectMap {
+ try requireHttps(url);
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ const storage = try arena.alloc(u8, max_response);
+ var writer: Io.Writer = .fixed(storage);
+ const headers = [_]std.http.Header{.{ .name = "Accept", .value = "application/json" }};
+ const res = try client.fetch(.{
+ .location = .{ .url = url },
+ .method = .POST,
+ .payload = payload,
+ .response_writer = &writer,
+ .redirect_behavior = .not_allowed,
+ .headers = .{ .content_type = .{ .override = "application/x-www-form-urlencoded" } },
+ .extra_headers = &headers,
+ });
+ if (@intFromEnum(res.status) < 200 or @intFromEnum(res.status) >= 300) return error.OAuthHttpFailure;
+ return jsonObject(writer.buffered(), arena);
+}
+
+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;
+
+ const servers = resource_metadata.get("authorization_servers") orelse return error.MissingAuthorizationServer;
+ if (servers != .array or servers.array.items.len == 0) return error.MissingAuthorizationServer;
+ var issuer: ?[]const u8 = null;
+ for (servers.array.items) |server| {
+ if (server != .string) continue;
+ requireHttps(server.string) catch continue;
+ issuer = server.string;
+ break;
+ }
+ 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,
+ };
+}
+
+fn registerClient(io: Io, gpa: Allocator, arena: Allocator, endpoint: []const u8, server_name: []const u8) !ClientInfo {
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(arena, "client_name", .{ .string = server_name });
+ try obj.put(arena, "token_endpoint_auth_method", .{ .string = "none" });
+ var redirects = std.json.Array.init(arena);
+ try redirects.append(.{ .string = redirect_uri });
+ try obj.put(arena, "redirect_uris", .{ .array = redirects });
+ var grants = std.json.Array.init(arena);
+ try grants.append(.{ .string = "authorization_code" });
+ try grants.append(.{ .string = "refresh_token" });
+ try obj.put(arena, "grant_types", .{ .array = grants });
+ var responses = std.json.Array.init(arena);
+ try responses.append(.{ .string = "code" });
+ try obj.put(arena, "response_types", .{ .array = responses });
+ var aw: Io.Writer.Allocating = .init(arena);
+ var stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ try stringify.write(Value{ .object = obj });
+ const response = try postJson(io, gpa, arena, endpoint, aw.writer.buffered());
+ return .{
+ .id = stringField(response, "client_id") orelse return error.BadOAuthResponse,
+ .secret = stringField(response, "client_secret") orelse "",
+ };
+}
+
+fn b64url(arena: Allocator, bytes: []const u8) ![]const u8 {
+ const encoder = std.base64.url_safe_no_pad.Encoder;
+ const result = try arena.alloc(u8, encoder.calcSize(bytes.len));
+ return encoder.encode(result, bytes);
+}
+
+fn openBrowser(io: Io, url: []const u8) void {
+ const argv: []const []const u8 = if (builtin.os.tag == .macos)
+ &.{ "open", url }
+ else if (builtin.os.tag == .windows)
+ // Avoid cmd.exe: OAuth URLs contain '&', and passing discovered URLs
+ // through a shell would both truncate them and permit injection.
+ &.{ "rundll32.exe", "url.dll,FileProtocolHandler", url }
+ else
+ &.{ "xdg-open", url };
+ var child = std.process.spawn(io, .{ .argv = argv, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore }) catch return;
+ _ = child.wait(io) catch {};
+}
+
+fn hexNibble(c: u8) ?u8 {
+ return switch (c) {
+ '0'...'9' => c - '0',
+ 'a'...'f' => c - 'a' + 10,
+ 'A'...'F' => c - 'A' + 10,
+ else => null,
+ };
+}
+
+fn percentDecode(arena: Allocator, encoded: []const u8) ![]const u8 {
+ const out = try arena.alloc(u8, encoded.len);
+ var src: usize = 0;
+ var dst: usize = 0;
+ while (src < encoded.len) {
+ if (encoded[src] == '%') {
+ if (src + 2 >= encoded.len) return error.BadOAuthResponse;
+ const hi = hexNibble(encoded[src + 1]) orelse return error.BadOAuthResponse;
+ const lo = hexNibble(encoded[src + 2]) orelse return error.BadOAuthResponse;
+ out[dst] = (hi << 4) | lo;
+ src += 3;
+ } else {
+ out[dst] = if (encoded[src] == '+') ' ' else encoded[src];
+ src += 1;
+ }
+ dst += 1;
+ }
+ return out[0..dst];
+}
+
+fn queryParam(arena: Allocator, request_line: []const u8, name: []const u8) !?[]const u8 {
+ const target_start = std.mem.indexOfScalar(u8, request_line, ' ') orelse return error.BadOAuthResponse;
+ const target_tail = request_line[target_start + 1 ..];
+ const target_end = std.mem.indexOfScalar(u8, target_tail, ' ') orelse return error.BadOAuthResponse;
+ const target = target_tail[0..target_end];
+ const qmark = std.mem.indexOfScalar(u8, target, '?') orelse return null;
+ var pairs = std.mem.splitScalar(u8, target[qmark + 1 ..], '&');
+ while (pairs.next()) |pair| {
+ const equal = std.mem.indexOfScalar(u8, pair, '=') orelse continue;
+ if (std.mem.eql(u8, pair[0..equal], name)) return try percentDecode(arena, pair[equal + 1 ..]);
+ }
+ return null;
+}
+
+fn tokenFromResponse(obj: std.json.ObjectMap, io: Io) !TokenSet {
+ const access = stringField(obj, "access_token") orelse return error.BadOAuthResponse;
+ const now = util.unixMs(io);
+ const expires_at = if (integerField(obj, "expires_in")) |expires_in|
+ if (expires_in <= 0)
+ now
+ else if (expires_in > @divTrunc(std.math.maxInt(i64) - now, 1000))
+ std.math.maxInt(i64)
+ else
+ now + expires_in * 1000
+ else
+ std.math.maxInt(i64);
+ return .{
+ .access = access,
+ .refresh = stringField(obj, "refresh_token") orelse "",
+ .expires_at_ms = expires_at,
+ };
+}
+
+fn credentialPath(arena: Allocator, home: []const u8, resource_url: []const u8) ![]const u8 {
+ var digest: [32]u8 = undefined;
+ std.crypto.hash.sha2.Sha256.hash(resource_url, &digest, .{});
+ const hex = std.fmt.bytesToHex(digest, .lower);
+ return std.fmt.allocPrint(arena, "{s}/.simple-harness-mcp/{s}.json", .{ home, &hex });
+}
+
+fn secureWindowsCredentials(io: Io, dir: []const u8, path: []const u8) !void {
+ // Zig 0.16 does not implement chmod on Windows. Remove inherited ACLs and
+ // grant full control only to the file owner, using a fixed SID and a
+ // hash-only basename so no shell or user-controlled command text is used.
+ const argv: []const []const u8 = &.{
+ "icacls.exe",
+ std.fs.path.basename(path),
+ "/inheritance:r",
+ "/grant:r",
+ "*S-1-3-4:F",
+ };
+ var child = try std.process.spawn(io, .{
+ .argv = argv,
+ .cwd = .{ .path = dir },
+ .stdin = .ignore,
+ .stdout = .ignore,
+ .stderr = .ignore,
+ });
+ const term = try child.wait(io);
+ if (term != .exited or term.exited != 0) return error.CredentialPermissionsFailed;
+}
+
+fn writeCredentials(io: Io, arena: Allocator, home: []const u8, resource_url: []const u8, endpoints: EndpointSet, client: ClientInfo, tokens: TokenSet) !void {
+ const dir = try std.fmt.allocPrint(arena, "{s}/.simple-harness-mcp", .{home});
+ Io.Dir.cwd().createDir(io, dir, .default_dir) catch |err| switch (err) {
+ error.PathAlreadyExists => {},
+ else => return err,
+ };
+ const path = try credentialPath(arena, home, resource_url);
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(arena, "resource", .{ .string = resource_url });
+ try obj.put(arena, "issuer", .{ .string = endpoints.issuer });
+ try obj.put(arena, "authorization_endpoint", .{ .string = endpoints.authorization });
+ try obj.put(arena, "token_endpoint", .{ .string = endpoints.token });
+ try obj.put(arena, "registration_endpoint", .{ .string = endpoints.registration });
+ try obj.put(arena, "scope", .{ .string = endpoints.scope });
+ try obj.put(arena, "client_id", .{ .string = client.id });
+ try obj.put(arena, "client_secret", .{ .string = client.secret });
+ try obj.put(arena, "access_token", .{ .string = tokens.access });
+ try obj.put(arena, "refresh_token", .{ .string = tokens.refresh });
+ try obj.put(arena, "expires_at_ms", .{ .integer = tokens.expires_at_ms });
+ var aw: Io.Writer.Allocating = .init(arena);
+ var stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ try stringify.write(Value{ .object = obj });
+ const user_only: Io.Dir.Permissions = @enumFromInt(0o600);
+ {
+ const file = try Io.Dir.cwd().createFile(io, path, .{ .permissions = user_only });
+ defer file.close(io);
+ var buffer: [4096]u8 = undefined;
+ var fw = file.writer(io, &buffer);
+ try fw.interface.writeAll(aw.writer.buffered());
+ try fw.interface.flush();
+ }
+ if (builtin.os.tag == .windows)
+ try secureWindowsCredentials(io, dir, path)
+ else
+ try Io.Dir.cwd().setFilePermissions(io, path, user_only, .{});
+}
+
+fn loginInner(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, server_name: []const u8, resource_url: []const u8, out: *Io.Writer) !void {
+ try requireHttps(resource_url);
+ try out.print("Discovering OAuth configuration for {s}…\n", .{resource_url});
+ try out.flush();
+ const endpoints = try discover(io, gpa, arena, resource_url);
+ try out.print("Registering {s} with {s}…\n", .{ server_name, endpoints.issuer });
+ try out.flush();
+ const client = try registerClient(io, gpa, arena, endpoints.registration, server_name);
+
+ var verifier_bytes: [48]u8 = undefined;
+ io.random(&verifier_bytes);
+ const verifier = try b64url(arena, &verifier_bytes);
+ var challenge_bytes: [32]u8 = undefined;
+ std.crypto.hash.sha2.Sha256.hash(verifier, &challenge_bytes, .{});
+ const challenge = try b64url(arena, &challenge_bytes);
+ var state_bytes: [24]u8 = undefined;
+ io.random(&state_bytes);
+ const state = try b64url(arena, &state_bytes);
+
+ var authorization_fields: std.ArrayList(struct { []const u8, []const u8 }) = .empty;
+ try authorization_fields.append(arena, .{ "response_type", "code" });
+ try authorization_fields.append(arena, .{ "client_id", client.id });
+ try authorization_fields.append(arena, .{ "redirect_uri", redirect_uri });
+ try authorization_fields.append(arena, .{ "code_challenge", challenge });
+ try authorization_fields.append(arena, .{ "code_challenge_method", "S256" });
+ try authorization_fields.append(arena, .{ "state", state });
+ if (endpoints.scope.len != 0) try authorization_fields.append(arena, .{ "scope", endpoints.scope });
+ try authorization_fields.append(arena, .{ "resource", resource_url });
+ const query = try formEncode(arena, authorization_fields.items);
+ const authorization_url = try std.fmt.allocPrint(arena, "{s}{c}{s}", .{
+ endpoints.authorization,
+ @as(u8, if (std.mem.indexOfScalar(u8, endpoints.authorization, '?') == null) '?' else '&'),
+ query,
+ });
+
+ var address = std.Io.net.IpAddress.parseLiteral("127.0.0.1:1456") catch return error.BadOAuthResponse;
+ var listener = try std.Io.net.IpAddress.listen(&address, io, .{});
+ defer listener.deinit(io);
+ try out.print("\nOpen this URL to authorize (the browser should open automatically):\n\n{s}\n\nWaiting for the callback on {s} …\n", .{ authorization_url, redirect_uri });
+ try out.flush();
+ openBrowser(io, authorization_url);
+
+ const stream = try listener.accept(io);
+ defer stream.close(io);
+ var read_buffer: [16 * 1024]u8 = undefined;
+ var reader = std.Io.net.Stream.Reader.init(stream, io, &read_buffer);
+ const request_line = (reader.interface.takeDelimiter('\n') catch null) orelse return error.BadOAuthResponse;
+ const code = try queryParam(arena, request_line, "code") orelse {
+ const description = try queryParam(arena, request_line, "error_description") orelse
+ try queryParam(arena, request_line, "error") orelse "authorization server returned no code";
+ try out.print("OAuth authorization failed: {s}\n", .{description});
+ try out.flush();
+ return error.AuthorizationDenied;
+ };
+ const returned_state = try queryParam(arena, request_line, "state") orelse return error.StateMismatch;
+
+ var write_buffer: [2048]u8 = undefined;
+ var stream_writer = std.Io.net.Stream.Writer.init(stream, io, &write_buffer);
+ if (!std.mem.eql(u8, state, returned_state)) {
+ try stream_writer.interface.writeAll("HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nOAuth state mismatch. Return to the CLI and try again.\n");
+ try stream_writer.interface.flush();
+ return error.StateMismatch;
+ }
+ try stream_writer.interface.writeAll("HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nMCP authorization complete. You can close this tab.\n");
+ try stream_writer.interface.flush();
+
+ var fields = [_]struct { []const u8, []const u8 }{
+ .{ "grant_type", "authorization_code" },
+ .{ "client_id", client.id },
+ .{ "code", code },
+ .{ "redirect_uri", redirect_uri },
+ .{ "code_verifier", verifier },
+ .{ "resource", resource_url },
+ .{ "client_secret", client.secret },
+ };
+ const field_count: usize = if (client.secret.len == 0) fields.len - 1 else fields.len;
+ const response = try postForm(io, gpa, arena, endpoints.token, try formEncode(arena, fields[0..field_count]));
+ const tokens = try tokenFromResponse(response, io);
+ try writeCredentials(io, arena, home, resource_url, endpoints, client, tokens);
+ try out.print("✓ {s} authorized; credentials saved to {s}\n", .{ server_name, try credentialPath(arena, home, resource_url) });
+ try out.flush();
+}
+
+/// Discover, register, and run an OAuth 2.1 authorization-code + PKCE flow for
+/// an MCP protected resource, then persist the resulting credentials.
+pub fn login(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, server_name: []const u8, resource_url: []const u8) !void {
+ if (home.len == 0) return error.HomeDirectoryUnavailable;
+ var buffer: [4096]u8 = undefined;
+ var stdout = Io.File.stdout().writer(io, &buffer);
+ loginInner(io, gpa, arena, home, server_name, resource_url, &stdout.interface) catch |err| {
+ try stdout.interface.print("✗ MCP OAuth login failed: {t}. Check the server URL and authorization-server metadata, then try again.\n", .{err});
+ try stdout.interface.flush();
+ return err;
+ };
+}
+
+/// Load a resource's persisted access token. Tokens within one minute of
+/// expiry are refreshed first; any malformed, insecure, or failed credential
+/// set is treated as unavailable.
+pub fn loadAccessToken(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, resource_url: []const u8) ?[]const u8 {
+ if (home.len == 0) return null;
+ requireHttps(resource_url) catch return null;
+ const path = credentialPath(arena, home, resource_url) catch return null;
+ const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(max_response)) catch return null;
+ const obj = jsonObject(data, arena) catch return null;
+ const stored_resource = stringField(obj, "resource") orelse return null;
+ if (!std.mem.eql(u8, stored_resource, resource_url)) return null;
+ const access = stringField(obj, "access_token") orelse return null;
+ const expires_at = integerField(obj, "expires_at_ms") orelse return null;
+ if (expires_at > util.unixMs(io) + 60_000) return access;
+
+ const refresh = stringField(obj, "refresh_token") orelse return null;
+ if (refresh.len == 0) return null;
+ const token_endpoint = stringField(obj, "token_endpoint") orelse return null;
+ requireHttps(token_endpoint) catch return null;
+ const client = ClientInfo{
+ .id = stringField(obj, "client_id") orelse return null,
+ .secret = stringField(obj, "client_secret") orelse "",
+ };
+ const fields = [_]struct { []const u8, []const u8 }{
+ .{ "grant_type", "refresh_token" },
+ .{ "client_id", client.id },
+ .{ "refresh_token", refresh },
+ .{ "resource", resource_url },
+ .{ "client_secret", client.secret },
+ };
+ const field_count: usize = if (client.secret.len == 0) fields.len - 1 else fields.len;
+ const response = postForm(io, gpa, arena, token_endpoint, formEncode(arena, fields[0..field_count]) catch return null) catch return null;
+ var tokens = tokenFromResponse(response, io) catch return null;
+ if (tokens.refresh.len == 0) tokens.refresh = refresh;
+ const endpoints = EndpointSet{
+ .issuer = stringField(obj, "issuer") orelse return null,
+ .authorization = stringField(obj, "authorization_endpoint") orelse return null,
+ .token = token_endpoint,
+ .registration = stringField(obj, "registration_endpoint") orelse return null,
+ .scope = stringField(obj, "scope") orelse "",
+ };
+ writeCredentials(io, arena, home, resource_url, endpoints, client, tokens) catch return null;
+ 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();
+ const encoded = try formEncode(arena_state.allocator(), &.{
+ .{ "plain", "AZaz09-._~" },
+ .{ "space + slash", "a b+c/d" },
+ });
+ try std.testing.expectEqualStrings("plain=AZaz09-._~&space%20%2B%20slash=a%20b%2Bc%2Fd", encoded);
+}
+
+test "supported scopes are joined for authorization requests" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const metadata = try jsonObject("{\"scopes_supported\":[\"openid\",\"docs:read\",\"offline_access\"]}", arena);
+ try std.testing.expectEqualStrings("openid docs:read offline_access", try supportedScopes(arena, metadata));
+}
+
+test "credential path is stable and resource-specific" {
+ const path = try credentialPath(std.testing.allocator, "/home/alice", "https://mcp.example/api");
+ defer std.testing.allocator.free(path);
+ try std.testing.expectEqualStrings(
+ "/home/alice/.simple-harness-mcp/d48481de503249e9a60247e669c522a432c2685e9af626d9d7e15794ab8f092e.json",
+ path,
+ );
+}
diff --git a/src/session_start.zig b/src/session_start.zig
index 276ac698..324cb213 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -246,22 +246,22 @@ pub fn initTelemetry(io: Io, gpa: Allocator, client: *std.http.Client, environ_m
/// `/mcp add` still works. Moved out of main() (600-line goal). Returns the
/// Registry by value — mcp.Registry holds no self-references (its storage
/// is ArrayList/HashMap-backed), so returning it is safe.
-pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Writer, in: *Io.Reader, flags: args.Flags, mcp_config_path: []const u8, use_color: bool, json_mode: bool) !mcp.Registry {
+pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Writer, in: *Io.Reader, flags: args.Flags, mcp_config_path: []const u8, home: []const u8, use_color: bool, json_mode: bool) !mcp.Registry {
const mcp_count = mcp_cli.countMcpServers(io, arena);
var connect_mcp = flags.yolo_flag or mcp_count == 0;
if (mcp_count > 0 and !flags.yolo_flag and !json_mode and use_color) {
- try out.print("{s}⚠ this workspace's .mcp.json defines {d} MCP server(s) that run local commands. Connect them this session? [y/N] {s}", .{ ansi.style.bold, mcp_count, ansi.style.reset });
+ try out.print("{s}⚠ this workspace's .mcp.json defines {d} untrusted MCP server(s). They may run local commands or receive data over the network. Connect them this session? [y/N] {s}", .{ ansi.style.bold, mcp_count, ansi.style.reset });
try out.flush();
const ans = in.takeDelimiter('\n') catch null;
connect_mcp = ans != null and ans.?.len > 0 and (ans.?[0] == 'y' or ans.?[0] == 'Y');
}
- return if (connect_mcp) ((mcp.Registry.init(gpa, io, mcp_config_path) catch |err| inner: {
+ return if (connect_mcp) ((mcp.Registry.init(gpa, io, mcp_config_path, home) catch |err| inner: {
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)) else outer: {
+ }) orelse mcp.Registry.empty(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);
+ break :outer mcp.Registry.empty(gpa, io, home);
};
}
@@ -274,7 +274,7 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wr
/// Moved out of main() (600-line goal); mutates `registry` in place (it's
/// already main()-owned and stable by the time this is called, so a pointer
/// is all that's needed — no return-by-value trickery here).
-pub fn connectCompanion(io: Io, registry: *mcp.Registry, flags: args.Flags, out: *Io.Writer, json_mode: bool) !void {
+pub fn connectCompanion(io: Io, registry: *mcp.Registry, flags: args.Flags, out: *Io.Writer, json_mode: bool, smolify_enabled: bool) !void {
connect: {
for (skills.companion_servers) |c| if (skills.mcpServerConnected(registry.tools, c.server)) break :connect;
for (skills.companion_servers) |c| {
@@ -289,4 +289,14 @@ pub fn connectCompanion(io: Io, registry: *mcp.Registry, flags: args.Flags, out:
}
}
}
+
+ // Smolify is a core, hosted Streamable HTTP MCP. It can be disabled with
+ // GRAFF_NO_SMOLIFY=1 for offline or privacy-sensitive sessions.
+ if (!smolify_enabled) return;
+ _ = registry.connectSmolify() catch |err| {
+ if (!json_mode and flags.oneshot_prompt == null) {
+ try out.print("{s}[mcp:smolify] auto-connect failed ({t}) — continuing offline{s}\n", .{ ansi.style.dim, err, ansi.style.reset });
+ try out.flush();
+ }
+ };
}
diff --git a/src/skills.zig b/src/skills.zig
index 37822e7f..6de182ab 100644
--- a/src/skills.zig
+++ b/src/skills.zig
@@ -78,6 +78,10 @@ pub const mcp_notes = [_]McpNote{
.server = "muonry",
.note = "The muonry MCP server is connected (mcp__muonry__* tools). SEARCH ORDER: the native codedb tool is free and indexed — always try it first for code search (search/symbol/callers/outline/find); use mcp__muonry__search or faster_search only when codedb can't answer (raw literal/regex content matches, non-code or non-indexed files) — muonry is metered. Prefer mcp__muonry__read (mode=outline first, then symbol) over read_file for navigating large code files, and mcp__muonry__batch to run several independent reads/searches/edits in one round-trip. Keep edits inside the cwd on the native edit_file/write_file tools (they are snapshot-tracked for /rewind); for an explicitly user-requested external target, use permission-gated bash with quoted paths and disclose that /rewind does not cover it. These tools are accelerators, not requirements: whenever an mcp__muonry__ call fails or is unavailable, fall back to read_file/codedb/bash and continue.",
},
+ .{
+ .server = "smolify",
+ .note = "The core Smolify MCP is connected (mcp__smolify__* tools). Use it to discover and search generated API documentation when a task involves an unfamiliar public project or library; prefer local repository code and its own docs when they already answer the question.",
+ },
};
/// The metered code-intelligence companion. It first shipped as `muonry` and
diff --git a/src/startup.zig b/src/startup.zig
index 21518721..07a92f97 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -410,7 +410,8 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
// `harness mcp add <name> -- <command> [args...]`: write workspace MCP config.
if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "mcp")) {
- try mcp_cli.mcpCommand(io, arena, flags.positionals.items[1..]);
+ const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});
+ try mcp_cli.mcpCommand(io, gpa, arena, home, flags.positionals.items[1..]);
return true;
}