graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: honor explicit project MCP configuration
Rach Pradhan83e5c3835160
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 19781a6f..d5537c2c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -115,6 +115,9 @@ jobs:- name: Streamable HTTP MCP handshake and session regressionrun: python3 scripts/test-mcp-streamable-http.py --graff zig-out/bin/graff+ - name: Optional MCP project opt-in and startup consent+ run: python3 scripts/test-mcp-optional.py zig-out/bin/graff+- name: Embedder mode --no-local-tools gate (#330)run: python3 scripts/test-no-local-tools.py --graff zig-out/bin/graffdiff --git a/assets/skills/mcp.md b/assets/skills/mcp.mdnew file mode 100644index 00000000..fdb5b7b3--- /dev/null+++ b/assets/skills/mcp.md@@ -0,0 +1,70 @@+---+name: mcp+description: Add, connect, or invoke an MCP server in this workspace — use when the user says "using the MCP skill", asks to add/connect/enable/turn on an MCP, pastes an MCP URL or npx package, or wants DeepWiki/Mobbin tools this session.+---++# Add and invoke an MCP server++This is the invocative half. `mcp-config` is the schema reference; load it+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"):++```sh+graff mcp add <name> --url https://host/mcp+graff mcp add <name> -- <command> [args...]+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>`.++4. Connect **this** session. Editing the file does not attach tools to the+ running harness. Ask the user to run one of:++```+/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.++## DeepWiki and Mobbin++When configured, boot skips a `deepwiki` / `mobbin` entry inherited from+global or plugin configuration unless `GRAFF_DEEPWIKI` / `GRAFF_MOBBIN`+is set, or `GRAFF_MCP_OPTIONAL=deepwiki,mobbin`.+A workspace `.mcp.json` that lists them is the project opting in. Startup+consent (`/mcp trust` or `--yolo`) still applies.++DeepWiki's public server is `https://mcp.deepwiki.com/mcp` (no auth). Tools+are `read_wiki_structure`, `read_wiki_contents`, and `ask_question`. Do not+webfetch DeepWiki pages; use those tools once loaded.++## Examples++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`.++User: "add playwright MCP"++- `graff mcp add playwright -- npx -y @playwright/mcp`+- Then `/mcp add playwright npx -y @playwright/mcp`.diff --git a/build.zig b/build.zigindex 9e4fe512..4c259450 100644--- a/build.zig+++ b/build.zig@@ -148,6 +148,7 @@ pub fn build(b: *std.Build) void {for ([_]struct { import: []const u8, path: []const u8 }{.{ .import = "skill_doc_creator", .path = "assets/skills/skill-creator.md" },.{ .import = "skill_doc_mcp_config", .path = "assets/skills/mcp-config.md" },+ .{ .import = "skill_doc_mcp", .path = "assets/skills/mcp.md" },.{ .import = "skill_doc_jspace", .path = "assets/skills/jspace.md" },.{ .import = "skill_doc_workspace", .path = "assets/skills/workspace.md" },}) |asset| {diff --git a/docs/adr/0110-project-mcp-listing-opts-in-optional-servers.md b/docs/adr/0110-project-mcp-listing-opts-in-optional-servers.mdnew file mode 100644index 00000000..ecdff906--- /dev/null+++ b/docs/adr/0110-project-mcp-listing-opts-in-optional-servers.md@@ -0,0 +1,27 @@+# 0110. A project MCP listing opts in optional servers++Status: accepted 2026-09-13++## Context++Optional server names were filtered at startup even when the workspace+explicitly configured them. Adding one to `.mcp.json` appeared to succeed,+but the next session silently skipped its handshake.++## Decision++- A server listed in the project `.mcp.json` opts in that optional server.+- Optional entries inherited only from global or plugin configuration retain+ their environment opt-in requirement.+- Opt-in selects which configured servers may start. The existing startup+ consent gate still applies equally to project and inherited servers.+- The bundled `mcp` skill explains configuration and connecting tools in the+ current session; `mcp-config` remains the detailed schema reference.++## Consequences++Project configuration works without an additional environment switch. Imported+extras stay quiet by default, and merely writing configuration does not grant+permission to connect. The offline `scripts/test-mcp-optional.py` fixture+checks both optional server names, both configuration scopes, explicit opt-in,+and startup with and without consent.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex ef5f27f4..8cb1e80b 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -120,6 +120,7 @@ record only when you need the evidence or the edge cases.| [0107](0107-model-drawn-pages-render-in-an-opaque-frame.md) | A page the model draws (`render_html`) is a private snapshot served under a CSP sandbox; the model picks the presentation, never the privilege. || [0108](0108-browser-events-outrank-pending-snapshots.md) | Browser page-info events invalidate older pending IPC snapshots; a loaded page must not revert to loading. || [0109](0109-resume-retains-catalog-and-layout-snapshots.md) | Resume restores loaded tool selections and the same-workspace layout snapshot, without freezing current instructions or granting permissions. |+| [0110](0110-project-mcp-listing-opts-in-optional-servers.md) | Project MCP entries opt in optional servers; inherited extras still require opt-in, and startup consent applies to both. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex ec5e2a2d..f80d09f0 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -79,3 +79,4 @@{"id": "completion-search-citations-clean", "why": "#819: the authoritative completion must remove search citation control spans while preserving human prose; the release regression also covers byte-fragmented line output.", "args": ["--old"], "prompt": "Return the scripted final result.", "script": [{"tool": "attempt_completion", "arguments": {"result": "Read the docsciteturn0search0turn1search2 today."}, "argument_chunk_size": 1}], "assert": [{"final_text_contains": "Read the docs today."}]}{"id": "publication-unresolved-command-refused", "why": "#847: a non-literal publication command cannot bypass head/body inspection by chaining checks before creation. No GitHub write or lookup should execute.", "args": ["--old"], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Exercise the scripted prepublication refusal.", "script": [{"tool": "bash", "arguments": {"command": "gh pr checks --watch && gh pr create --title fixture --body '## Verification: local passed'"}}, {"text": "The publication was blocked."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "is_error": true}}, {"request_contains": {"text": "separate literal gh pr command"}}, {"final_text_contains": "The publication was blocked."}]}{"id": "render-html-hands-back-an-opaque-view", "why": "The model's own drawing surface must be advertised, dispatch to the snapshot writer, and put only the opaque path into the transcript - a page the model drew must never come back to it as a second copy of the markup.", "args": [], "prompt": "draw the retry flow as a page", "script": [{"tool": "render_html", "arguments": {"html": "<h1 id=\"flow\">Retry flow</h1><p>the second attempt is declined</p>"}}, {"text": "drawn above"}], "assert": [{"request_contains": {"index": 0, "text": "render_html"}}, {"events_at_least": {"match": {"type": "tool_call", "name": "render_html"}, "count": 1}}, {"event": {"type": "tool_result"}}, {"request_contains": {"index": -1, "text": "[Rendered view]"}}, {"request_contains": {"index": -1, "text": "/.graff/views/"}}, {"final_text_contains": "drawn above"}]}+{"id": "bundled-mcp-skill-loads", "why": "The bundled invocation skill must be discoverable and load its connection instructions after adding an MCP server.", "prompt": "Load the bundled mcp skill before adding a server.", "script": [{"tool": "skill", "arguments": {"name": "mcp"}}, {"text": "MCP instructions loaded."}], "assert": [{"event": {"type": "tool_call", "name": "skill"}}, {"request_contains": {"index": -1, "text": "graff mcp add"}}, {"request_contains": {"index": -1, "text": "/mcp trust"}}, {"final_text_contains": "MCP instructions loaded."}]}diff --git a/scripts/test-mcp-optional.py b/scripts/test-mcp-optional.pynew file mode 100644index 00000000..703d8763--- /dev/null+++ b/scripts/test-mcp-optional.py@@ -0,0 +1,83 @@+#!/usr/bin/env python3+"""Offline startup proof: project MCP opt-in never replaces consent.++No model requests or network servers are needed. The local stdio fixture+records successful initialize and tools/list requests before graff exits.+"""+import json+import os+from pathlib import Path+import sys+import tempfile++sys.path.insert(0, str(Path(__file__).parent / "eval"))+from process_guard import run as bounded_run+++def serve(log):+ for line in sys.stdin:+ request = json.loads(line)+ method = request["method"]+ with log.open("a") as output:+ output.write(method + "\n")+ if method == "initialize":+ result = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {}},+ "serverInfo": {"name": "optional-fixture", "version": "1"}}+ elif method == "tools/list":+ result = {"tools": []}+ else:+ continue+ print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True)+++def run_case(graff, name, project, opted_in, consent):+ with tempfile.TemporaryDirectory(prefix="graff-optional-mcp-") as temp:+ root = Path(temp)+ log = root / "requests.txt"+ config = {"mcpServers": {name: {+ "command": sys.executable,+ "args": [str(Path(__file__).resolve()), "--serve", str(log)],+ }}}+ # A missing override keeps real global config out and allows the project+ # merge; a valid empty override would disable MCP altogether.+ global_path = root / "global.json"+ path = root / ".mcp.json" if project else global_path+ path.write_text(json.dumps(config))+ settings = root / ".harness" / "settings.json"+ settings.parent.mkdir()+ settings.write_text('{"skills":{"codedbpro":false,"muonry":false}}')+ env = {key: value for key, value in os.environ.items()+ if not key.endswith("_API_KEY") and key not in (+ "GRAFF_DEEPWIKI", "GRAFF_MOBBIN", "GRAFF_MCP_OPTIONAL")}+ env.update(LMSTUDIO_API_KEY="fixture-not-used", GRAFF_MCP_CONFIG=str(global_path),+ GRAFF_NO_PLUGINS="1", GRAFF_MCP_PROBE="0", GRAFF_FLEET="off",+ GRAFF_NO_SMOLIFY="1", GRAFF_NO_TELEMETRY="1", GRAFF_BEHAVIOR_TRACE="0")+ env["HOME"] = str(root)+ if opted_in:+ env["GRAFF_MCP_OPTIONAL"] = name+ argv = [str(graff), "--json", "--model", "lmstudio"]+ if consent:+ argv.append("--yolo")+ run = bounded_run(argv, cwd=root, env=env, input="", text=True,+ capture_output=True, timeout=40)+ assert run.returncode == 0, run.stderr[-2000:]+ methods = log.read_text().splitlines() if log.exists() else []+ expected = consent and (project or opted_in)+ label = f"{name}: project={project}, opt-in={opted_in}, consent={consent}"+ if expected:+ assert "initialize" in methods and "tools/list" in methods, (label, methods, run.stderr)+ else:+ assert not methods, (label, methods)+ print("PASS " + label)+++if __name__ == "__main__":+ if len(sys.argv) > 1 and sys.argv[1] == "--serve":+ serve(Path(sys.argv[2]))+ else:+ graff = Path(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff").resolve()+ for name in ("deepwiki", "mobbin"):+ for project, opted_in, consent in (+ (True, False, True), (False, False, True), (False, True, True),+ (True, False, False), (True, True, False), (False, True, False)):+ run_case(graff, name, project, opted_in, consent)diff --git a/src/mcp_boot.zig b/src/mcp_boot.zigindex 136e8205..e8d57ce6 100644--- a/src/mcp_boot.zig+++ b/src/mcp_boot.zig@@ -124,7 +124,7 @@ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]convar entries: std.ArrayList(Entry) = .empty;var it = merged.servers.iterator();while (it.next()) |entry| {- if (@import("tool_surface.zig").skipOptionalServer(entry.key_ptr.*, environ_map)) continue;+ if (@import("tool_surface.zig").skipOptionalAtBoot(entry.key_ptr.*, environ_map, merged.isGlobalOnly(entry.key_ptr.*))) continue;if (entry.value_ptr.* != .object) continue;try entries.append(a, .{ .name = try a.dupe(u8, entry.key_ptr.*), .cfg = entry.value_ptr.*.object });}diff --git a/src/skill_docs.zig b/src/skill_docs.zigindex 1ec1196b..a60a7546 100644--- a/src/skill_docs.zig+++ b/src/skill_docs.zig@@ -10,8 +10,8 @@//! and disclosure is progressive: only the descriptions ride in the system prompt//! (promptCatalog), while bodies stay on disk until the `skill` tool loads one//! (execSkill). Bundled skills teach writing more (skill-creator), MCP-//! config (mcp-config), long-horizon control (jspace), and mid-session-//! worktree switch (workspace).+//! config (mcp-config), adding an MCP (mcp), long-horizon control (jspace),+//! and mid-session worktree switch (workspace).const std = @import("std");const Io = std.Io;@@ -68,7 +68,7 @@ const desc_cap = 160; // per-skill description budget in the system prompt — t/// a schema.ToolSpec) so schema.zig's catalog needs one entry and no import/// cycle. The description must stay free of characters needing JSON escapes.pub const tool_name = "skill";-pub const tool_desc = "Load a skill: the full instructions for one kind of task, kept out of your context until you need them. The system prompt lists only skill names and descriptions, so call this to read the body BEFORE doing work a skill covers, then follow it. Omit name to list every available skill. Skills come from .harness/skills/, ~/.harness/skills/, .claude/skills/, Cursor/Claude/Grok/Codex plugin trees (including Claude commands/*.md and a root SKILL.md), plus bundled skill-creator, mcp-config, jspace, and workspace.";+pub const tool_desc = "Load a skill: the full instructions for one kind of task, kept out of your context until you need them. The system prompt lists only skill names and descriptions, so call this to read the body BEFORE doing work a skill covers, then follow it. Omit name to list every available skill. Skills come from .harness/skills/, ~/.harness/skills/, .claude/skills/, Cursor/Claude/Grok/Codex plugin trees (including Claude commands/*.md and a root SKILL.md), plus bundled skill-creator, mcp-config, mcp, jspace, and workspace.";pub const tool_schema =\\{"type": "object", "properties": {"name": {"type": "string", "description": "Skill name to load; omit to list every available skill"}}};@@ -103,6 +103,7 @@ const Embedded = struct { fallback: []const u8, bytes: []const u8 };const embedded = [_]Embedded{.{ .fallback = "skill-creator", .bytes = @embedFile("skill_doc_creator") },.{ .fallback = "mcp-config", .bytes = @embedFile("skill_doc_mcp_config") },+ .{ .fallback = "mcp", .bytes = @embedFile("skill_doc_mcp") },.{ .fallback = "jspace", .bytes = @embedFile("skill_doc_jspace") },.{ .fallback = "workspace", .bytes = @embedFile("skill_doc_workspace") },};@@ -383,11 +384,12 @@ test "parseDoc: no frontmatter keeps the filename and the whole file as body" {}test "bundled skills: both parse at comptime with a trigger description" {- try std.testing.expectEqual(@as(usize, 4), builtins.len);+ try std.testing.expectEqual(@as(usize, 5), builtins.len);try std.testing.expectEqualStrings("skill-creator", builtins[0].name);try std.testing.expectEqualStrings("mcp-config", builtins[1].name);- try std.testing.expectEqualStrings("jspace", builtins[2].name);- try std.testing.expectEqualStrings("workspace", builtins[3].name);+ try std.testing.expectEqualStrings("mcp", builtins[2].name);+ try std.testing.expectEqualStrings("jspace", builtins[3].name);+ try std.testing.expectEqualStrings("workspace", builtins[4].name);for (builtins) |sk| {try std.testing.expect(sk.desc.len > 40); // a trigger, not a topic wordtry std.testing.expect(sk.body.len > 500);@@ -399,14 +401,16 @@ test "bundled skills: both parse at comptime with a trigger description" {try std.testing.expect(std.mem.indexOf(u8, builtins[0].body, project_dir) != null);try std.testing.expect(std.mem.indexOf(u8, builtins[1].body, ".mcp.json") != null);try std.testing.expect(std.mem.indexOf(u8, builtins[1].body, "/mcp trust") != null);- try std.testing.expect(std.mem.indexOf(u8, builtins[2].body, "action=inbox") != null);- try std.testing.expect(std.mem.indexOf(u8, builtins[3].body, "action=use") != null);+ try std.testing.expect(std.mem.indexOf(u8, builtins[2].body, "graff mcp add") != null);+ try std.testing.expect(std.mem.indexOf(u8, builtins[3].body, "action=inbox") != null);+ try std.testing.expect(std.mem.indexOf(u8, builtins[4].body, "action=use") != null);}test "tool_desc stays JSON-escape-free (it is spliced into a raw schema string)" {for (tool_desc) |c| try std.testing.expect(c != '"' and c != '\\' and c >= 0x20);try std.testing.expect(std.mem.indexOf(u8, tool_desc, "skill-creator") != null);try std.testing.expect(std.mem.indexOf(u8, tool_desc, "mcp-config") != null);+ try std.testing.expect(std.mem.indexOf(u8, tool_desc, "mcp") != null);try std.testing.expect(std.mem.indexOf(u8, tool_desc, "jspace") != null);try std.testing.expect(std.mem.indexOf(u8, tool_desc, "workspace") != null);}diff --git a/src/tool_surface.zig b/src/tool_surface.zigindex bb990d74..57a8a4f4 100644--- a/src/tool_surface.zig+++ b/src/tool_surface.zig@@ -114,6 +114,12 @@ pub fn skipOptionalServer(name: []const u8, environ_map: anytype) bool {return false;}+/// Extras inherited from global/plugin config stay opt-in. A workspace+/// `.mcp.json` listing opts in that server; startup consent still applies.+pub fn skipOptionalAtBoot(name: []const u8, environ_map: anytype, global_only: bool) bool {+ return global_only and skipOptionalServer(name, environ_map);+}+fn optionalAllowed(name: []const u8, environ_map: anytype) bool {if (environ_map.get("GRAFF_MCP_OPTIONAL")) |v| {var it = std.mem.tokenizeAny(u8, v, ", ");@@ -242,6 +248,14 @@ test "skipOptionalServer keeps deepwiki/mobbin opt-in" {try std.testing.expect(!skipOptionalServer("mobbin", env));}+test "skipOptionalAtBoot lets a workspace listing connect" {+ var env = std.process.Environ.Map.init(std.testing.allocator);+ defer env.deinit();+ try std.testing.expect(skipOptionalAtBoot("deepwiki", env, true));+ try std.testing.expect(!skipOptionalAtBoot("deepwiki", env, false));+ try std.testing.expect(!skipOptionalAtBoot("codedbpro", env, true));+}+test "worker specs keep read_file and codedb; worker MCP keeps pro reads not writes" {const schema = @import("schema.zig");const saved = main_mod.g_codedbpro_licensed;