@@ -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+}