Skip to content

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

Python

perf(mcp): make Smolify lazy and public-only

Rach Pradhan33b6a0f3218d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 52c222aa..d5349475 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -63,6 +63,9 @@ jobs:
- name: Streamable HTTP MCP handshake and session regression
run: python3 scripts/test-mcp-streamable-http.py --graff zig-out/bin/graff
+ - name: Smolify lazy public-only and secret-egress boundary
+ run: python3 scripts/test-smolify-boundary.py --graff zig-out/bin/graff
+
- name: Live JSON stream contains no raw stdout lines
run: python3 scripts/test-json-live.py zig-out/bin/graff
diff --git a/README.md b/README.md
index f26fdaad..8e9ea323 100644
--- a/README.md
+++ b/README.md
@@ -466,11 +466,14 @@ 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
+Streamable HTTP servers. Smolify (`https://app.smol.ly/mcp`) is available as a
+core documentation service; it needs no Node bridge or project configuration.
+Its public-read schemas are bundled locally, so startup makes no Smolify
+request. The anonymous transport initializes only after an approved tool call,
+and recognizable credentials in arguments are blocked locally. Set
+`GRAFF_NO_SMOLIFY=1` to remove its tool surface entirely. Authenticated and
+write-capable tools are hidden unless the session explicitly opts in with
+`GRAFF_SMOLIFY_ACCESS=full`. Other servers can be added from the shell or during
a session:
```sh
@@ -478,6 +481,7 @@ 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
+GRAFF_SMOLIFY_ACCESS=full graff # expose the authenticated/full catalog
# In the REPL: /mcp add mobbin --url https://api.mobbin.com/mcp
```
diff --git a/docs/releases/v0.0.215.md b/docs/releases/v0.0.215.md
index da4eda37..838183d7 100644
--- a/docs/releases/v0.0.215.md
+++ b/docs/releases/v0.0.215.md
@@ -50,9 +50,16 @@ and connects Streamable HTTP tools without a Node bridge.
- Authentication tokens live outside the repository with user-only
permissions. Static headers remain available for servers that do not use
OAuth.
-- Smolify is available as an anonymous core documentation server without
- project configuration. `GRAFF_NO_SMOLIFY=1` disables its startup discovery
- and tool surface for offline or privacy-sensitive sessions.
+- Smolify public-read schemas are bundled locally, removing its hosted
+ discovery round trips from startup. The anonymous transport initializes only
+ after an approved call; recognizable credentials in arguments fail closed
+ before egress.
+- In five enabled runs before the change, the Smolify startup phase took
+ 185–1,094 ms. With the bundled catalog it measured 0 ms, matching the
+ disabled path while preserving a successful live first-tool-call handshake.
+- The default catalog excludes identity, private-project, rating, proposal, and
+ publishing tools. `GRAFF_SMOLIFY_ACCESS=full` explicitly opts into the full
+ OAuth-aware catalog; `GRAFF_NO_SMOLIFY=1` removes the surface entirely.
## Validation
diff --git a/scripts/test-smolify-boundary.py b/scripts/test-smolify-boundary.py
new file mode 100644
index 00000000..c6bd0329
--- /dev/null
+++ b/scripts/test-smolify-boundary.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python3
+"""Offline E2E for Smolify's lazy, public-only, secret-blocking boundary."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+
+from codex_ws_mock import CodexMock, RecordedRequest
+
+
+FINAL_REPLY = "SMOLIFY_BOUNDARY_OK"
+SAFE_TOOLS = {
+ "mcp__smolify__discover_public_projects",
+ "mcp__smolify__read_docs_structure",
+ "mcp__smolify__search_docs",
+ "mcp__smolify__get_doc_page",
+ "mcp__smolify__build_docs_context",
+ "mcp__smolify__resolve_public_symbols",
+ "mcp__smolify__inspect_public_symbols",
+ "mcp__smolify__read_public_source",
+}
+
+
+def response_events(item: dict[str, object], response_id: str) -> list[dict[str, object]]:
+ return [
+ {"type": "response.output_item.done", "item": item},
+ {
+ "type": "response.completed",
+ "response": {
+ "id": response_id,
+ "usage": {
+ "input_tokens": 10,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens": 5,
+ "total_tokens": 15,
+ },
+ },
+ },
+ ]
+
+
+def events(request: RecordedRequest) -> list[dict[str, object]]:
+ if request.ordinal == 1:
+ return response_events(
+ {
+ "type": "function_call",
+ "id": "fc_smolify_secret",
+ "call_id": "call_smolify_secret",
+ "name": "mcp__smolify__search_docs",
+ "arguments": json.dumps(
+ {"project": "public-fixture", "query": "github_token=ghp_never_egress"}
+ ),
+ "status": "completed",
+ },
+ "resp_smolify_secret",
+ )
+ return response_events(
+ {
+ "type": "message",
+ "id": "msg_smolify_done",
+ "status": "completed",
+ "role": "assistant",
+ "content": [
+ {"type": "output_text", "text": FINAL_REPLY, "annotations": []}
+ ],
+ },
+ "resp_smolify_done",
+ )
+
+
+def run(graff: Path) -> None:
+ mock = CodexMock(events_for_request=events)
+ port = mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-smolify-boundary-") as temp:
+ workspace = Path(temp)
+ codex_home = workspace / "codex-home"
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(
+ json.dumps(
+ {
+ "tokens": {
+ "access_token": "smolify-boundary-mock",
+ "account_id": "acct-smolify-boundary",
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ settings = workspace / ".harness" / "settings.json"
+ settings.parent.mkdir()
+ settings.write_text(
+ json.dumps(
+ {
+ "ai_title": False,
+ "skills": {"codedbpro": False, "muonry": False},
+ }
+ ),
+ encoding="utf-8",
+ )
+ env = {
+ key: value
+ for key, value in os.environ.items()
+ if not (key.startswith("GRAFF_") or key.startswith("CODEX_"))
+ }
+ env.update(
+ {
+ "HOME": str(workspace),
+ "CODEX_HOME": str(codex_home),
+ "GRAFF_CODEX_URL": (
+ f"http://127.0.0.1:{port}/backend-api/codex/responses"
+ ),
+ "GRAFF_CODEX_WS": "off",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+ )
+ completed = subprocess.run(
+ [
+ str(graff),
+ "--model",
+ "codex",
+ "--yolo",
+ "--no-telemetry",
+ "-p",
+ "try the hosted docs query, then report",
+ ],
+ cwd=workspace,
+ env=env,
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=20,
+ check=False,
+ )
+ if completed.returncode != 0 or completed.stdout.strip() != FINAL_REPLY:
+ raise AssertionError(
+ f"graff exit={completed.returncode}\n"
+ f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}"
+ )
+
+ requests = mock.recorded_requests()
+ if len(requests) != 2:
+ raise AssertionError(f"expected a two-request tool loop: {requests!r}")
+ advertised = {
+ tool.get("name")
+ for tool in requests[0].body.get("tools", [])
+ if isinstance(tool, dict)
+ and isinstance(tool.get("name"), str)
+ and tool["name"].startswith("mcp__smolify__")
+ }
+ if advertised != SAFE_TOOLS:
+ raise AssertionError(f"unsafe or missing default Smolify tools: {advertised!r}")
+ second_input = requests[1].body.get("input", [])
+ outputs = [
+ item.get("output", "")
+ for item in second_input
+ if isinstance(item, dict)
+ and item.get("type") == "function_call_output"
+ ]
+ if len(outputs) != 1 or "blocked locally" not in outputs[0]:
+ raise AssertionError(f"secret-bearing call did not fail closed: {outputs!r}")
+ if "GitHub token" not in outputs[0]:
+ raise AssertionError(f"block reason lost its local scan evidence: {outputs[0]!r}")
+ finally:
+ mock.stop()
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--graff", type=Path, default=Path("zig-out/bin/graff"))
+ args = parser.parse_args()
+ graff = args.graff.resolve()
+ if not graff.is_file():
+ parser.error(f"graff binary not found: {graff}")
+ run(graff)
+ print("Smolify lazy/public/secret boundary E2E passed")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/update-smolify-manifest.py b/scripts/update-smolify-manifest.py
new file mode 100644
index 00000000..f405d21e
--- /dev/null
+++ b/scripts/update-smolify-manifest.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""Refresh the deterministic, locally bundled Smolify MCP tool manifest."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import pathlib
+import sys
+import urllib.request
+
+
+ENDPOINT = "https://app.smol.ly/mcp"
+PROTOCOL = "2025-11-25"
+ROOT = pathlib.Path(__file__).resolve().parents[1]
+DEFAULT_OUTPUT = ROOT / "src" / "smolify-tools.json"
+
+
+def post(payload: dict[str, object], session_id: str | None) -> tuple[dict[str, object] | None, str | None]:
+ headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ "Mcp-Protocol-Version": PROTOCOL,
+ "User-Agent": "codegraff-smolify-manifest/1",
+ }
+ if session_id:
+ headers["Mcp-Session-Id"] = session_id
+ request = urllib.request.Request(
+ ENDPOINT,
+ data=json.dumps(payload, separators=(",", ":")).encode(),
+ headers=headers,
+ method="POST",
+ )
+ with urllib.request.urlopen(request, timeout=20) as response:
+ body = response.read().decode()
+ session_id = response.headers.get("Mcp-Session-Id") or session_id
+ if not body:
+ return None, session_id
+ if body.lstrip().startswith("data:"):
+ expected_id = payload.get("id")
+ for line in body.splitlines():
+ if not line.startswith("data:"):
+ continue
+ candidate = json.loads(line.removeprefix("data:").strip())
+ if candidate.get("id") == expected_id:
+ return candidate, session_id
+ raise RuntimeError("Smolify SSE response omitted the matching JSON-RPC id")
+ return json.loads(body), session_id
+
+
+def fetch_manifest() -> bytes:
+ initialized, session_id = post(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": PROTOCOL,
+ "capabilities": {},
+ "clientInfo": {"name": "codegraff-smolify-manifest", "version": "1"},
+ },
+ },
+ None,
+ )
+ if not initialized:
+ raise RuntimeError("Smolify initialize returned no response")
+ negotiated = initialized.get("result", {}).get("protocolVersion")
+ post({"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}}, session_id)
+ listed, _ = post({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}, session_id)
+ if not listed:
+ raise RuntimeError("Smolify tools/list returned no response")
+ tools = listed.get("result", {}).get("tools")
+ if not isinstance(tools, list) or not tools:
+ raise RuntimeError("Smolify tools/list returned an empty or invalid manifest")
+ projected = []
+ for tool in tools:
+ projected.append(
+ {
+ key: tool[key]
+ for key in ("name", "title", "description", "inputSchema")
+ if key in tool
+ }
+ )
+ normalized = {"protocolVersion": negotiated, "tools": projected}
+ return (json.dumps(normalized, separators=(",", ":"), sort_keys=True) + "\n").encode()
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--check", action="store_true", help="fail when the live manifest differs")
+ parser.add_argument("--output", type=pathlib.Path, default=DEFAULT_OUTPUT)
+ args = parser.parse_args()
+ current = args.output.read_bytes() if args.output.exists() else b""
+ fetched = fetch_manifest()
+ if args.check:
+ if current != fetched:
+ print("bundled Smolify manifest differs from the live endpoint", file=sys.stderr)
+ return 1
+ print("bundled Smolify manifest is current")
+ return 0
+ args.output.write_bytes(fetched)
+ print(f"wrote {args.output} ({len(fetched)} bytes)")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zig
index cb1fb030..f64eb6c3 100644
--- a/src/agent_tool_gate.zig
+++ b/src/agent_tool_gate.zig
@@ -108,6 +108,22 @@ fn gatePrivateTemplateSharing(self: *Agent, call: ToolCall) !?ExecResult {
};
}
+/// Hosted documentation queries still cross a network boundary after the
+/// ordinary approval prompt. Reject recognizable credentials locally even
+/// under --yolo; source/docs identifiers never need to contain a secret.
+fn gateSmolifySecrets(arena: std.mem.Allocator, call: ToolCall) !?ExecResult {
+ if (!std.mem.startsWith(u8, call.name, "mcp__smolify__")) return null;
+ var encoded: std.Io.Writer.Allocating = .init(arena);
+ var stringify: std.json.Stringify = .{ .writer = &encoded.writer };
+ try stringify.write(call.input);
+ const scan = learning_privacy.scanSecrets(encoded.writer.buffered());
+ if (scan.safe()) return null;
+ return .{
+ .text = try std.fmt.allocPrint(arena, "Smolify call blocked locally: arguments resemble a {s}. Remove secrets and send only public project/documentation identifiers.", .{scan.first_kind}),
+ .is_error = true,
+ };
+}
+
/// The permission gate, root side: an unapproved external action prompts the
/// user. Subagents never prompt; their gate is the executor's allowlist.
pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
@@ -124,6 +140,7 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
}
return null;
}
+ if (try gateSmolifySecrets(self.arena, call)) |blocked| return blocked;
if (try gatePrivateTemplateSharing(self, call)) |blocked| return blocked;
const approvals = self.approvals orelse return null;
@@ -223,7 +240,10 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
if (companionTrusted(call.name)) return null;
if (approvals.allowedExact(self.io, call.name)) return null;
key = call.name;
- prompt_line = std.fmt.bufPrint(&line_buf, "call MCP tool {s}", .{call.name}) catch call.name;
+ prompt_line = if (std.mem.startsWith(u8, call.name, "mcp__smolify__"))
+ std.fmt.bufPrint(&line_buf, "send arguments to hosted Smolify tool {s}", .{call.name}) catch call.name
+ else
+ std.fmt.bufPrint(&line_buf, "call MCP tool {s}", .{call.name}) catch call.name;
} else return null;
const in = self.in orelse return .{
@@ -269,6 +289,19 @@ test "firstWord splits the command on the first whitespace" {
try std.testing.expectEqualStrings("", firstWord(" leading"));
}
+test "Smolify arguments containing recognizable secrets fail closed locally" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const secret = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"query\":\"github_token=ghp_not-for-egress\"}", .{});
+ const public = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"query\":\"Zig HTTP client\"}", .{});
+ const blocked = (try gateSmolifySecrets(arena, .{ .id = "1", .name = "mcp__smolify__search_docs", .input = secret })).?;
+ try std.testing.expect(blocked.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, blocked.text, "blocked locally") != null);
+ try std.testing.expect((try gateSmolifySecrets(arena, .{ .id = "2", .name = "mcp__smolify__search_docs", .input = public })) == null);
+ try std.testing.expect((try gateSmolifySecrets(arena, .{ .id = "3", .name = "read_file", .input = secret })) == null);
+}
+
test "private template collector covers subagents and workflow stages" {
const io = std.testing.io;
learning_privacy.setMode(io, .templates);
diff --git a/src/main.zig b/src/main.zig
index 743abdf9..fa6e8abc 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -404,8 +404,7 @@ pub fn main(init: std.process.Init) !void {
};
if (theme_setup.should_exit) return;
boot.mark(io, "settings/theme");
- const smolify_enabled = init.environ_map.get("GRAFF_NO_SMOLIFY") == null;
- try session_start.connectCompanion(io, &registry_storage, flags, out, json_mode, smolify_enabled);
+ try session_start.connectCompanion(io, &registry_storage, flags, out, json_mode, init.environ_map);
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 13dc0818..de9ec300 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -17,6 +17,7 @@ const Allocator = std.mem.Allocator;
const mcp_http = @import("mcp_http.zig");
const mcp_protocol = @import("mcp_protocol.zig");
const mcp_stdio = @import("mcp_stdio.zig");
+const smolify_manifest = @import("smolify_manifest.zig");
const latest_protocol = mcp_protocol.latest_protocol;
const rewriteOneOf = mcp_protocol.rewriteOneOf;
@@ -47,6 +48,7 @@ const Server = struct {
name: []const u8,
transport: Transport,
next_id: i64 = 1,
+ initialized: bool = true,
/// Revision the server negotiated in its validated `initialize` response,
/// shown in `/mcp` so version skew is visible.
protocol_version: []const u8 = "?",
@@ -171,12 +173,37 @@ pub const Registry = struct {
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 {
+ /// Advertise bundled Smolify schemas without dialing the hosted endpoint.
+ /// The first approved tool call performs the MCP handshake. Default mode
+ /// is anonymous and public-read-only; full access also loads OAuth state.
+ pub fn connectSmolify(reg: *Registry, full_access: bool) !usize {
for (reg.servers) |server| if (std.mem.eql(u8, server.name, "smolify")) return 0;
- return reg.addRemoteServer("smolify", smolify_url, &.{});
+ 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 server = try a.create(Server);
+ server.* = .{
+ .name = "smolify",
+ .transport = .{ .http = .{
+ .url = smolify_url,
+ .client = .{ .allocator = reg.gpa, .io = reg.io },
+ .oauth_home = if (full_access and reg.home.len != 0) try a.dupe(u8, reg.home) else null,
+ } },
+ .initialized = false,
+ .protocol_version = "on-demand",
+ };
+ var registry_owns_server = false;
+ errdefer if (!registry_owns_server) deinitServer(server, reg.io);
+ const added = try smolify_manifest.appendTools(Tool, a, &tools, servers.items.len, full_access);
+ try servers.append(a, server);
+ const new_servers = try a.dupe(*Server, servers.items);
+ const new_tools = try a.dupe(Tool, tools.items);
+ reg.servers = new_servers;
+ reg.tools = new_tools;
+ registry_owns_server = true;
+ return added;
}
/// Connect any workspace `.mcp.json` servers not already running — the
@@ -425,6 +452,7 @@ pub const Registry = struct {
var response_arena_state = std.heap.ArenaAllocator.init(reg.gpa);
defer response_arena_state.deinit();
const response_alloc = response_arena_state.allocator();
+ if (!server.initialized) try initializeServer(server, response_alloc, reg.arena());
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.
@@ -510,6 +538,7 @@ fn initializeServer(server: *Server, response_alloc: Allocator, session_alloc: A
const protocol_version = try mcp_protocol.negotiatedProtocol(init_resp, protocol_transport);
server.protocol_version = try session_alloc.dupe(u8, protocol_version);
try notify(server, response_alloc, "notifications/initialized");
+ server.initialized = true;
}
/// JSON-RPC request/response over either transport. `params` is a raw JSON
diff --git a/src/session_start.zig b/src/session_start.zig
index df4ae82a..fdd9bfe5 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -382,7 +382,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, smolify_enabled: bool) !void {
+pub fn connectCompanion(io: Io, registry: *mcp.Registry, flags: args.Flags, out: *Io.Writer, json_mode: bool, environ_map: anytype) !void {
connect: {
for (skills.companion_servers) |c| if (skills.mcpServerConnected(registry.tools, c.server)) break :connect;
for (skills.companion_servers) |c| {
@@ -398,13 +398,34 @@ 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| {
+ // Smolify schemas are bundled and its hosted transport stays offline until
+ // an approved call. Full/authenticated/write tools require explicit opt-in.
+ if (environ_map.get("GRAFF_NO_SMOLIFY") != null) return;
+ const access = environ_map.get("GRAFF_SMOLIFY_ACCESS") orelse "public";
+ const full_access = std.ascii.eqlIgnoreCase(access, "full") or std.ascii.eqlIgnoreCase(access, "authenticated");
+ const added = registry.connectSmolify(full_access) 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();
}
+ return;
};
+ if (added > 0 and !json_mode and flags.oneshot_prompt == null)
+ try out.print("{s}[mcp:smolify] available on demand — {d} {s} tool(s){s}\n", .{ ansi.style.dim, added, if (full_access) "full-access" else "anonymous public-read", ansi.style.reset });
+}
+
+test "core Smolify registration is offline and lazy" {
+ var registry = mcp.Registry.empty(std.testing.allocator, std.testing.io);
+ defer registry.deinit();
+ try std.testing.expectEqual(@as(usize, 8), try registry.connectSmolify(false));
+ try std.testing.expectEqual(@as(usize, 1), registry.servers.len);
+ try std.testing.expectEqualStrings("on-demand", registry.servers[0].protocol_version);
+ try std.testing.expectEqual(@as(usize, 8), registry.tools.len);
+ try std.testing.expect(registry.servers[0].transport.http.oauth_home == null);
+ try std.testing.expectEqual(@as(usize, 0), try registry.connectSmolify(false));
+
+ var full = mcp.Registry.emptyWithOAuthHome(std.testing.allocator, std.testing.io, "/not-read-during-registration");
+ defer full.deinit();
+ try std.testing.expectEqual(@as(usize, 13), try full.connectSmolify(true));
+ try std.testing.expectEqualStrings("/not-read-during-registration", full.servers[0].transport.http.oauth_home.?);
}
diff --git a/src/skills.zig b/src/skills.zig
index 6de182ab..40f733da 100644
--- a/src/skills.zig
+++ b/src/skills.zig
@@ -18,6 +18,7 @@ const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const mcp = @import("mcp.zig");
+const smolify_manifest = @import("smolify_manifest.zig");
const main_mod = @import("main.zig");
const approvals_mod = @import("approvals.zig");
@@ -80,7 +81,7 @@ pub const mcp_notes = [_]McpNote{
},
.{
.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.",
+ .note = "The core Smolify MCP is available on demand (mcp__smolify__* tools). Its default catalog is anonymous and public-read-only; the network handshake waits for an approved call. Use it to discover/search public API documentation for unfamiliar libraries, while preferring local code and docs when they answer the question.",
},
};
@@ -126,6 +127,7 @@ pub fn companionTrusted(tool: []const u8) bool {
/// trust notwithstanding). Mirrors the server's readOnlyHint annotations;
/// batch is read-only iff every op inside it is.
pub fn companionReadOnly(tool: []const u8, input: Value) bool {
+ if (smolify_manifest.isPublicReadQualified(tool)) return true;
const t = companionToolName(tool) orelse return false;
if (companionToolReadOnly(t)) return true;
if (!std.mem.eql(u8, t, "batch")) return false;
@@ -306,6 +308,8 @@ test "companionReadOnly: the plan-mode classifier mirrors readOnlyHint" {
try std.testing.expect(!companionReadOnly("mcp__codedbpro__memo", none));
try std.testing.expect(!companionReadOnly("mcp__other__read", none)); // only the trusted server
try std.testing.expect(!companionReadOnly("read_file", none));
+ try std.testing.expect(companionReadOnly("mcp__smolify__search_docs", none));
+ try std.testing.expect(!companionReadOnly("mcp__smolify__publish_docs", none));
// batch: read-only iff every op is
try std.testing.expect(companionReadOnly("mcp__codedbpro__batch", parse(a,
\\{"ops":[{"tool":"read","args":{}},{"tool":"search","args":{}}]}
diff --git a/src/smolify-tools.json b/src/smolify-tools.json
new file mode 100644
index 00000000..8aec236b
--- /dev/null
+++ b/src/smolify-tools.json
@@ -0,0 +1 @@
+{"protocolVersion":"2025-11-25","tools":[{"description":"List public Smolify projects that agents may search, rate, and propose improvements for.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"query":{"maxLength":120,"type":"string"}},"type":"object"},"name":"discover_public_projects","title":"Discover public repository documentation"},{"description":"Return the signed-in identity, connected providers, granted OAuth scopes, and identity assurance used for community review status.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{},"type":"object"},"name":"whoami","title":"Inspect authenticated Smolify identity"},{"description":"List documentation projects accessible to the authenticated user.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{},"type":"object"},"name":"list_projects","title":"List Smolify projects"},{"description":"List the active documentation pages for one public or accessible Smolify project before searching or reading them.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"project":{"maxLength":120,"minLength":1,"type":"string"}},"required":["project"],"type":"object"},"name":"read_docs_structure","title":"Read documentation structure"},{"description":"Search one active documentation deployment. Exact code identifiers are matched before weighted BM25; the response reports confidence, fallback use, identifier coverage, source files, and bounded passages.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"limit":{"default":8,"maximum":20,"minimum":1,"type":"integer"},"project":{"maxLength":120,"minLength":1,"type":"string"},"query":{"maxLength":500,"minLength":1,"type":"string"}},"required":["project","query"],"type":"object"},"name":"search_docs","title":"Search hosted documentation"},{"description":"Read a bounded Markdown slice from an active page. Use search_docs first and continue with offset when totalLength exceeds the returned slice.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"length":{"default":12000,"maximum":40000,"minimum":1000,"type":"integer"},"offset":{"default":0,"maximum":9007199254740991,"minimum":0,"type":"integer"},"project":{"maxLength":120,"minLength":1,"type":"string"},"slug":{"maxLength":160,"minLength":1,"type":"string"}},"required":["project","slug"],"type":"object"},"name":"get_doc_page","title":"Read a hosted documentation page"},{"description":"Compose an answer-sized evidence pack with exact identifier lookup, focused FTS5/BM25 facets, and eligible commit-pinned public source ranges. Smolify does not call embeddings or an answer model; the calling agent synthesizes and cites the evidence.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"maxPages":{"default":6,"maximum":10,"minimum":1,"type":"integer"},"maxTokens":{"default":4000,"maximum":12000,"minimum":1000,"type":"integer"},"project":{"maxLength":120,"minLength":1,"type":"string"},"task":{"maxLength":1000,"minLength":3,"type":"string"}},"required":["project","task"],"type":"object"},"name":"build_docs_context","title":"Build bounded documentation context"},{"description":"Resolve up to eight exact code identifiers without embeddings by checking source-file hints first, then ranking the imported GitHub tree and scanning at most 96 files/4 MB. Returns value-free paths, line numbers, match kinds, and commit-pinned links.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"maxResults":{"default":8,"maximum":20,"minimum":1,"type":"integer"},"pathHints":{"items":{"maxLength":500,"minLength":1,"type":"string"},"maxItems":20,"type":"array"},"project":{"maxLength":120,"minLength":1,"type":"string"},"symbols":{"items":{"pattern":"^[A-Za-z_$][\\w$]{2,120}$","type":"string"},"maxItems":8,"minItems":1,"type":"array"}},"required":["project","symbols"],"type":"object"},"name":"resolve_public_symbols","title":"Resolve identifiers in pinned public source"},{"description":"Build value-free CodeDB-style evidence for up to eight exact identifiers: definitions, scoped callers, callees, and short connector paths that reach multiple requested symbols. Relative imports are followed before the bounded 96-file/4-MB fallback scan. No source body is persisted.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"maxResults":{"default":8,"maximum":20,"minimum":1,"type":"integer"},"pathHints":{"items":{"maxLength":500,"minLength":1,"type":"string"},"maxItems":20,"type":"array"},"project":{"maxLength":120,"minLength":1,"type":"string"},"symbols":{"items":{"pattern":"^[A-Za-z_$][\\w$]{2,120}$","type":"string"},"maxItems":8,"minItems":1,"type":"array"}},"required":["project","symbols"],"type":"object"},"name":"inspect_public_symbols","title":"Inspect pinned public symbol relationships"},{"description":"Read at most 200 explicit lines from a safe source-code path at the public GitHub commit imported by Smolify. Disabled for private repositories, ZIP uploads, and metadata-only projects.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"lineCount":{"default":80,"maximum":200,"minimum":1,"type":"integer"},"path":{"maxLength":500,"minLength":1,"type":"string"},"project":{"maxLength":120,"minLength":1,"type":"string"},"startLine":{"default":1,"maximum":9007199254740991,"minimum":1,"type":"integer"}},"required":["project","path"],"type":"object"},"name":"read_public_source","title":"Read commit-pinned public source lines"},{"description":"Record or update one authenticated GPT-5.6 agent rating for a readable project.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"model":{"maxLength":80,"pattern":"^gpt-5\\.6(?:$|[-.])","type":"string"},"notes":{"maxLength":2000,"type":"string"},"project":{"maxLength":120,"minLength":1,"type":"string"},"score":{"maximum":5,"minimum":1,"type":"integer"}},"required":["project","score","model"],"type":"object"},"name":"rate_docs","title":"Rate public documentation"},{"description":"Submit a complete validated replacement bundle for owner review. This never changes the live deployment by itself.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"bundle":{"properties":{"generatedAt":{"format":"date-time","pattern":"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$","type":"string"},"generator":{"properties":{"model":{"maxLength":80,"minLength":1,"type":"string"},"name":{"enum":["codex","smolify"],"type":"string"}},"required":["name","model"],"type":"object"},"navigation":{"items":{"properties":{"items":{"items":{"properties":{"label":{"maxLength":80,"minLength":1,"type":"string"},"slug":{"maxLength":160,"minLength":1,"type":"string"}},"required":["label","slug"],"type":"object"},"maxItems":100,"minItems":1,"type":"array"},"label":{"maxLength":80,"minLength":1,"type":"string"}},"required":["label","items"],"type":"object"},"maxItems":30,"minItems":1,"type":"array"},"pages":{"items":{"properties":{"description":{"default":"","maxLength":240,"type":"string"},"markdown":{"maxLength":250000,"minLength":1,"type":"string"},"slug":{"maxLength":160,"minLength":1,"pattern":"^[a-z0-9]+(?:[/-][a-z0-9]+)*$","type":"string"},"sourceFiles":{"default":[],"items":{"maxLength":500,"type":"string"},"maxItems":100,"type":"array"},"title":{"maxLength":120,"minLength":1,"type":"string"}},"required":["slug","title","markdown"],"type":"object"},"maxItems":500,"minItems":1,"type":"array"},"project":{"properties":{"accent":{"default":"#6d5efc","pattern":"^#[0-9a-fA-F]{6}$","type":"string"},"description":{"maxLength":240,"type":"string"},"name":{"maxLength":80,"minLength":1,"type":"string"}},"required":["name","description"],"type":"object"},"schemaVersion":{"const":1,"type":"number"}},"required":["schemaVersion","project","generatedAt","generator","navigation","pages"],"type":"object"},"model":{"maxLength":80,"pattern":"^gpt-5\\.6(?:$|[-.])","type":"string"},"project":{"maxLength":120,"minLength":1,"type":"string"},"rationale":{"maxLength":4000,"minLength":20,"type":"string"},"summary":{"maxLength":240,"minLength":8,"type":"string"}},"required":["project","model","summary","rationale","bundle"],"type":"object"},"name":"propose_doc_improvement","title":"Propose improved documentation"},{"description":"Validate, store, index, and activate an immutable Smolify bundle. This changes the public documentation deployment and requires explicit user approval.","inputSchema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"bundle":{"properties":{"generatedAt":{"format":"date-time","pattern":"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$","type":"string"},"generator":{"properties":{"model":{"maxLength":80,"minLength":1,"type":"string"},"name":{"enum":["codex","smolify"],"type":"string"}},"required":["name","model"],"type":"object"},"navigation":{"items":{"properties":{"items":{"items":{"properties":{"label":{"maxLength":80,"minLength":1,"type":"string"},"slug":{"maxLength":160,"minLength":1,"type":"string"}},"required":["label","slug"],"type":"object"},"maxItems":100,"minItems":1,"type":"array"},"label":{"maxLength":80,"minLength":1,"type":"string"}},"required":["label","items"],"type":"object"},"maxItems":30,"minItems":1,"type":"array"},"pages":{"items":{"properties":{"description":{"default":"","maxLength":240,"type":"string"},"markdown":{"maxLength":250000,"minLength":1,"type":"string"},"slug":{"maxLength":160,"minLength":1,"pattern":"^[a-z0-9]+(?:[/-][a-z0-9]+)*$","type":"string"},"sourceFiles":{"default":[],"items":{"maxLength":500,"type":"string"},"maxItems":100,"type":"array"},"title":{"maxLength":120,"minLength":1,"type":"string"}},"required":["slug","title","markdown"],"type":"object"},"maxItems":500,"minItems":1,"type":"array"},"project":{"properties":{"accent":{"default":"#6d5efc","pattern":"^#[0-9a-fA-F]{6}$","type":"string"},"description":{"maxLength":240,"type":"string"},"name":{"maxLength":80,"minLength":1,"type":"string"}},"required":["name","description"],"type":"object"},"schemaVersion":{"const":1,"type":"number"}},"required":["schemaVersion","project","generatedAt","generator","navigation","pages"],"type":"object"},"project":{"maxLength":120,"minLength":1,"type":"string"}},"required":["project","bundle"],"type":"object"},"name":"publish_docs","title":"Publish a documentation bundle"}]}
diff --git a/src/smolify_manifest.zig b/src/smolify_manifest.zig
new file mode 100644
index 00000000..d153414d
--- /dev/null
+++ b/src/smolify_manifest.zig
@@ -0,0 +1,106 @@
+//! Bundled Smolify tool metadata. Startup advertises these schemas without
+//! dialing the hosted MCP; the transport initializes only after an approved
+//! tool call. Refresh the generated JSON with update-smolify-manifest.py.
+
+const std = @import("std");
+const mcp_protocol = @import("mcp_protocol.zig");
+
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+const manifest_json = @embedFile("smolify-tools.json");
+
+pub const bundled_protocol = mcp_protocol.latest_protocol;
+
+const public_read_tools = [_][]const u8{
+ "discover_public_projects",
+ "read_docs_structure",
+ "search_docs",
+ "get_doc_page",
+ "build_docs_context",
+ "resolve_public_symbols",
+ "inspect_public_symbols",
+ "read_public_source",
+};
+
+pub fn isPublicReadName(name: []const u8) bool {
+ for (public_read_tools) |allowed| {
+ if (std.mem.eql(u8, name, allowed)) return true;
+ }
+ return false;
+}
+
+pub fn isPublicReadQualified(name: []const u8) bool {
+ const prefix = "mcp__smolify__";
+ return std.mem.startsWith(u8, name, prefix) and isPublicReadName(name[prefix.len..]);
+}
+
+/// Append bundled Smolify tools to an MCP-compatible Tool list. Keeping this
+/// generic makes this leaf module independent from mcp.zig's Registry type.
+pub fn appendTools(
+ comptime Tool: type,
+ a: Allocator,
+ out: *std.ArrayList(Tool),
+ server_index: usize,
+ full_access: bool,
+) !usize {
+ const parsed = try std.json.parseFromSliceLeaky(Value, a, manifest_json, .{ .allocate = .alloc_always });
+ if (parsed != .object) return error.BadSmolifyManifest;
+ const protocol = parsed.object.get("protocolVersion") orelse return error.BadSmolifyManifest;
+ if (protocol != .string or !std.mem.eql(u8, protocol.string, bundled_protocol)) return error.StaleSmolifyManifestProtocol;
+ const tools = parsed.object.get("tools") orelse return error.BadSmolifyManifest;
+ if (tools != .array) return error.BadSmolifyManifest;
+ const before = out.items.len;
+ for (tools.array.items) |tool| {
+ if (tool != .object) return error.BadSmolifyManifest;
+ const name_v = tool.object.get("name") orelse return error.BadSmolifyManifest;
+ if (name_v != .string or name_v.string.len == 0) return error.BadSmolifyManifest;
+ if (!full_access and !isPublicReadName(name_v.string)) continue;
+ const description = if (tool.object.get("description")) |v|
+ (if (v == .string) v.string else "")
+ else if (tool.object.get("title")) |v|
+ (if (v == .string) v.string else "")
+ else
+ "";
+ var schema = tool.object.get("inputSchema") orelse Value{ .object = .empty };
+ try mcp_protocol.rewriteOneOf(a, &schema);
+ try out.append(a, .{
+ .server_index = server_index,
+ .original_name = try a.dupe(u8, name_v.string),
+ .qualified_name = try std.fmt.allocPrint(a, "mcp__smolify__{s}", .{name_v.string}),
+ .description = try a.dupe(u8, description),
+ .input_schema = schema,
+ });
+ }
+ if (out.items.len == before) return error.EmptySmolifyManifest;
+ return out.items.len - before;
+}
+
+const TestTool = struct {
+ server_index: usize,
+ original_name: []const u8,
+ qualified_name: []const u8,
+ description: []const u8,
+ input_schema: Value,
+};
+
+test "bundled default exposes only anonymous public-read tools" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var tools: std.ArrayList(TestTool) = .empty;
+ try std.testing.expectEqual(@as(usize, public_read_tools.len), try appendTools(TestTool, a, &tools, 3, false));
+ for (tools.items) |tool| {
+ try std.testing.expectEqual(@as(usize, 3), tool.server_index);
+ try std.testing.expect(isPublicReadQualified(tool.qualified_name));
+ try std.testing.expect(tool.input_schema == .object);
+ }
+}
+
+test "full opt-in exposes the complete generated manifest" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var tools: std.ArrayList(TestTool) = .empty;
+ try std.testing.expectEqual(@as(usize, 13), try appendTools(TestTool, a, &tools, 0, true));
+ try std.testing.expect(!isPublicReadQualified("mcp__smolify__publish_docs"));
+}