Skip to content

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

Python

graff mcp add: infer, verify, and join a running session

justrach81950357fc0e
diff --git a/README.md b/README.md
index 2f2c1da4..c94c7828 100644
--- a/README.md
+++ b/README.md
@@ -179,6 +179,7 @@ graff [flags] REPL
graff -p "prompt" one-shot (answer on stdout)
graff login [codegraff|codex|kimi|xai|zai]
graff key set <provider> <key>
+graff mcp add <url | @scope/pkg | uvx:pkg | json> save + verify an MCP server
graff mcp add <name> -- <cmd>
graff learn <command>
graff --schema
diff --git a/assets/skills/mcp.md b/assets/skills/mcp.md
index fdb5b7b3..eff15bf4 100644
--- a/assets/skills/mcp.md
+++ b/assets/skills/mcp.md
@@ -10,39 +10,34 @@ only when you need field-level detail. Do the add here.
## Choreography
-1. Name the server (short, lowercase, no spaces). Infer from the URL or
- package when the user did not pick one (`deepwiki`, `playwright`, …).
-2. Classify the entry:
- - Remote / hosted: a `https://…/mcp` URL (Streamable HTTP). Prefer `/mcp`
- over legacy `/sse`.
- - Local / stdio: a `command` plus `args` (`npx -y @playwright/mcp`).
-3. Persist to the **project** `.mcp.json` (never the global file unless the
- user said "every project"):
+1. Pass what the user gave you straight to `graff mcp add`. It infers the
+ name and transport, saves to the **project** `.mcp.json`, then connects
+ and lists the tools:
```sh
-graff mcp add <name> --url https://host/mcp
-graff mcp add <name> -- <command> [args...]
+graff mcp add https://mcp.deepwiki.com/mcp # URL → HTTP, named "deepwiki"
+graff mcp add @playwright/mcp # npm package → npx -y
+graff mcp add uvx:mcp-server-fetch # Python package → uvx
+graff mcp add '{"mcpServers":{...}}' # a pasted Claude/Cursor/VS Code block
graff mcp add <name> --env KEY=VALUE -- <command> [args...]
```
-`edit_file` on `.mcp.json` is equally valid. Do not commit secrets; OAuth
-is `graff mcp login <name>`.
+ `--name <name>` overrides the inferred name. Never write the global file
+ unless the user said "every project". Do not put secrets in the chat.
-4. Connect **this** session. Editing the file does not attach tools to the
- running harness. Ask the user to run one of:
+2. Read the result line:
+ - `✓ <name> works: N tool(s) — …`: done.
+ - `needs sign-in: run graff mcp login <name>`: ask the user to run it
+ (it opens a browser; you cannot finish it for them).
+ - `✗ saved <name>, but it did not connect (…): <hint>`: follow the hint
+ (install Node or uv, add `--env`, fix the package name), then re-run
+ the same `graff mcp add`.
-```
-/mcp add <name> --url <URL>
-/mcp add <name> <command> [args...]
-/mcp trust
-```
-
-Then `load_tool_schemas` with `server` set to that name (or the exact
-`mcp__<server>__<tool>` names) before calling anything.
-
-5. If the tools still do not appear after a restart: the command is not on
- PATH, the URL is not HTTPS (localhost excepted), a token is missing, or
- consent was declined. Fall back to native tools and keep going.
+3. Use it. When this session already connected its configured servers, a new
+ entry joins before your next request with no restart. Call
+ `load_tool_schemas` with `server` set to the name (or the exact
+ `mcp__<server>__<tool>` names) before calling anything. If startup consent
+ was declined, the user runs `/mcp trust` first.
## DeepWiki and Mobbin
@@ -60,11 +55,9 @@ webfetch DeepWiki pages; use those tools once loaded.
User: "using the MCP skill, add this MCP: https://mcp.deepwiki.com/mcp"
-- `graff mcp add deepwiki --url https://mcp.deepwiki.com/mcp`
-- Ask them to `/mcp add deepwiki --url https://mcp.deepwiki.com/mcp` so this
- session can `load_tool_schemas` `server=deepwiki`.
+- `graff mcp add https://mcp.deepwiki.com/mcp`
+- `load_tool_schemas` with `server=deepwiki`, then use it.
User: "add playwright MCP"
-- `graff mcp add playwright -- npx -y @playwright/mcp`
-- Then `/mcp add playwright npx -y @playwright/mcp`.
+- `graff mcp add @playwright/mcp`
diff --git a/build.zig b/build.zig
index c904e37a..123720bd 100644
--- a/build.zig
+++ b/build.zig
@@ -153,6 +153,9 @@ pub fn build(b: *std.Build) void {
const mcp_client_spec_test = b.addSystemCommand(&.{ "python3", "scripts/test-mcp-client-spec.py" });
mcp_client_spec_test.addArtifactArg(exe);
test_step.dependOn(&mcp_client_spec_test.step);
+ const mcp_add_test = b.addSystemCommand(&.{ "python3", "scripts/test-mcp-add.py" });
+ mcp_add_test.addArtifactArg(exe);
+ test_step.dependOn(&mcp_add_test.step);
const acp_v2_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-v2.py" });
acp_v2_test.addArtifactArg(exe);
test_step.dependOn(&acp_v2_test.step);
diff --git a/scripts/test-mcp-add.py b/scripts/test-mcp-add.py
new file mode 100644
index 00000000..59f1d9d5
--- /dev/null
+++ b/scripts/test-mcp-add.py
@@ -0,0 +1,121 @@
+#!/usr/bin/env python3
+"""`graff mcp add` for anything, checked by connecting, and live join.
+
+- a command entry is saved and verified: the tool count and names are printed
+- a pasted Claude-style JSON snippet saves every server in it
+- a missing command is saved but reported with an actionable hint
+- a server that answers 401 points at `graff mcp login` (no TTY here)
+- a server added by the agent mid-session is callable on its next request
+"""
+import json, os, shutil, subprocess, sys, tempfile, threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parent / 'eval'))
+from mock_model import ScriptedModel
+
+SERVER = r"""
+import sys, json
+def out(o): sys.stdout.write(json.dumps(o) + "\n"); sys.stdout.flush()
+for line in sys.stdin:
+ try: m = json.loads(line)
+ except ValueError: continue
+ mid = m.get('id'); meth = m.get('method')
+ if mid is None: continue
+ if meth == 'initialize':
+ out({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2025-11-25", "capabilities": {"tools": {}}, "serverInfo": {"name": "demo", "version": "1"}}})
+ elif meth == 'server/discover':
+ out({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "Method not found"}})
+ elif meth == 'tools/list':
+ out({"jsonrpc": "2.0", "id": mid, "result": {"tools": [
+ {"name": "echo", "description": "echo", "inputSchema": {"type": "object", "properties": {}}},
+ {"name": "ping", "description": "ping", "inputSchema": {"type": "object", "properties": {}}}]}})
+ elif meth == 'tools/call':
+ out({"jsonrpc": "2.0", "id": mid, "result": {"content": [{"type": "text", "text": "echo ok from demo"}]}})
+ else:
+ out({"jsonrpc": "2.0", "id": mid, "result": {}})
+"""
+
+
+class Unauthorized(BaseHTTPRequestHandler):
+ def _deny(self):
+ self.send_response(401)
+ self.send_header('WWW-Authenticate', 'Bearer resource_metadata="http://127.0.0.1/.well-known/oauth-protected-resource"')
+ self.send_header('Content-Length', '0')
+ self.end_headers()
+ do_POST = do_GET = _deny
+ def log_message(self, *a): pass
+
+
+def run(binary, cwd, env, *args, stdin=None):
+ r = subprocess.run([binary, 'mcp', *args], cwd=cwd, env=env, input=stdin, capture_output=True, text=True, timeout=180)
+ return r.stdout + r.stderr
+
+
+def saved(cwd):
+ return json.loads((Path(cwd) / '.mcp.json').read_text())['mcpServers']
+
+
+def main():
+ binary = str(Path(sys.argv[1] if len(sys.argv) > 1 else 'zig-out/bin/graff').resolve())
+ temp = tempfile.mkdtemp(prefix='graff-mcp-add-')
+ try:
+ server = Path(temp) / 'server.py'
+ server.write_text(SERVER)
+ env = {k: v for k, v in os.environ.items() if not k.endswith('_API_KEY')}
+ env.update(HOME=temp, GRAFF_NO_TELEMETRY='1', GRAFF_FLEET='off', GRAFF_MCP_CONFIG=str(Path(temp) / 'global.json'))
+ (Path(temp) / 'global.json').write_text('{"mcpServers":{}}')
+ work = Path(temp) / 'proj'
+ work.mkdir()
+
+ text = run(binary, work, env, 'add', 'demo', '--', sys.executable, str(server))
+ assert '✓ demo works: 2 tool(s) — echo, ping' in text, text
+ print('PASS mcp add: a command entry is saved, connected, and its tools listed', flush=True)
+
+ snippet = json.dumps({"mcpServers": {"Snippet-One": {"command": sys.executable, "args": [str(server)]},
+ "missing": {"command": "graff-no-such-binary-xyz", "args": []}}})
+ text = run(binary, work, env, 'add', snippet)
+ servers = saved(work)
+ assert 'snippet-one' in servers and 'missing' in servers, servers
+ assert '✓ snippet-one works: 2 tool(s)' in text, text
+ assert '✗ saved missing, but it did not connect' in text and 'not found on PATH' in text, text
+ print('PASS mcp add: a pasted JSON snippet saves every server; a missing command gets a hint', flush=True)
+
+ httpd = ThreadingHTTPServer(('127.0.0.1', 0), Unauthorized)
+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
+ try:
+ url = f'http://127.0.0.1:{httpd.server_address[1]}/mcp'
+ text = run(binary, work, env, 'add', url)
+ name = f'local-{httpd.server_address[1]}'
+ assert saved(work)[name]['url'] == url, saved(work)
+ assert f'needs sign-in: run `graff mcp login {name}`' in text, text
+ finally:
+ httpd.shutdown()
+ print('PASS mcp add: a URL is named from its host; a 401 points at graff mcp login', flush=True)
+
+ live = Path(temp) / 'live'
+ live.mkdir()
+ add_cmd = f'{binary} mcp add livedemo --no-verify -- {sys.executable} {server}'
+ model = ScriptedModel([
+ {'tool': 'bash', 'arguments': {'command': add_cmd}},
+ {'tool': 'mcp__livedemo__echo', 'arguments': {}},
+ {'text': 'Done.'},
+ ])
+ port = model.start(0)
+ # No GRAFF_MCP_CONFIG here: an empty override is MCP's off-switch (#549).
+ env2 = {k: v for k, v in env.items() if k != 'GRAFF_MCP_CONFIG'}
+ env2.update(AI_GATEWAY_API_KEY='local', GRAFF_VERCEL_URL=f'http://127.0.0.1:{port}/v1/chat/completions',
+ GRAFF_NO_SMOLIFY='1', GRAFF_NO_CODEDB_GUARD='1')
+ try:
+ subprocess.run([binary, '--model', 'vercel', '--old', '--no-lean', '--yolo', '-p', 'add the demo server and use it'],
+ cwd=live, env=env2, capture_output=True, text=True, timeout=180)
+ finally:
+ model.stop()
+ results = [m.get('content') for m in model.requests[-1].get('messages', []) if m.get('role') == 'tool']
+ assert any('echo ok from demo' in str(r) for r in results), results
+ print('PASS live join: a server the agent adds mid-session is callable on its next request', flush=True)
+ finally:
+ shutil.rmtree(temp, ignore_errors=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index f8ea0d49..05181e48 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -286,6 +286,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
};
+ @import("mcp_watch.zig").arm(reg, mcp_config_path); // later additions join live
if (n == 0) {
try out.writeAll("no untrusted MCP server(s) left to connect.\n");
} else {
diff --git a/src/main.zig b/src/main.zig
index d7df0fc6..c0542034 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -579,7 +579,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig") }; // h2 stream path, and graff's request/response contract over the pinned http-zig
_ = @import("tui_acp_updates.zig");
_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root
- _ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_elicit.zig"), @import("hot_context.zig"), @import("history_translate.zig"), @import("mcp_notify.zig"), @import("mcp_wait.zig"), @import("mcp_pages.zig"), @import("mcp_mrtr.zig"), @import("ask_user_args.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig"), @import("ask_user_answers.zig"), @import("job_class.zig"), @import("startup_claim.zig") };
+ _ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_elicit.zig"), @import("hot_context.zig"), @import("history_translate.zig"), @import("mcp_notify.zig"), @import("mcp_wait.zig"), @import("mcp_pages.zig"), @import("mcp_mrtr.zig"), @import("ask_user_args.zig"), @import("mcp_add.zig"), @import("mcp_watch.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig"), @import("ask_user_answers.zig"), @import("job_class.zig"), @import("startup_claim.zig") };
_ = @import("task_outcome.zig"); // goal-outcome telemetry events
_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here
_ = .{ @import("additional_tests.zig"), @import("req_stats.zig"), @import("exact_reply.zig"), @import("rlm_order_tests.zig"), @import("async_tool_policy.zig"), @import("agent_async_tools.zig"), @import("request_usage_attempts.zig"), @import("learn_formal.zig") };
diff --git a/src/mcp_add.zig b/src/mcp_add.zig
new file mode 100644
index 00000000..493b8da6
--- /dev/null
+++ b/src/mcp_add.zig
@@ -0,0 +1,294 @@
+//! `graff mcp add <anything>`: infer an entry from a URL, an npm/uvx package, or
+//! a pasted Claude/Cursor/VS Code JSON snippet, then verify it connects.
+//!
+//! The explicit forms (`add <name> --url …`, `add <name> -- <command> …`) stay
+//! in mcp_cli.zig; this module only decides what an unlabeled argument means
+//! and checks the saved entry by connecting to it and listing its tools.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+/// One server to save: the name and its `.mcp.json` entry
+/// (`command`/`args`/`env` or `url`/`headers`).
+pub const Named = struct { name: []const u8, cfg: std.json.ObjectMap };
+
+fn lowerSlug(a: Allocator, raw: []const u8) ![]const u8 {
+ var out: std.ArrayList(u8) = .empty;
+ for (raw) |c| {
+ const l = std.ascii.toLower(c);
+ if (std.ascii.isAlphanumeric(l)) {
+ try out.append(a, l);
+ } else if ((l == '-' or l == '_' or l == '.') and out.items.len > 0 and out.items[out.items.len - 1] != '-') {
+ try out.append(a, '-');
+ }
+ }
+ while (out.items.len > 0 and out.items[out.items.len - 1] == '-') out.items.len -= 1;
+ return out.items;
+}
+
+pub fn isUrl(token: []const u8) bool {
+ return std.mem.startsWith(u8, token, "https://") or std.mem.startsWith(u8, token, "http://");
+}
+
+/// `https://mcp.linear.app/sse` → "linear"; `http://localhost:8931/mcp` → "local-8931".
+pub fn nameFromUrl(a: Allocator, url: []const u8) ![]const u8 {
+ const after = url[(std.mem.indexOf(u8, url, "://") orelse return error.InvalidUrl) + 3 ..];
+ const authority = after[0 .. std.mem.indexOfAny(u8, after, "/?#") orelse after.len];
+ const host_start = if (std.mem.lastIndexOfScalar(u8, authority, '@')) |at| at + 1 else 0;
+ const host_port = authority[host_start..];
+ const bracketed = std.mem.startsWith(u8, host_port, "[");
+ const colon = if (bracketed) std.mem.indexOf(u8, host_port, "]:") else std.mem.lastIndexOfScalar(u8, host_port, ':');
+ const host = if (colon) |c| host_port[0 .. c + @intFromBool(bracketed)] else host_port;
+ const port = if (colon) |c| host_port[c + 1 + @intFromBool(bracketed) ..] else "";
+ if (std.mem.eql(u8, host, "localhost") or std.mem.startsWith(u8, host, "127.") or std.mem.eql(u8, host, "[::1]"))
+ return if (port.len > 0) std.fmt.allocPrint(a, "local-{s}", .{port}) else "local";
+ var labels = std.mem.splitScalar(u8, host, '.');
+ while (labels.next()) |label| {
+ if (labels.peek() == null) break; // never the TLD
+ const generic = [_][]const u8{ "mcp", "api", "www", "server", "app", "remote" };
+ const skip = for (generic) |g| {
+ if (std.ascii.eqlIgnoreCase(label, g)) break true;
+ } else false;
+ if (!skip) return lowerSlug(a, label);
+ }
+ return lowerSlug(a, host);
+}
+
+pub const Runner = enum { npx, uvx };
+pub const Package = struct { runner: Runner, pkg: []const u8 };
+
+/// An npm package (`@scope/name`, a bare `*mcp*` name, or `npx:name`), or a
+/// Python one with an explicit `uvx:` prefix. Paths and plain commands are not.
+pub fn packageSpec(token: []const u8) ?Package {
+ if (std.mem.startsWith(u8, token, "uvx:")) return if (token.len > 4) .{ .runner = .uvx, .pkg = token[4..] } else null;
+ if (std.mem.startsWith(u8, token, "npx:")) return if (token.len > 4) .{ .runner = .npx, .pkg = token[4..] } else null;
+ if (token.len > 2 and token[0] == '@' and std.mem.indexOfScalar(u8, token, '/') != null and std.mem.indexOfAny(u8, token, " \\") == null)
+ return .{ .runner = .npx, .pkg = token };
+ if (std.mem.indexOf(u8, token, "mcp") == null) return null;
+ for (token) |c| if (!(std.ascii.isLower(c) or std.ascii.isDigit(c) or c == '-' or c == '.' or c == '_' or c == '@')) return null;
+ return .{ .runner = .npx, .pkg = token };
+}
+
+/// `@modelcontextprotocol/server-github` → "github", `@playwright/mcp` →
+/// "playwright", `@upstash/context7-mcp@latest` → "context7".
+pub fn nameFromPackage(a: Allocator, pkg: []const u8) ![]const u8 {
+ var body = pkg;
+ // A version pin: the last '@' past the scope marker.
+ if (std.mem.lastIndexOfScalar(u8, body, '@')) |at| if (at > 0) {
+ body = body[0..at];
+ };
+ const slash = std.mem.lastIndexOfScalar(u8, body, '/');
+ var seg = if (slash) |s| body[s + 1 ..] else body;
+ const scope = if (slash) |s| std.mem.trimStart(u8, body[0..s], "@") else "";
+ for ([_][]const u8{ "mcp-server-", "server-", "mcp-" }) |p| if (std.mem.startsWith(u8, seg, p) and seg.len > p.len) {
+ seg = seg[p.len..];
+ break;
+ };
+ for ([_][]const u8{ "-mcp-server", "-server-mcp", "-mcp", "-server" }) |s| if (std.mem.endsWith(u8, seg, s) and seg.len > s.len) {
+ seg = seg[0 .. seg.len - s.len];
+ break;
+ };
+ if ((std.mem.eql(u8, seg, "mcp") or std.mem.eql(u8, seg, "server")) and scope.len > 0) seg = scope;
+ return lowerSlug(a, seg);
+}
+
+fn putStrings(a: Allocator, cfg: *std.json.ObjectMap, key: []const u8, items: []const []const u8) !void {
+ var arr = std.json.Array.init(a);
+ for (items) |s| try arr.append(.{ .string = s });
+ try cfg.put(a, key, .{ .array = arr });
+}
+
+/// The entry for one unlabeled token (URL or package), or null when the token
+/// is neither: the caller then treats it as an explicit command.
+pub fn infer(a: Allocator, token: []const u8, name_override: ?[]const u8) !?Named {
+ var cfg: std.json.ObjectMap = .empty;
+ if (isUrl(token)) {
+ try cfg.put(a, "url", .{ .string = token });
+ return .{ .name = name_override orelse try nameFromUrl(a, token), .cfg = cfg };
+ }
+ const spec = packageSpec(token) orelse return null;
+ switch (spec.runner) {
+ .npx => {
+ try cfg.put(a, "command", .{ .string = "npx" });
+ try putStrings(a, &cfg, "args", &.{ "-y", spec.pkg });
+ },
+ .uvx => {
+ try cfg.put(a, "command", .{ .string = "uvx" });
+ try putStrings(a, &cfg, "args", &.{spec.pkg});
+ },
+ }
+ return .{ .name = name_override orelse try nameFromPackage(a, spec.pkg), .cfg = cfg };
+}
+
+/// Keep only what graff's config reads; map the URL spellings other clients use.
+fn normalize(a: Allocator, raw: Value) !std.json.ObjectMap {
+ if (raw != .object) return error.UnsupportedEntry;
+ var cfg: std.json.ObjectMap = .empty;
+ const o = raw.object;
+ if (o.get("command")) |c| {
+ if (c != .string) return error.UnsupportedEntry;
+ try cfg.put(a, "command", c);
+ if (o.get("args")) |args| {
+ if (args != .array) return error.UnsupportedEntry;
+ for (args.array.items) |arg| if (arg != .string) return error.UnsupportedEntry;
+ try cfg.put(a, "args", args);
+ }
+ if (o.get("env")) |env| if (env == .object) try cfg.put(a, "env", env);
+ return cfg;
+ }
+ for ([_][]const u8{ "url", "serverUrl", "httpUrl" }) |key| if (o.get(key)) |u| if (u == .string) {
+ try cfg.put(a, "url", u);
+ if (o.get("headers")) |h| if (h == .object) try cfg.put(a, "headers", h);
+ return cfg;
+ };
+ return error.UnsupportedEntry;
+}
+
+fn isEntry(v: Value) bool {
+ return v == .object and (v.object.get("command") != null or v.object.get("url") != null or v.object.get("serverUrl") != null or v.object.get("httpUrl") != null);
+}
+
+/// Servers in a pasted snippet: `{"mcpServers":{…}}` (Claude, Cursor),
+/// `{"servers":{…}}` or `{"mcp":{"servers":{…}}}` (VS Code), a bare
+/// `{name: entry}` map, or one entry (named by `name_override` or its URL).
+pub fn fromJson(a: Allocator, text: []const u8, name_override: ?[]const u8) ![]Named {
+ const root = std.json.parseFromSliceLeaky(Value, a, text, .{ .allocate = .alloc_always }) catch return error.InvalidJson;
+ if (root != .object) return error.InvalidJson;
+ var out: std.ArrayList(Named) = .empty;
+ if (isEntry(root)) {
+ const cfg = try normalize(a, root);
+ const name = name_override orelse blk: {
+ if (cfg.get("url")) |u| break :blk try nameFromUrl(a, u.string);
+ if (cfg.get("args")) |args| for (args.array.items) |arg| if (packageSpec(arg.string)) |p| break :blk try nameFromPackage(a, p.pkg);
+ return error.NameRequired;
+ };
+ try out.append(a, .{ .name = name, .cfg = cfg });
+ return out.items;
+ }
+ const map = if (root.object.get("mcpServers")) |m| m else if (root.object.get("servers")) |m| m else if (root.object.get("mcp")) |m|
+ (if (m == .object) (m.object.get("servers") orelse return error.NoServers) else return error.NoServers)
+ else
+ root;
+ if (map != .object) return error.NoServers;
+ var it = map.object.iterator();
+ while (it.next()) |e| {
+ if (!isEntry(e.value_ptr.*)) continue;
+ try out.append(a, .{ .name = try lowerSlug(a, e.key_ptr.*), .cfg = try normalize(a, e.value_ptr.*) });
+ }
+ if (out.items.len == 0) return error.NoServers;
+ return out.items;
+}
+
+pub const Checked = union(enum) {
+ ok: struct { tools: usize, sample: []const u8 },
+ needs_login,
+ failed: anyerror,
+};
+
+/// Connect to one saved entry, list its tools, and disconnect.
+pub fn verify(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, entry: Named) Checked {
+ const mcp = @import("mcp.zig");
+ const rpc = @import("mcp_rpc.zig");
+ // A first `npx -y` or `uvx` run downloads the package before it can answer.
+ const saved_timeout = rpc.stdio_handshake_timeout_ms;
+ rpc.stdio_handshake_timeout_ms = @max(saved_timeout, 120_000);
+ defer rpc.stdio_handshake_timeout_ms = saved_timeout;
+ var reg = mcp.Registry.emptyWithOAuthHome(gpa, io, home);
+ defer reg.deinit();
+ const a = reg.arena();
+ var servers: std.ArrayList(*rpc.Server) = .empty;
+ var tools: std.ArrayList(mcp.Tool) = .empty;
+ reg.startServer(a, &servers, &tools, entry.name, entry.cfg) catch |err| {
+ reg.servers = servers.items;
+ return if (err == error.McpAuthenticationRequired) .needs_login else .{ .failed = err };
+ };
+ reg.servers = servers.items;
+ reg.tools = tools.items;
+ var sample: std.ArrayList(u8) = .empty;
+ for (tools.items, 0..) |t, i| {
+ if (i == 5) {
+ sample.appendSlice(arena, ", …") catch break;
+ break;
+ }
+ if (i > 0) sample.appendSlice(arena, ", ") catch break;
+ sample.appendSlice(arena, t.original_name) catch break;
+ }
+ return .{ .ok = .{ .tools = tools.items.len, .sample = sample.items } };
+}
+
+/// One line a person can act on for a failed connection.
+pub fn failureHint(err: anyerror, cfg: std.json.ObjectMap) []const u8 {
+ const command = if (cfg.get("command")) |c| (if (c == .string) c.string else "") else "";
+ return switch (err) {
+ error.FileNotFound => if (std.mem.eql(u8, command, "npx"))
+ "`npx` was not found; install Node.js, or add the server with an explicit command"
+ else if (std.mem.eql(u8, command, "uvx"))
+ "`uvx` was not found; install uv, or add the server with an explicit command"
+ else
+ "the command was not found on PATH",
+ error.BadMcpUrl => "the URL must use HTTPS (HTTP only for localhost)",
+ error.EndOfStream, error.BrokenPipe => "the server exited during startup; it may need an environment variable (`--env KEY=VALUE`) or a different package (`uvx:` for Python servers)",
+ else => "the server did not complete the MCP handshake",
+ };
+}
+
+test "names come from the host or the package, not boilerplate" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ try std.testing.expectEqualStrings("linear", try nameFromUrl(a, "https://mcp.linear.app/sse"));
+ try std.testing.expectEqualStrings("mobbin", try nameFromUrl(a, "https://api.mobbin.com/mcp"));
+ try std.testing.expectEqualStrings("local-8931", try nameFromUrl(a, "http://localhost:8931/mcp"));
+ try std.testing.expectEqualStrings("example", try nameFromUrl(a, "https://[email protected]:8443/x"));
+ try std.testing.expectEqualStrings("github", try nameFromPackage(a, "@modelcontextprotocol/server-github"));
+ try std.testing.expectEqualStrings("playwright", try nameFromPackage(a, "@playwright/mcp"));
+ try std.testing.expectEqualStrings("context7", try nameFromPackage(a, "@upstash/context7-mcp@latest"));
+ try std.testing.expectEqualStrings("fetch", try nameFromPackage(a, "mcp-server-fetch"));
+}
+
+test "infer maps URLs and packages; other tokens stay commands" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const url = (try infer(a, "https://mcp.linear.app/sse", null)).?;
+ try std.testing.expectEqualStrings("https://mcp.linear.app/sse", url.cfg.get("url").?.string);
+ const npm = (try infer(a, "@playwright/mcp", null)).?;
+ try std.testing.expectEqualStrings("npx", npm.cfg.get("command").?.string);
+ try std.testing.expectEqualStrings("-y", npm.cfg.get("args").?.array.items[0].string);
+ const py = (try infer(a, "uvx:mcp-server-fetch", "fetch")).?;
+ try std.testing.expectEqualStrings("uvx", py.cfg.get("command").?.string);
+ try std.testing.expectEqualStrings("fetch", py.name);
+ try std.testing.expect((try infer(a, "node", null)) == null);
+ try std.testing.expect((try infer(a, "./server.js", null)) == null);
+}
+
+test "fromJson reads Claude, VS Code, bare-map, and single-entry snippets" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const claude = try fromJson(a,
+ \\{"mcpServers":{"Sentry":{"command":"npx","args":["-y","@sentry/mcp-server"],"env":{"TOKEN":"x"}},"linear":{"url":"https://mcp.linear.app/sse"}}}
+ , null);
+ try std.testing.expectEqual(@as(usize, 2), claude.len);
+ var saw_sentry_env = false;
+ for (claude) |n| if (std.mem.eql(u8, n.name, "sentry")) {
+ saw_sentry_env = n.cfg.get("env") != null;
+ };
+ try std.testing.expect(saw_sentry_env);
+ const vscode = try fromJson(a,
+ \\{"mcp":{"servers":{"gh":{"type":"http","url":"https://api.githubcopilot.com/mcp/"}}}}
+ , null);
+ try std.testing.expectEqualStrings("https://api.githubcopilot.com/mcp/", vscode[0].cfg.get("url").?.string);
+ try std.testing.expect(vscode[0].cfg.get("type") == null);
+ const windsurf = try fromJson(a,
+ \\{"deepwiki":{"serverUrl":"https://mcp.deepwiki.com/mcp"}}
+ , null);
+ try std.testing.expectEqualStrings("https://mcp.deepwiki.com/mcp", windsurf[0].cfg.get("url").?.string);
+ const single = try fromJson(a,
+ \\{"command":"npx","args":["-y","@upstash/context7-mcp"]}
+ , null);
+ try std.testing.expectEqualStrings("context7", single[0].name);
+ try std.testing.expectError(error.NoServers, fromJson(a, "{\"x\":1}", null));
+}
diff --git a/src/mcp_cli.zig b/src/mcp_cli.zig
index 0dbf5a21..800a5773 100644
--- a/src/mcp_cli.zig
+++ b/src/mcp_cli.zig
@@ -101,6 +101,65 @@ fn persistMcpServerWithEnv(io: Io, arena: Allocator, name: []const u8, command:
return true;
}
+/// Save one ready-made entry (`command`/`args`/`env` or `url`/`headers`) into
+/// the project .mcp.json, keeping every other server. False on any error.
+pub fn persistEntry(io: Io, arena: Allocator, name: []const u8, entry: std.json.ObjectMap) 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;
+ };
+ 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, .options = .{ .whitespace = .indent_2 } };
+ 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.writeByte('\n') catch return false;
+ writer.interface.flush() catch return false;
+ return true;
+}
+
+/// Connect to a just-saved server and say what it offers, or what to do next.
+/// A server that wants OAuth is signed in on the spot when a person is at the
+/// terminal; an agent's shell gets the `graff mcp login` line instead.
+fn checkSaved(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, name: []const u8, out: *Io.Writer) !void {
+ const text = Io.Dir.cwd().readFileAlloc(io, mcp_config_path, arena, .limited(1 << 20)) catch return;
+ const v = std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always }) catch return;
+ const servers = if (v == .object) v.object.get("mcpServers") orelse return else return;
+ const entry = if (servers == .object) servers.object.get(name) orelse return else return;
+ if (entry != .object) return;
+ const add = @import("mcp_add.zig");
+ try out.print(" connecting to {s}…\n", .{name});
+ try out.flush();
+ var result = add.verify(io, gpa, arena, home, .{ .name = name, .cfg = entry.object });
+ if (result == .needs_login) {
+ const url = if (entry.object.get("url")) |u| (if (u == .string) u.string else "") else "";
+ if (url.len == 0 or !(Io.File.stdin().isTty(io) catch false)) {
+ try out.print(" {s} needs sign-in: run `graff mcp login {s}`\n", .{ name, name });
+ return;
+ }
+ try out.print(" {s} needs sign-in; opening the OAuth flow\n", .{name});
+ try out.flush();
+ mcp_oauth.login(io, gpa, arena, home, name, url) catch return;
+ result = add.verify(io, gpa, arena, home, .{ .name = name, .cfg = entry.object });
+ }
+ switch (result) {
+ .ok => |ok| try out.print("✓ {s} works: {d} tool(s){s}{s}\n", .{ name, ok.tools, if (ok.sample.len > 0) " — " else "", ok.sample }),
+ .needs_login => try out.print(" {s} still needs sign-in: run `graff mcp login {s}`\n", .{ name, name }),
+ .failed => |err| try out.print("✗ saved {s}, but it did not connect ({t}): {s}\n fix it and re-run `graff mcp add`, or remove it from .mcp.json\n", .{ name, err, add.failureHint(err, entry.object) }),
+ }
+}
+
/// 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.
@@ -145,6 +204,7 @@ fn mcpCliUsage(w: *Io.Writer) !void {
\\ graff mcp serve [--http] [--port N] [--model NAME] [--yolo] expose run_task over stdio or HTTP
\\ graff mcp list servers in .mcp.json + ~/.codegraff/mcp.json
\\ graff mcp import copy Claude/Cursor MCP + skills into graff folders
+ \\ graff mcp add <url | @scope/package | uvx:package | '{json}' | -> infer, save, then connect to check it
\\ 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...]
@@ -160,6 +220,49 @@ fn mcpCliUsage(w: *Io.Writer) !void {
);
}
+/// `add <url|package|json|->` and `add <name> <url|package>`. False when the
+/// arguments are an explicit form for the caller to parse.
+fn addInferred(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, add_args: []const []const u8, name_flag: ?[]const u8, verify_after: bool, out: *Io.Writer) !bool {
+ const add = @import("mcp_add.zig");
+ var entries: []const add.Named = &.{};
+ if (add_args.len == 2) {
+ const token = add_args[1];
+ if (std.mem.eql(u8, token, "-") or std.mem.startsWith(u8, std.mem.trimStart(u8, token, " \t\r\n"), "{")) {
+ const text = if (std.mem.eql(u8, token, "-")) blk: {
+ var ibuf: [4096]u8 = undefined;
+ var in = Io.File.stdin().reader(io, &ibuf);
+ break :blk in.interface.allocRemaining(arena, .limited(1 << 20)) catch std.process.fatal("mcp add: could not read JSON from stdin", .{});
+ } else token;
+ entries = add.fromJson(arena, text, name_flag) catch |err| std.process.fatal("mcp add: could not read that JSON ({t}); paste a Claude/Cursor `mcpServers` block, a VS Code `servers` block, or one entry with --name", .{err});
+ } else if (try add.infer(arena, token, name_flag)) |one| {
+ entries = try arena.dupe(add.Named, &.{one});
+ } else {
+ std.process.fatal("mcp add: can't tell what '{s}' is. Give a URL, an npm package (@scope/name), uvx:<python-package>, a JSON snippet, or `graff mcp add <name> -- <command> [args...]`", .{token});
+ }
+ } else if (add_args.len == 3 and !std.mem.startsWith(u8, add_args[2], "-") and
+ (add.isUrl(add_args[2]) or add_args[2][0] == '@' or std.mem.startsWith(u8, add_args[2], "npx:") or std.mem.startsWith(u8, add_args[2], "uvx:")))
+ {
+ const one = (try add.infer(arena, add_args[2], add_args[1])) orelse return false;
+ entries = try arena.dupe(add.Named, &.{one});
+ } else return false;
+ for (entries) |e| {
+ if (e.cfg.get("url")) |u| if (!mcp.validRemoteUrl(u.string)) std.process.fatal("mcp add: {s}: URL must use HTTPS (HTTP is allowed only for localhost)", .{e.name});
+ if (!persistEntry(io, arena, e.name, e.cfg)) std.process.fatal("mcp add: could not write .mcp.json", .{});
+ if (e.cfg.get("url")) |u| {
+ try out.print("✓ added {s} ({s}) to .mcp.json\n", .{ e.name, u.string });
+ } else {
+ try out.print("✓ added {s} (", .{e.name});
+ try out.writeAll(e.cfg.get("command").?.string);
+ if (e.cfg.get("args")) |argv| for (argv.array.items) |x| try out.print(" {s}", .{x.string});
+ try out.writeAll(") to .mcp.json\n");
+ }
+ if (verify_after) try checkSaved(io, gpa, arena, home, e.name, out);
+ }
+ try out.writeAll(" a running session connects new servers before its next request.\n");
+ try out.flush();
+ return true;
+}
+
pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, environ_map: anytype, args: []const []const u8) !void {
if (args.len > 0 and std.mem.eql(u8, args[0], "install")) {
const exe = try std.process.executablePathAlloc(io, arena);
@@ -257,29 +360,51 @@ pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, en
try out.interface.flush();
return;
}
- if (args.len < 3) {
+ // `--no-verify` and `--name N` apply to every form; stop at `--`, whose
+ // tail belongs to the server's own command line.
+ var verify_after = true;
+ var name_flag: ?[]const u8 = null;
+ var kept: std.ArrayList([]const u8) = .empty;
+ try kept.append(arena, "add");
+ {
+ var k: usize = 1;
+ while (k < args.len) : (k += 1) {
+ if (std.mem.eql(u8, args[k], "--")) {
+ try kept.appendSlice(arena, args[k..]);
+ break;
+ } else if (std.mem.eql(u8, args[k], "--no-verify")) {
+ verify_after = false;
+ } else if (std.mem.eql(u8, args[k], "--name") and k + 1 < args.len) {
+ k += 1;
+ name_flag = args[k];
+ } else try kept.append(arena, args[k]);
+ }
+ }
+ const add_args = kept.items;
+ if (try addInferred(io, gpa, arena, home, add_args, name_flag, verify_after, &out.interface)) return;
+ if (add_args.len < 3) {
try mcpCliUsage(&out.interface);
try out.interface.flush();
return;
}
- const name = args[1];
- 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..];
+ const name = add_args[1];
+ if (std.mem.eql(u8, add_args[2], "--url") or std.mem.startsWith(u8, add_args[2], "--url=")) {
+ const url = if (std.mem.eql(u8, add_args[2], "--url")) blk: {
+ if (add_args.len < 4) std.process.fatal("mcp add: --url needs an HTTP(S) URL", .{});
+ break :blk add_args[3];
+ } else add_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;
+ const first_option: usize = if (std.mem.eql(u8, add_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];
+ while (j < add_args.len) : (j += 1) {
+ const arg = add_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];
+ if (j >= add_args.len) std.process.fatal("mcp add: --header needs KEY=VALUE", .{});
+ break :value add_args[j];
} else if (std.mem.startsWith(u8, arg, "--header="))
arg["--header=".len..]
else
@@ -289,6 +414,7 @@ pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, en
}
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});
+ if (verify_after) try checkSaved(io, gpa, arena, home, name, &out.interface);
try out.interface.flush();
return;
}
@@ -297,16 +423,16 @@ pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, en
defer env_pairs.deinit(arena);
var command_index: ?usize = null;
var i: usize = 2;
- while (i < args.len) : (i += 1) {
- const arg = args[i];
+ while (i < add_args.len) : (i += 1) {
+ const arg = add_args[i];
if (std.mem.eql(u8, arg, "--")) {
command_index = i + 1;
break;
} else if (std.mem.eql(u8, arg, "--env")) {
i += 1;
- if (i >= args.len) std.process.fatal("mcp add: --env needs KEY=VALUE", .{});
- const eq = std.mem.indexOfScalar(u8, args[i], '=') orelse std.process.fatal("mcp add: --env expects KEY=VALUE", .{});
- try env_pairs.append(arena, .{ .key = args[i][0..eq], .value = args[i][eq + 1 ..] });
+ if (i >= add_args.len) std.process.fatal("mcp add: --env needs KEY=VALUE", .{});
+ const eq = std.mem.indexOfScalar(u8, add_args[i], '=') orelse std.process.fatal("mcp add: --env expects KEY=VALUE", .{});
+ try env_pairs.append(arena, .{ .key = add_args[i][0..eq], .value = add_args[i][eq + 1 ..] });
} else if (std.mem.startsWith(u8, arg, "--env=")) {
const kv = arg["--env=".len..];
const eq = std.mem.indexOfScalar(u8, kv, '=') orelse std.process.fatal("mcp add: --env expects KEY=VALUE", .{});
@@ -317,12 +443,21 @@ pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, en
}
}
const ci = command_index orelse std.process.fatal("mcp add: missing command after server name", .{});
- if (ci >= args.len) std.process.fatal("mcp add: missing command after --", .{});
- const command = args[ci];
- const command_args = args[ci + 1 ..];
+ if (ci >= add_args.len) std.process.fatal("mcp add: missing command after --", .{});
+ var command = add_args[ci];
+ var command_args = add_args[ci + 1 ..];
+ // `add <name> --env K=V @scope/pkg`: a lone package token, not a program.
+ if (command_args.len == 0 and (command[0] == '@' or std.mem.startsWith(u8, command, "npx:") or std.mem.startsWith(u8, command, "uvx:"))) {
+ if (@import("mcp_add.zig").packageSpec(command)) |spec| {
+ command_args = if (spec.runner == .npx) try arena.dupe([]const u8, &.{ "-y", spec.pkg }) else try arena.dupe([]const u8, &.{spec.pkg});
+ command = if (spec.runner == .npx) "npx" else "uvx";
+ }
+ }
if (!persistMcpServerWithEnv(io, arena, name, command, command_args, env_pairs.items))
std.process.fatal("mcp add: failed to write .mcp.json", .{});
- try out.interface.print("✓ added MCP server {s} to .mcp.json\n run `graff` and use `/mcp trust` if workspace MCP startup is waiting for consent.\n", .{name});
+ try out.interface.print("✓ added MCP server {s} to .mcp.json\n", .{name});
+ if (verify_after) try checkSaved(io, gpa, arena, home, name, &out.interface);
+ try out.interface.writeAll(" a running session connects it before its next request; otherwise `/mcp trust` if startup is waiting for consent.\n");
try out.interface.flush();
}
test "trustedMcpEntry: only the exact companion shape skips the consent gate" {
diff --git a/src/mcp_pages.zig b/src/mcp_pages.zig
index 30d95914..f4b1c60b 100644
--- a/src/mcp_pages.zig
+++ b/src/mcp_pages.zig
@@ -107,7 +107,8 @@ pub fn listen(server: *Server, a: Allocator) void {
/// Before each model request: merge finished deferred handshakes, then
/// re-list servers whose tools changed. True when the catalog must rebuild.
pub fn beforeRequest(reg: *mcp.Registry) bool {
- const joined = @import("mcp_boot.zig").joinBeforeRequest(reg);
+ const added = @import("mcp_watch.zig").poll(reg); // servers added mid-session
+ const joined = @import("mcp_boot.zig").joinBeforeRequest(reg) or added;
const refreshed = refreshStale(reg);
return joined or refreshed;
}
diff --git a/src/mcp_watch.zig b/src/mcp_watch.zig
new file mode 100644
index 00000000..fb57c8b8
--- /dev/null
+++ b/src/mcp_watch.zig
@@ -0,0 +1,120 @@
+//! Servers added to the MCP config while a session runs join it (live join).
+//!
+//! `graff mcp add` writes `.mcp.json`; before this, a running session only saw
+//! the new server after a restart or `/mcp trust`. The watcher is armed only
+//! once the session has connected its configured servers (consent given,
+//! `--yolo`, or `/mcp trust`), so it never widens what the user agreed to: it
+//! joins names that appear after arming and ignores ones boot chose to skip.
+
+const std = @import("std");
+const Io = std.Io;
+const mcp = @import("mcp.zig");
+const mcp_boot = @import("mcp_boot.zig");
+const mcp_config = @import("mcp_config.zig");
+
+const State = struct {
+ armed: bool = false,
+ project_path: []const u8 = ".mcp.json",
+ stamp: u64 = 0,
+ /// Hashes of every configured name when armed or last joined.
+ known: std.ArrayList(u64) = .empty,
+};
+var g: State = .{};
+const alloc = std.heap.page_allocator;
+
+pub fn resetForTest() void {
+ g.known.deinit(alloc);
+ g = .{};
+}
+
+fn nameHash(name: []const u8) u64 {
+ return std.hash.Wyhash.hash(0x6d63, name);
+}
+
+fn isKnown(name: []const u8) bool {
+ const h = nameHash(name);
+ for (g.known.items) |k| if (k == h) return true;
+ return false;
+}
+
+fn signature(io: Io, global_path: ?[]const u8) u64 {
+ var h = std.hash.Wyhash.init(0);
+ for ([_]?[]const u8{ g.project_path, global_path }) |maybe| {
+ const path = maybe orelse continue;
+ const st = Io.Dir.cwd().statFile(io, path, .{}) catch {
+ h.update("-");
+ continue;
+ };
+ const mtime: i128 = st.mtime.nanoseconds;
+ h.update(std.mem.asBytes(&st.size));
+ h.update(std.mem.asBytes(&mtime));
+ }
+ return h.final();
+}
+
+fn load(reg: *mcp.Registry) mcp_config.Merged {
+ return mcp_config.load(reg.io, reg.arena(), Io.Dir.cwd(), g.project_path, reg.global_config_path, reg.home, reg.global_is_override);
+}
+
+/// The session connected its configured servers: from here, new ones join.
+pub fn arm(reg: *mcp.Registry, project_path: []const u8) void {
+ g.project_path = project_path;
+ g.known.clearRetainingCapacity();
+ const merged = load(reg);
+ var it = merged.servers.iterator();
+ while (it.next()) |e| g.known.append(alloc, nameHash(e.key_ptr.*)) catch {};
+ g.stamp = signature(reg.io, reg.global_config_path);
+ g.armed = true;
+}
+
+/// Before a model request: start servers that appeared in the config since the
+/// last look and give their handshakes a short window. True when tools joined.
+pub fn poll(reg: *mcp.Registry) bool {
+ if (!g.armed) return false;
+ const now = signature(reg.io, reg.global_config_path);
+ if (now == g.stamp) return false;
+ g.stamp = now;
+ const merged = load(reg);
+ var names: std.ArrayList([]const u8) = .empty;
+ defer names.deinit(alloc);
+ var it = merged.servers.iterator();
+ while (it.next()) |e| {
+ const name = e.key_ptr.*;
+ if (isKnown(name)) continue;
+ g.known.append(alloc, nameHash(name)) catch {};
+ if (e.value_ptr.* != .object or mcp_boot.alreadyStarting(reg, name)) continue;
+ if (!mcp_boot.queueConfig(reg, name, e.value_ptr.*.object)) continue;
+ names.append(alloc, name) catch continue;
+ if (@import("engine_sink.zig").hostedSink()) |sink| {
+ var buf: [160]u8 = undefined;
+ const text = std.fmt.bufPrint(&buf, "MCP: connecting {s} (added to the config)", .{name}) catch "MCP: connecting a new server";
+ sink.emit(reg.io, .{ .session_notice = .{ .text = text, .tone = .dim } });
+ }
+ }
+ if (names.items.len == 0) return false;
+ return mcp_boot.joinNamedWithin(reg, names.items, 8_000);
+}
+
+test "only names added after arming join; a touched file with no new name is quiet" {
+ if (@import("builtin").os.tag == .windows) return;
+ const io = std.testing.io;
+ resetForTest();
+ defer resetForTest();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const dir = buf[0..try tmp.dir.realPath(io, &buf)];
+ var pbuf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.fmt.bufPrint(&pbuf, "{s}/mcp.json", .{dir});
+ try tmp.dir.writeFile(io, .{ .sub_path = "mcp.json", .data = "{\"mcpServers\":{\"old\":{\"command\":\"/bin/false\"}}}" });
+ var reg = mcp.Registry.empty(std.testing.allocator, io);
+ defer reg.deinit();
+ arm(&reg, path);
+ try std.testing.expect(isKnown("old"));
+ try std.testing.expect(!poll(&reg)); // unchanged
+ try tmp.dir.writeFile(io, .{ .sub_path = "mcp.json", .data = "{\"mcpServers\":{\"old\":{\"command\":\"/bin/false\"},\"brand-new\":{\"command\":\"/bin/false\"}}}" });
+ _ = poll(&reg); // /bin/false never handshakes; the point is it was picked up
+ try std.testing.expect(isKnown("brand-new"));
+ try std.testing.expect(mcp_boot.alreadyStarting(&reg, "brand-new") or reg.pending_starts.len == 0);
+ try std.testing.expect(!poll(&reg)); // nothing new since
+}
diff --git a/src/session_start.zig b/src/session_start.zig
index f6c3dfeb..db92b750 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -532,6 +532,7 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wr
registry.global_config_path = global_path;
registry.global_is_override = mcp_config.isEnvOverride(environ_map);
registry.show_diagnostics = json_mode or flags.oneshot_prompt != null or environ_map.get("GRAFF_REPL_DEBUG") != null;
+ if (connect_mcp and !skip_imported) @import("mcp_watch.zig").arm(&registry, mcp_config_path); // live join
if (!json_mode and flags.oneshot_prompt == null) {
const ms = @max(0, mcp_t0.untilNow(io, .awake).toMilliseconds());
if (ms >= 80)