xonecas.io
79113
Ma

mini-coding-agent / commit 51d305c

feat: implement the stateless MCP protocol

The ecosystem is a mess, so we need to negociate some versions to find
out if the server supports some form of stateless. Craptastic.

xonecas2026-10-14 51d305c45878dae325956c514a04a05cdd844072 parent edc9841

6 files changed

README.md+25−0
@@ -72,6 +72,23 @@ error.
7272 | `edit` | replaces `oldText`, which must occur exactly once; an empty `oldText` creates a new file and fails if it exists; prints a unified diff |
7373 | `bash` | runs `bash -c` in the cwd with a 120s default `timeout`; output keeps the first 10k and last 6k bytes; a before/after snapshot of the cwd reports changed files as diffs |
7474
75+## MCP
76+
77+`mini mcp` speaks the stateless MCP protocol to the servers in `mcpServers`.
78+It probes a revision and, when a server rejects it, retries with the newest
79+revision that server advertises, so no single revision is pinned. It lets the
80+`bash` tool reach MCP tools without any MCP tool description entering the
81+model's context: the model discovers and calls them with three commands,
82+composing them like any other shell command.
83+
84+ mini mcp search <query> # ranked { path, description } matches
85+ mini mcp describe <path> # the description and input signature
86+ mini mcp invoke <path> <json> # call a tool with a JSON argument object
87+
88+A tool path is `<server>.<tool>`, for example
89+`mini mcp invoke context7.resolve-library-id '{"libraryName":"zig"}'`. Absent
90+`mcpServers`, every command reports that no servers are configured.
91+
7592 ## Configure
7693
7794 The config is one JSON object. It is read from
@@ -92,6 +109,13 @@ A full example:
92109 "discoverAgentFiles": true,
93110 "skillsDirs": ["/home/me/.agents/skills"],
94111 "tools": ["edit", "read", "bash"],
112+ "mcpServers": {
113+ "context7": { "url": "https://mcp.context7.com/mcp" },
114+ "firecrawl": {
115+ "url": "https://mcp.firecrawl.dev/v2/mcp",
116+ "headers": { "Authorization": "Bearer fc-YOUR-API-KEY" }
117+ }
118+ },
95119 "snapshotIgnoreDirs": [".git"],
96120 "snapshotUsesGitignore": true,
97121 "historySize": 100,
@@ -135,6 +159,7 @@ Keys:
135159 | `skillsDirs` | `[]` | directories holding `<name>/SKILL.md` skills; each `SKILL.md` needs a `name` in its frontmatter (optional `description`) |
136160 | `tools` | `["edit", "read", "bash"]` | which tools the model sees |
137161 | `customProviders` | `[]` | in-tree provider definitions |
162+| `mcpServers` | `{}` | named MCP servers (`<name>: { url, headers }`) the `mini mcp` subcommand talks to |
138163 | `snapshotIgnoreDirs` | `[]` | directory names skipped when the `bash` tool snapshots the cwd for diffs |
139164 | `snapshotUsesGitignore` | `true` | also skip directories named in `.gitignore` when snapshotting |
140165 | `historySize` | `100` | past inputs kept in `<state dir>/mini-coding-agent/history` for `Ctrl+R` |
src/config.zig+9−0
@@ -32,6 +32,11 @@ pub const CustomProvider = struct {
3232 headers: ?std.json.ArrayHashMap([]const u8) = null,
3333 };
3434
35+pub const McpServer = struct {
36+ url: []const u8,
37+ headers: ?std.json.ArrayHashMap([]const u8) = null,
38+};
39+
3540 pub const Config = struct {
3641 path: []const u8,
3742 sessions_dir: []const u8,
@@ -45,6 +50,7 @@ pub const Config = struct {
4550 theme: []const u8,
4651 program_status: bool,
4752 custom_providers: []const CustomProvider,
53+ mcp_servers: std.json.ArrayHashMap(McpServer),
4854 snapshot_ignore_dirs: []const []const u8,
4955 snapshot_uses_gitignore: bool,
5056 history_size: usize,
@@ -63,6 +69,7 @@ const File = struct {
6369 model: ?[]const u8 = null,
6470 thinkingEffort: ?[]const u8 = null,
6571 customProviders: ?[]const CustomProvider = null,
72+ mcpServers: ?std.json.ArrayHashMap(McpServer) = null,
6673 theme: ?[]const u8 = null,
6774 programStatus: ?bool = null,
6875 snapshotIgnoreDirs: ?[]const []const u8 = null,
@@ -139,6 +146,7 @@ fn readInto(a: std.mem.Allocator, path: []const u8, required: bool, cfg: *Config
139146 if (file.skillsDirs) |v| cfg.skills_dirs = v;
140147 if (file.tools) |v| cfg.tools = v;
141148 if (file.customProviders) |v| cfg.custom_providers = v;
149+ if (file.mcpServers) |v| cfg.mcp_servers = v;
142150 if (file.thinkingEffort) |v| cfg.thinking_effort = v;
143151 if (file.theme) |v| cfg.theme = v;
144152 if (file.programStatus) |v| cfg.program_status = v;
@@ -194,6 +202,7 @@ fn defaults(a: std.mem.Allocator) !Config {
194202 .theme = "tokyonight",
195203 .program_status = false,
196204 .custom_providers = &.{},
205+ .mcp_servers = .{},
197206 .snapshot_ignore_dirs = &.{},
198207 .snapshot_uses_gitignore = true,
199208 .history_size = 100,
src/http.zig+52−0
@@ -75,6 +75,58 @@ pub fn get(
7575 return reader.allocRemaining(a, .limited(1 << 22)) catch return error.ReadFailed;
7676 }
7777
78+pub const Response = struct {
79+ status: u16,
80+ body: []u8,
81+};
82+
83+/// A single request whose whole body is buffered, for JSON request/response
84+/// exchanges such as MCP. The body may be JSON or an SSE stream; the caller
85+/// sniffs it. A non-2xx status is not an error here: the body often carries the
86+/// protocol-level reason, and the caller can read `status` itself.
87+pub fn post(
88+ a: std.mem.Allocator,
89+ url: []const u8,
90+ headers: []const Header,
91+ body: []const u8,
92+ cancel: *const std.atomic.Value(bool),
93+) HttpError!Response {
94+ if (cancel.load(.acquire)) return error.Aborted;
95+ const uri = std.Uri.parse(url) catch return error.RequestFailed;
96+ var client: std.http.Client = .{ .allocator = a, .io = platform.io };
97+ defer client.deinit();
98+
99+ var hdrs: std.ArrayList(std.http.Header) = .empty;
100+ defer hdrs.deinit(a);
101+ for (headers) |h| hdrs.append(a, .{ .name = h.name, .value = h.value }) catch return error.OutOfMemory;
102+
103+ var req = client.request(.POST, uri, .{
104+ .redirect_behavior = .unhandled,
105+ .extra_headers = hdrs.items,
106+ .headers = .{ .user_agent = .{ .override = user_agent } },
107+ }) catch return error.RequestFailed;
108+ defer req.deinit();
109+
110+ req.transfer_encoding = .{ .content_length = body.len };
111+ var bw = req.sendBodyUnflushed(&.{}) catch return error.RequestFailed;
112+ bw.writer.writeAll(body) catch return error.RequestFailed;
113+ bw.end() catch return error.RequestFailed;
114+ req.connection.?.flush() catch return error.RequestFailed;
115+
116+ var response = req.receiveHead(&.{}) catch return error.RequestFailed;
117+ const status = @intFromEnum(response.head.status);
118+
119+ var transfer: [16 * 1024]u8 = undefined;
120+ var decompress: std.http.Decompress = undefined;
121+ var decompress_buf: [std.compress.flate.max_window_len]u8 = undefined;
122+ const reader = response.readerDecompressing(&transfer, &decompress, &decompress_buf);
123+
124+ return .{
125+ .status = status,
126+ .body = reader.allocRemaining(a, .limited(1 << 22)) catch return error.ReadFailed,
127+ };
128+}
129+
78130 pub fn postSse(
79131 a: std.mem.Allocator,
80132 url: []const u8,
src/main.zig+31−0
@@ -6,6 +6,7 @@ const models = @import("models.zig");
66 const session = @import("session.zig");
77 const agent = @import("agent.zig");
88 const tools = @import("tools.zig");
9+const mcp = @import("mcp.zig");
910 const tui = @import("tui/tui.zig");
1011 const term = @import("tui/term.zig");
1112 const headless = @import("headless.zig");
@@ -62,9 +63,39 @@ pub fn main(init: std.process.Init) void {
6263 std.process.exit(code);
6364 }
6465
66+/// Splits a leading `mcp` subcommand from any configuration flags that precede
67+/// it, so `mini -c <file> mcp …` behaves like every other mode. Returns null
68+/// when `mcp` is not the subcommand.
69+fn mcpArgs(a: std.mem.Allocator) !?struct { config: ?[]const u8, args: []const []const u8 } {
70+ var it = std.process.Args.Iterator.init(platform.args);
71+ _ = it.next();
72+ var config_path: ?[]const u8 = null;
73+ while (it.next()) |arg| {
74+ if (std.mem.startsWith(u8, arg, "--config=")) {
75+ config_path = try a.dupe(u8, arg["--config=".len..]);
76+ continue;
77+ }
78+ if (std.mem.eql(u8, arg, "-c") or std.mem.eql(u8, arg, "--config")) {
79+ config_path = try a.dupe(u8, it.next() orelse return null);
80+ continue;
81+ }
82+ if (!std.mem.eql(u8, arg, "mcp")) return null;
83+
84+ var rest: std.ArrayList([]const u8) = .empty;
85+ while (it.next()) |sub| try rest.append(a, sub);
86+ return .{ .config = config_path, .args = try rest.toOwnedSlice(a) };
87+ }
88+ return null;
89+}
90+
6591 fn run() !u8 {
6692 const a = platform.gpa;
6793
94+ if (try mcpArgs(a)) |mcp_call| {
95+ const cfg = config.load(a, mcp_call.config) catch return 1;
96+ return mcp.run(a, &cfg, mcp_call.args);
97+ }
98+
6899 const args = parseArgs(a) catch |e| {
69100 switch (e) {
70101 error.MissingPrompt => platform.printErr("a prompt is required\n", .{}),
src/mcp.zig+453−0
@@ -0,0 +1,453 @@
1+const std = @import("std");
2+const platform = @import("platform.zig");
3+const config = @import("config.zig");
4+const http = @import("http.zig");
5+const json = @import("json.zig");
6+
7+// Only the stateless MCP revision is supported: no handshake, no session,
8+// protocol metadata in `_meta` on every request. A server rejects whatever
9+// revision it does not speak and names the ones it does, so the first request
10+// probes with the newest revision and `negotiatedVersion` retries with the
11+// server's newest. No single revision is pinned.
12+const preferred_version = "2026-07-28";
13+const client_name = "mini-coding-agent";
14+const client_version = "0.1.0";
15+
16+/// The subcommand runs one request with no interactive cancellation.
17+var no_cancel = std.atomic.Value(bool).init(false);
18+
19+const Tool = struct {
20+ name: []const u8,
21+ path: []const u8,
22+ description: []const u8,
23+ schema: ?std.json.Value,
24+};
25+
26+pub fn usage() void {
27+ platform.printErr(
28+ \\usage: mini mcp <command>
29+ \\ search <query> discover tools across configured servers
30+ \\ describe <path> show the docs for one tool
31+ \\ invoke <path> <json> call a tool with JSON arguments
32+ \\
33+ , .{});
34+}
35+
36+pub fn run(a: std.mem.Allocator, cfg: *const config.Config, args: []const []const u8) u8 {
37+ var arena_state = std.heap.ArenaAllocator.init(a);
38+ defer arena_state.deinit();
39+ const al = arena_state.allocator();
40+
41+ if (cfg.mcp_servers.map.count() == 0) {
42+ platform.printErr("no MCP servers configured; add \"mcpServers\" to {s}\n", .{cfg.path});
43+ return 1;
44+ }
45+ if (args.len == 0) {
46+ usage();
47+ return 1;
48+ }
49+
50+ const cmd = args[0];
51+ if (std.mem.eql(u8, cmd, "search")) {
52+ return search(al, cfg, if (args.len > 1) args[1] else "");
53+ }
54+ if (std.mem.eql(u8, cmd, "describe")) {
55+ if (args.len < 2) {
56+ platform.printErr("usage: mini mcp describe <path>\n", .{});
57+ return 1;
58+ }
59+ return describe(al, cfg, args[1]);
60+ }
61+ if (std.mem.eql(u8, cmd, "invoke")) {
62+ if (args.len < 2) {
63+ platform.printErr("usage: mini mcp invoke <path> <json>\n", .{});
64+ return 1;
65+ }
66+ return invoke(al, cfg, args[1], if (args.len > 2) args[2] else "{}");
67+ }
68+
69+ platform.printErr("unknown mcp command: {s}\n", .{cmd});
70+ usage();
71+ return 1;
72+}
73+
74+fn search(al: std.mem.Allocator, cfg: *const config.Config, query: []const u8) u8 {
75+ var tools: std.ArrayList(Tool) = .empty;
76+ fetchTools(al, cfg, &tools) catch return 1;
77+
78+ const Ranked = struct { score: i32, tool: Tool };
79+ var ranked: std.ArrayList(Ranked) = .empty;
80+ for (tools.items) |t| {
81+ const s = score(t, query) orelse continue;
82+ ranked.append(al, .{ .score = s, .tool = t }) catch return 1;
83+ }
84+ std.mem.sort(Ranked, ranked.items, {}, struct {
85+ fn lessThan(_: void, x: Ranked, y: Ranked) bool {
86+ return x.score > y.score;
87+ }
88+ }.lessThan);
89+
90+ const Match = struct { path: []const u8, description: []const u8 };
91+ var matches: std.ArrayList(Match) = .empty;
92+ for (ranked.items) |r| matches.append(al, .{
93+ .path = r.tool.path,
94+ .description = r.tool.description,
95+ }) catch return 1;
96+
97+ const body = std.json.Stringify.valueAlloc(al, struct { results: []const Match }{
98+ .results = matches.items,
99+ }, .{}) catch return 1;
100+ platform.writeOut(body);
101+ platform.writeOut("\n");
102+ return 0;
103+}
104+
105+fn score(t: Tool, query: []const u8) ?i32 {
106+ if (query.len == 0) return 0;
107+ if (std.ascii.eqlIgnoreCase(t.name, query)) return 1000;
108+ if (std.ascii.eqlIgnoreCase(t.path, query)) return 900;
109+ if (std.ascii.startsWithIgnoreCase(t.path, query)) return 600;
110+ if (std.ascii.findIgnoreCase(t.path, query) != null) return 300;
111+ if (std.ascii.findIgnoreCase(t.description, query) != null) return 100;
112+ return null;
113+}
114+
115+fn describe(al: std.mem.Allocator, cfg: *const config.Config, path: []const u8) u8 {
116+ var tools: std.ArrayList(Tool) = .empty;
117+ fetchTools(al, cfg, &tools) catch return 1;
118+
119+ for (tools.items) |t| {
120+ if (!std.mem.eql(u8, t.path, path)) continue;
121+ var out: std.Io.Writer.Allocating = .init(al);
122+ out.writer.writeAll(t.path) catch return 1;
123+ if (t.description.len > 0) {
124+ out.writer.writeAll("\n") catch return 1;
125+ out.writer.writeAll(t.description) catch return 1;
126+ }
127+ out.writer.writeAll("\n\n") catch return 1;
128+ writeSignature(&out.writer, t.path, t.schema) catch return 1;
129+ out.writer.writeAll("\n") catch return 1;
130+ platform.writeOut(out.written());
131+ return 0;
132+ }
133+
134+ platform.printErr("mcp: no tool at path {s}\n", .{path});
135+ return 1;
136+}
137+
138+fn invoke(al: std.mem.Allocator, cfg: *const config.Config, path: []const u8, json_args: []const u8) u8 {
139+ const dot = std.mem.indexOfScalar(u8, path, '.') orelse {
140+ platform.printErr("mcp: tool path must be <server>.<tool>\n", .{});
141+ return 1;
142+ };
143+ const server = path[0..dot];
144+ const tool_name = path[dot + 1 ..];
145+ const sc = cfg.mcp_servers.map.get(server) orelse {
146+ platform.printErr("mcp: no server named {s}\n", .{server});
147+ return 1;
148+ };
149+ _ = std.json.parseFromSliceLeaky(std.json.Value, al, json_args, .{}) catch {
150+ platform.printErr("mcp: arguments must be valid JSON\n", .{});
151+ return 1;
152+ };
153+
154+ const result = callRpc(al, server, sc, "tools/call", tool_name, json_args) catch return 1;
155+ const rendered = renderResult(al, result) catch return 1;
156+ if (isError(result)) {
157+ platform.writeErr(rendered);
158+ return 1;
159+ }
160+ platform.writeOut(rendered);
161+ return 0;
162+}
163+
164+fn isError(result: std.json.Value) bool {
165+ const v = objField(result, "isError") orelse return false;
166+ return v == .bool and v.bool;
167+}
168+
169+fn renderResult(al: std.mem.Allocator, result: std.json.Value) ![]const u8 {
170+ var out: std.Io.Writer.Allocating = .init(al);
171+ if (structuredContent(result)) |structured| {
172+ try std.json.Stringify.value(structured, .{ .whitespace = .indent_2 }, &out.writer);
173+ } else if (try textContent(al, result)) |text| {
174+ try out.writer.writeAll(text);
175+ } else {
176+ try std.json.Stringify.value(result, .{ .whitespace = .indent_2 }, &out.writer);
177+ }
178+ const written = out.written();
179+ if (written.len == 0 or written[written.len - 1] != '\n') try out.writer.writeByte('\n');
180+ return out.written();
181+}
182+
183+/// The tool's `structuredContent`, or null when absent. Rendering prefers it so
184+/// a result that carries both it and text is not printed twice.
185+fn structuredContent(result: std.json.Value) ?std.json.Value {
186+ const v = objField(result, "structuredContent") orelse return null;
187+ return if (v == .null) null else v;
188+}
189+
190+/// Concatenates the `content[].text` entries, or null when the result carries
191+/// none. A tool that returns neither text nor structured content gets its whole
192+/// result printed.
193+fn textContent(al: std.mem.Allocator, result: std.json.Value) !?[]const u8 {
194+ const content = objField(result, "content") orelse return null;
195+ if (content != .array) return null;
196+
197+ var out: std.Io.Writer.Allocating = .init(al);
198+ var wrote = false;
199+ for (content.array.items) |item| {
200+ const kind = objField(item, "type") orelse continue;
201+ if (kind != .string or !std.mem.eql(u8, kind.string, "text")) continue;
202+ const text = objField(item, "text") orelse continue;
203+ if (text != .string) continue;
204+ try out.writer.writeAll(text.string);
205+ wrote = true;
206+ }
207+ if (!wrote) return null;
208+ return out.written();
209+}
210+
211+fn fetchTools(al: std.mem.Allocator, cfg: *const config.Config, out: *std.ArrayList(Tool)) !void {
212+ var it = cfg.mcp_servers.map.iterator();
213+ while (it.next()) |entry| {
214+ const server = entry.key_ptr.*;
215+ const sc = entry.value_ptr.*;
216+ const result = callRpc(al, server, sc, "tools/list", null, null) catch continue;
217+ const tools = objField(result, "tools") orelse continue;
218+ if (tools != .array) continue;
219+ for (tools.array.items) |t| {
220+ const name = objField(t, "name") orelse continue;
221+ if (name != .string) continue;
222+ const description = objField(t, "description") orelse std.json.Value{ .string = "" };
223+ try out.append(al, .{
224+ .name = name.string,
225+ .path = try std.fmt.allocPrint(al, "{s}.{s}", .{ server, name.string }),
226+ .description = if (description == .string) description.string else "",
227+ .schema = objField(t, "inputSchema"),
228+ });
229+ }
230+ }
231+}
232+
233+/// One JSON-RPC request, retried once at the revision the server advertises
234+/// when it rejects ours. Prints any transport or protocol error with the server
235+/// name and returns an error, so callers only decide whether to stop.
236+fn callRpc(
237+ al: std.mem.Allocator,
238+ server: []const u8,
239+ sc: config.McpServer,
240+ method: []const u8,
241+ name: ?[]const u8,
242+ arguments_json: ?[]const u8,
243+) !std.json.Value {
244+ var version: []const u8 = preferred_version;
245+ var retried = false;
246+ while (true) {
247+ const response = request(al, server, sc, version, method, name, arguments_json) catch return error.McpRequest;
248+ const root = parseResponse(al, response.body) catch {
249+ platform.printErr("mcp {s}: malformed response\n", .{server});
250+ return error.McpRequest;
251+ };
252+ if (root != .object) {
253+ platform.printErr("mcp {s}: malformed response\n", .{server});
254+ return error.McpRequest;
255+ }
256+ if (root.object.get("error")) |err| {
257+ if (!retried) {
258+ if (negotiatedVersion(err)) |v| {
259+ retried = true;
260+ version = v;
261+ continue;
262+ }
263+ }
264+ platform.printErr("mcp {s}: {s}\n", .{ server, errorText(err) });
265+ return error.McpRequest;
266+ }
267+ return root.object.get("result") orelse {
268+ platform.printErr("mcp {s}: unexpected response (HTTP {d})\n", .{ server, response.status });
269+ return error.McpRequest;
270+ };
271+ }
272+}
273+
274+/// The server's answer to a revision it does not speak: `data.supported` when
275+/// structured, or the list named in the message text otherwise. Returns the
276+/// newest revision the server accepts, or null when the error is unrelated.
277+fn negotiatedVersion(err: std.json.Value) ?[]const u8 {
278+ if (objField(err, "data")) |data| {
279+ if (objField(data, "supported")) |supported| {
280+ if (supported == .array) for (supported.array.items) |item| {
281+ if (item == .string) return item.string;
282+ };
283+ }
284+ }
285+ const message = errorText(err);
286+ const marker = "supported versions:";
287+ const at = std.mem.indexOf(u8, message, marker) orelse return null;
288+ const rest = std.mem.trim(u8, message[at + marker.len ..], " \t");
289+ var end = rest.len;
290+ if (std.mem.indexOfScalar(u8, rest, ',')) |c| end = c else if (std.mem.indexOfScalar(u8, rest, ')')) |p| end = p;
291+ const first = std.mem.trim(u8, rest[0..end], " \t");
292+ return if (first.len > 0) first else null;
293+}
294+
295+fn request(
296+ al: std.mem.Allocator,
297+ server: []const u8,
298+ sc: config.McpServer,
299+ version: []const u8,
300+ method: []const u8,
301+ name: ?[]const u8,
302+ arguments_json: ?[]const u8,
303+) !http.Response {
304+ const body = try buildBody(al, version, method, name, arguments_json);
305+
306+ var headers: std.ArrayList(http.Header) = .empty;
307+ try headers.append(al, .{ .name = "Content-Type", .value = "application/json" });
308+ try headers.append(al, .{ .name = "Accept", .value = "application/json, text/event-stream" });
309+ try headers.append(al, .{ .name = "MCP-Protocol-Version", .value = version });
310+ try headers.append(al, .{ .name = "Mcp-Method", .value = method });
311+ if (name) |n| try headers.append(al, .{ .name = "Mcp-Name", .value = n });
312+ if (sc.headers) |hs| {
313+ var hit = hs.map.iterator();
314+ while (hit.next()) |h| try headers.append(al, .{ .name = h.key_ptr.*, .value = h.value_ptr.* });
315+ }
316+
317+ return http.post(al, sc.url, headers.items, body, &no_cancel) catch |e| {
318+ platform.printErr("mcp {s}: {s}\n", .{ server, @errorName(e) });
319+ return error.McpRequest;
320+ };
321+}
322+
323+fn buildBody(al: std.mem.Allocator, version: []const u8, method: []const u8, name: ?[]const u8, arguments_json: ?[]const u8) ![]const u8 {
324+ return std.json.Stringify.valueAlloc(al, Request{
325+ .method = method,
326+ .params = .{
327+ .name = name,
328+ .arguments = if (arguments_json) |args| .{ .bytes = args } else null,
329+ ._meta = .{ .version = version },
330+ },
331+ }, .{ .emit_null_optional_fields = false });
332+}
333+
334+const meta_prefix = "io.modelcontextprotocol/";
335+
336+/// `_meta` keys carry a reverse-DNS prefix that Zig identifiers cannot hold, so
337+/// the object is written field by field.
338+const Meta = struct {
339+ version: []const u8,
340+
341+ pub fn jsonStringify(self: Meta, jws: anytype) !void {
342+ try jws.beginObject();
343+ try jws.objectField(meta_prefix ++ "protocolVersion");
344+ try jws.write(self.version);
345+ try jws.objectField(meta_prefix ++ "clientInfo");
346+ try jws.write(ClientInfo{});
347+ try jws.objectField(meta_prefix ++ "clientCapabilities");
348+ try jws.write(Capabilities{});
349+ try jws.endObject();
350+ }
351+};
352+
353+const ClientInfo = struct {
354+ name: []const u8 = client_name,
355+ version: []const u8 = client_version,
356+};
357+
358+const Capabilities = struct {};
359+
360+const Request = struct {
361+ jsonrpc: []const u8 = "2.0",
362+ id: u32 = 1,
363+ method: []const u8,
364+ params: Params,
365+};
366+
367+const Params = struct {
368+ name: ?[]const u8 = null,
369+ arguments: ?json.Raw = null,
370+ _meta: Meta,
371+};
372+
373+/// Responses are either a JSON object or a request-scoped SSE stream whose
374+/// last `data:` payload carries the reply.
375+fn parseResponse(al: std.mem.Allocator, body: []const u8) !std.json.Value {
376+ const trimmed = std.mem.trim(u8, body, " \t\r\n");
377+ if (trimmed.len > 0 and trimmed[0] == '{') {
378+ return std.json.parseFromSliceLeaky(std.json.Value, al, trimmed, .{});
379+ }
380+ var last: ?std.json.Value = null;
381+ var lines = std.mem.splitScalar(u8, body, '\n');
382+ while (lines.next()) |raw| {
383+ const line = std.mem.trim(u8, raw, " \t\r");
384+ if (!std.mem.startsWith(u8, line, "data:")) continue;
385+ const payload = std.mem.trim(u8, line["data:".len..], " \t");
386+ if (payload.len == 0) continue;
387+ last = std.json.parseFromSliceLeaky(std.json.Value, al, payload, .{}) catch continue;
388+ }
389+ return last orelse error.MalformedResponse;
390+}
391+
392+fn objField(v: std.json.Value, key: []const u8) ?std.json.Value {
393+ if (v != .object) return null;
394+ return v.object.get(key);
395+}
396+
397+fn errorText(err: std.json.Value) []const u8 {
398+ const message = objField(err, "message") orelse return "request failed";
399+ return if (message == .string) message.string else "request failed";
400+}
401+
402+fn writeSignature(w: *std.Io.Writer, path: []const u8, schema: ?std.json.Value) !void {
403+ try w.print("{s}(args: ", .{path});
404+ if (schema) |s| {
405+ if (s == .object) try writeObjectType(w, s.object) else try w.writeAll("unknown");
406+ } else {
407+ try w.writeAll("unknown");
408+ }
409+ try w.writeAll("): Promise<unknown>");
410+}
411+
412+fn writeObjectType(w: *std.Io.Writer, obj: std.json.ObjectMap) std.Io.Writer.Error!void {
413+ const props = obj.get("properties") orelse return w.writeAll("Record<string, unknown>");
414+ if (props != .object or props.object.count() == 0) return w.writeAll("Record<string, unknown>");
415+
416+ const required = obj.get("required");
417+ try w.writeAll("{ ");
418+ var it = props.object.iterator();
419+ var first = true;
420+ while (it.next()) |entry| {
421+ if (!first) try w.writeAll("; ");
422+ first = false;
423+ try w.writeAll(entry.key_ptr.*);
424+ if (!isRequired(required, entry.key_ptr.*)) try w.writeByte('?');
425+ try w.writeAll(": ");
426+ try writeType(w, entry.value_ptr.*);
427+ }
428+ try w.writeAll(" }");
429+}
430+
431+fn writeType(w: *std.Io.Writer, v: std.json.Value) std.Io.Writer.Error!void {
432+ if (v != .object) return w.writeAll("unknown");
433+ const obj = v.object;
434+ const kind = obj.get("type") orelse return w.writeAll("unknown");
435+ if (kind != .string) return w.writeAll("unknown");
436+ if (std.mem.eql(u8, kind.string, "string")) return w.writeAll("string");
437+ if (std.mem.eql(u8, kind.string, "integer")) return w.writeAll("number");
438+ if (std.mem.eql(u8, kind.string, "number")) return w.writeAll("number");
439+ if (std.mem.eql(u8, kind.string, "boolean")) return w.writeAll("boolean");
440+ if (std.mem.eql(u8, kind.string, "array")) return w.writeAll("unknown[]");
441+ if (std.mem.eql(u8, kind.string, "object")) return writeObjectType(w, obj);
442+ return w.writeAll("unknown");
443+}
444+
445+fn isRequired(v: ?std.json.Value, key: []const u8) bool {
446+ const required = v orelse return false;
447+ if (required != .array) return false;
448+ for (required.array.items) |item| {
449+ if (item != .string) continue;
450+ if (std.mem.eql(u8, item.string, key)) return true;
451+ }
452+ return false;
453+}
src/prompt.zig+18−0
@@ -107,6 +107,24 @@ pub fn buildSystemPrompt(a: std.mem.Allocator, cfg: *const config.Config) !Built
107107 }
108108 }
109109
110+ if (cfg.mcp_servers.map.count() > 0) {
111+ var out: std.ArrayList(u8) = .empty;
112+ try out.appendSlice(a, "## MCP\n\nConfigured servers: ");
113+ var it = cfg.mcp_servers.map.iterator();
114+ var first = true;
115+ while (it.next()) |entry| {
116+ if (!first) try out.appendSlice(a, ", ");
117+ first = false;
118+ try out.appendSlice(a, entry.key_ptr.*);
119+ }
120+ try out.appendSlice(
121+ a,
122+ "\n\nReach their tools with the bash tool: `mini mcp search <query>`, " ++
123+ "`mini mcp describe <server>.<tool>`, `mini mcp invoke <server>.<tool> <json>`.",
124+ );
125+ try sections.append(a, out.items);
126+ }
127+
110128 var joined: std.ArrayList(u8) = .empty;
111129 for (sections.items, 0..) |section, i| {
112130 if (i > 0) try joined.appendSlice(a, "\n\n");