@@ -1,456 +0,0 @@
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- if (args.len < 2 or args[1].len == 0) {
53- platform.printErr("usage: mini mcp search <query>\n", .{});
54- return 1;
55- }
56- return search(al, cfg, args[1]);
57- }
58- if (std.mem.eql(u8, cmd, "describe")) {
59- if (args.len < 2) {
60- platform.printErr("usage: mini mcp describe <path>\n", .{});
61- return 1;
62- }
63- return describe(al, cfg, args[1]);
64- }
65- if (std.mem.eql(u8, cmd, "invoke")) {
66- if (args.len < 2) {
67- platform.printErr("usage: mini mcp invoke <path> <json>\n", .{});
68- return 1;
69- }
70- return invoke(al, cfg, args[1], if (args.len > 2) args[2] else "{}");
71- }
72-
73- platform.printErr("unknown mcp command: {s}\n", .{cmd});
74- usage();
75- return 1;
76-}
77-
78-fn search(al: std.mem.Allocator, cfg: *const config.Config, query: []const u8) u8 {
79- var tools: std.ArrayList(Tool) = .empty;
80- fetchTools(al, cfg, &tools) catch return 1;
81-
82- const Ranked = struct { score: i32, tool: Tool };
83- var ranked: std.ArrayList(Ranked) = .empty;
84- for (tools.items) |t| {
85- const s = score(t, query) orelse continue;
86- ranked.append(al, .{ .score = s, .tool = t }) catch return 1;
87- }
88- std.mem.sort(Ranked, ranked.items, {}, struct {
89- fn lessThan(_: void, x: Ranked, y: Ranked) bool {
90- return x.score > y.score;
91- }
92- }.lessThan);
93-
94- const Match = struct { path: []const u8, description: []const u8 };
95- var matches: std.ArrayList(Match) = .empty;
96- for (ranked.items) |r| matches.append(al, .{
97- .path = r.tool.path,
98- .description = r.tool.description,
99- }) catch return 1;
100-
101- const body = std.json.Stringify.valueAlloc(al, struct { results: []const Match }{
102- .results = matches.items,
103- }, .{}) catch return 1;
104- platform.writeOut(body);
105- platform.writeOut("\n");
106- return 0;
107-}
108-
109-fn score(t: Tool, query: []const u8) ?i32 {
110- if (std.ascii.eqlIgnoreCase(t.name, query)) return 1000;
111- if (std.ascii.eqlIgnoreCase(t.path, query)) return 900;
112- if (std.ascii.startsWithIgnoreCase(t.path, query)) return 600;
113- if (std.ascii.findIgnoreCase(t.path, query) != null) return 300;
114- if (std.ascii.findIgnoreCase(t.description, query) != null) return 100;
115- return null;
116-}
117-
118-fn describe(al: std.mem.Allocator, cfg: *const config.Config, path: []const u8) u8 {
119- var tools: std.ArrayList(Tool) = .empty;
120- fetchTools(al, cfg, &tools) catch return 1;
121-
122- for (tools.items) |t| {
123- if (!std.mem.eql(u8, t.path, path)) continue;
124- var out: std.Io.Writer.Allocating = .init(al);
125- out.writer.writeAll(t.path) catch return 1;
126- if (t.description.len > 0) {
127- out.writer.writeAll("\n") catch return 1;
128- out.writer.writeAll(t.description) catch return 1;
129- }
130- out.writer.writeAll("\n\n") catch return 1;
131- writeSignature(&out.writer, t.path, t.schema) catch return 1;
132- out.writer.writeAll("\n") catch return 1;
133- platform.writeOut(out.written());
134- return 0;
135- }
136-
137- platform.printErr("mcp: no tool at path {s}\n", .{path});
138- return 1;
139-}
140-
141-fn invoke(al: std.mem.Allocator, cfg: *const config.Config, path: []const u8, json_args: []const u8) u8 {
142- const dot = std.mem.indexOfScalar(u8, path, '.') orelse {
143- platform.printErr("mcp: tool path must be <server>.<tool>\n", .{});
144- return 1;
145- };
146- const server = path[0..dot];
147- const tool_name = path[dot + 1 ..];
148- const sc = cfg.mcp_servers.map.get(server) orelse {
149- platform.printErr("mcp: no server named {s}\n", .{server});
150- return 1;
151- };
152- _ = std.json.parseFromSliceLeaky(std.json.Value, al, json_args, .{}) catch {
153- platform.printErr("mcp: arguments must be valid JSON\n", .{});
154- return 1;
155- };
156-
157- const result = callRpc(al, server, sc, "tools/call", tool_name, json_args) catch return 1;
158- const rendered = renderResult(al, result) catch return 1;
159- if (isError(result)) {
160- platform.writeErr(rendered);
161- return 1;
162- }
163- platform.writeOut(rendered);
164- return 0;
165-}
166-
167-fn isError(result: std.json.Value) bool {
168- const v = objField(result, "isError") orelse return false;
169- return v == .bool and v.bool;
170-}
171-
172-fn renderResult(al: std.mem.Allocator, result: std.json.Value) ![]const u8 {
173- var out: std.Io.Writer.Allocating = .init(al);
174- if (structuredContent(result)) |structured| {
175- try std.json.Stringify.value(structured, .{ .whitespace = .indent_2 }, &out.writer);
176- } else if (try textContent(al, result)) |text| {
177- try out.writer.writeAll(text);
178- } else {
179- try std.json.Stringify.value(result, .{ .whitespace = .indent_2 }, &out.writer);
180- }
181- const written = out.written();
182- if (written.len == 0 or written[written.len - 1] != '\n') try out.writer.writeByte('\n');
183- return out.written();
184-}
185-
186-/// The tool's `structuredContent`, or null when absent. Rendering prefers it so
187-/// a result that carries both it and text is not printed twice.
188-fn structuredContent(result: std.json.Value) ?std.json.Value {
189- const v = objField(result, "structuredContent") orelse return null;
190- return if (v == .null) null else v;
191-}
192-
193-/// Concatenates the `content[].text` entries, or null when the result carries
194-/// none. A tool that returns neither text nor structured content gets its whole
195-/// result printed.
196-fn textContent(al: std.mem.Allocator, result: std.json.Value) !?[]const u8 {
197- const content = objField(result, "content") orelse return null;
198- if (content != .array) return null;
199-
200- var out: std.Io.Writer.Allocating = .init(al);
201- var wrote = false;
202- for (content.array.items) |item| {
203- const kind = objField(item, "type") orelse continue;
204- if (kind != .string or !std.mem.eql(u8, kind.string, "text")) continue;
205- const text = objField(item, "text") orelse continue;
206- if (text != .string) continue;
207- try out.writer.writeAll(text.string);
208- wrote = true;
209- }
210- if (!wrote) return null;
211- return out.written();
212-}
213-
214-fn fetchTools(al: std.mem.Allocator, cfg: *const config.Config, out: *std.ArrayList(Tool)) !void {
215- var it = cfg.mcp_servers.map.iterator();
216- while (it.next()) |entry| {
217- const server = entry.key_ptr.*;
218- const sc = entry.value_ptr.*;
219- const result = callRpc(al, server, sc, "tools/list", null, null) catch continue;
220- const tools = objField(result, "tools") orelse continue;
221- if (tools != .array) continue;
222- for (tools.array.items) |t| {
223- const name = objField(t, "name") orelse continue;
224- if (name != .string) continue;
225- const description = objField(t, "description") orelse std.json.Value{ .string = "" };
226- try out.append(al, .{
227- .name = name.string,
228- .path = try std.fmt.allocPrint(al, "{s}.{s}", .{ server, name.string }),
229- .description = if (description == .string) description.string else "",
230- .schema = objField(t, "inputSchema"),
231- });
232- }
233- }
234-}
235-
236-/// One JSON-RPC request, retried once at the revision the server advertises
237-/// when it rejects ours. Prints any transport or protocol error with the server
238-/// name and returns an error, so callers only decide whether to stop.
239-fn callRpc(
240- al: std.mem.Allocator,
241- server: []const u8,
242- sc: config.McpServer,
243- method: []const u8,
244- name: ?[]const u8,
245- arguments_json: ?[]const u8,
246-) !std.json.Value {
247- var version: []const u8 = preferred_version;
248- var retried = false;
249- while (true) {
250- const response = request(al, server, sc, version, method, name, arguments_json) catch return error.McpRequest;
251- const root = parseResponse(al, response.body) catch {
252- platform.printErr("mcp {s}: malformed response\n", .{server});
253- return error.McpRequest;
254- };
255- if (root != .object) {
256- platform.printErr("mcp {s}: malformed response\n", .{server});
257- return error.McpRequest;
258- }
259- if (root.object.get("error")) |err| {
260- if (!retried) {
261- if (negotiatedVersion(err)) |v| {
262- retried = true;
263- version = v;
264- continue;
265- }
266- }
267- platform.printErr("mcp {s}: {s}\n", .{ server, errorText(err) });
268- return error.McpRequest;
269- }
270- return root.object.get("result") orelse {
271- platform.printErr("mcp {s}: unexpected response (HTTP {d})\n", .{ server, response.status });
272- return error.McpRequest;
273- };
274- }
275-}
276-
277-/// The server's answer to a revision it does not speak: `data.supported` when
278-/// structured, or the list named in the message text otherwise. Returns the
279-/// newest revision the server accepts, or null when the error is unrelated.
280-fn negotiatedVersion(err: std.json.Value) ?[]const u8 {
281- if (objField(err, "data")) |data| {
282- if (objField(data, "supported")) |supported| {
283- if (supported == .array) for (supported.array.items) |item| {
284- if (item == .string) return item.string;
285- };
286- }
287- }
288- const message = errorText(err);
289- const marker = "supported versions:";
290- const at = std.mem.indexOf(u8, message, marker) orelse return null;
291- const rest = std.mem.trim(u8, message[at + marker.len ..], " \t");
292- var end = rest.len;
293- if (std.mem.indexOfScalar(u8, rest, ',')) |c| end = c else if (std.mem.indexOfScalar(u8, rest, ')')) |p| end = p;
294- const first = std.mem.trim(u8, rest[0..end], " \t");
295- return if (first.len > 0) first else null;
296-}
297-
298-fn request(
299- al: std.mem.Allocator,
300- server: []const u8,
301- sc: config.McpServer,
302- version: []const u8,
303- method: []const u8,
304- name: ?[]const u8,
305- arguments_json: ?[]const u8,
306-) !http.Response {
307- const body = try buildBody(al, version, method, name, arguments_json);
308-
309- var headers: std.ArrayList(http.Header) = .empty;
310- try headers.append(al, .{ .name = "Content-Type", .value = "application/json" });
311- try headers.append(al, .{ .name = "Accept", .value = "application/json, text/event-stream" });
312- try headers.append(al, .{ .name = "MCP-Protocol-Version", .value = version });
313- try headers.append(al, .{ .name = "Mcp-Method", .value = method });
314- if (name) |n| try headers.append(al, .{ .name = "Mcp-Name", .value = n });
315- if (sc.headers) |hs| {
316- var hit = hs.map.iterator();
317- while (hit.next()) |h| try headers.append(al, .{ .name = h.key_ptr.*, .value = h.value_ptr.* });
318- }
319-
320- return http.post(al, sc.url, headers.items, body, &no_cancel) catch |e| {
321- platform.printErr("mcp {s}: {s}\n", .{ server, @errorName(e) });
322- return error.McpRequest;
323- };
324-}
325-
326-fn buildBody(al: std.mem.Allocator, version: []const u8, method: []const u8, name: ?[]const u8, arguments_json: ?[]const u8) ![]const u8 {
327- return std.json.Stringify.valueAlloc(al, Request{
328- .method = method,
329- .params = .{
330- .name = name,
331- .arguments = if (arguments_json) |args| .{ .bytes = args } else null,
332- ._meta = .{ .version = version },
333- },
334- }, .{ .emit_null_optional_fields = false });
335-}
336-
337-const meta_prefix = "io.modelcontextprotocol/";
338-
339-/// `_meta` keys carry a reverse-DNS prefix that Zig identifiers cannot hold, so
340-/// the object is written field by field.
341-const Meta = struct {
342- version: []const u8,
343-
344- pub fn jsonStringify(self: Meta, jws: anytype) !void {
345- try jws.beginObject();
346- try jws.objectField(meta_prefix ++ "protocolVersion");
347- try jws.write(self.version);
348- try jws.objectField(meta_prefix ++ "clientInfo");
349- try jws.write(ClientInfo{});
350- try jws.objectField(meta_prefix ++ "clientCapabilities");
351- try jws.write(Capabilities{});
352- try jws.endObject();
353- }
354-};
355-
356-const ClientInfo = struct {
357- name: []const u8 = client_name,
358- version: []const u8 = client_version,
359-};
360-
361-const Capabilities = struct {};
362-
363-const Request = struct {
364- jsonrpc: []const u8 = "2.0",
365- id: u32 = 1,
366- method: []const u8,
367- params: Params,
368-};
369-
370-const Params = struct {
371- name: ?[]const u8 = null,
372- arguments: ?json.Raw = null,
373- _meta: Meta,
374-};
375-
376-/// Responses are either a JSON object or a request-scoped SSE stream whose
377-/// last `data:` payload carries the reply.
378-fn parseResponse(al: std.mem.Allocator, body: []const u8) !std.json.Value {
379- const trimmed = std.mem.trim(u8, body, " \t\r\n");
380- if (trimmed.len > 0 and trimmed[0] == '{') {
381- return std.json.parseFromSliceLeaky(std.json.Value, al, trimmed, .{});
382- }
383- var last: ?std.json.Value = null;
384- var lines = std.mem.splitScalar(u8, body, '\n');
385- while (lines.next()) |raw| {
386- const line = std.mem.trim(u8, raw, " \t\r");
387- if (!std.mem.startsWith(u8, line, "data:")) continue;
388- const payload = std.mem.trim(u8, line["data:".len..], " \t");
389- if (payload.len == 0) continue;
390- last = std.json.parseFromSliceLeaky(std.json.Value, al, payload, .{}) catch continue;
391- }
392- return last orelse error.MalformedResponse;
393-}
394-
395-fn objField(v: std.json.Value, key: []const u8) ?std.json.Value {
396- if (v != .object) return null;
397- return v.object.get(key);
398-}
399-
400-fn errorText(err: std.json.Value) []const u8 {
401- const message = objField(err, "message") orelse return "request failed";
402- return if (message == .string) message.string else "request failed";
403-}
404-
405-fn writeSignature(w: *std.Io.Writer, path: []const u8, schema: ?std.json.Value) !void {
406- try w.print("{s}(args: ", .{path});
407- if (schema) |s| {
408- if (s == .object) try writeObjectType(w, s.object) else try w.writeAll("unknown");
409- } else {
410- try w.writeAll("unknown");
411- }
412- try w.writeAll("): Promise<unknown>");
413-}
414-
415-fn writeObjectType(w: *std.Io.Writer, obj: std.json.ObjectMap) std.Io.Writer.Error!void {
416- const props = obj.get("properties") orelse return w.writeAll("Record<string, unknown>");
417- if (props != .object or props.object.count() == 0) return w.writeAll("Record<string, unknown>");
418-
419- const required = obj.get("required");
420- try w.writeAll("{ ");
421- var it = props.object.iterator();
422- var first = true;
423- while (it.next()) |entry| {
424- if (!first) try w.writeAll("; ");
425- first = false;
426- try w.writeAll(entry.key_ptr.*);
427- if (!isRequired(required, entry.key_ptr.*)) try w.writeByte('?');
428- try w.writeAll(": ");
429- try writeType(w, entry.value_ptr.*);
430- }
431- try w.writeAll(" }");
432-}
433-
434-fn writeType(w: *std.Io.Writer, v: std.json.Value) std.Io.Writer.Error!void {
435- if (v != .object) return w.writeAll("unknown");
436- const obj = v.object;
437- const kind = obj.get("type") orelse return w.writeAll("unknown");
438- if (kind != .string) return w.writeAll("unknown");
439- if (std.mem.eql(u8, kind.string, "string")) return w.writeAll("string");
440- if (std.mem.eql(u8, kind.string, "integer")) return w.writeAll("number");
441- if (std.mem.eql(u8, kind.string, "number")) return w.writeAll("number");
442- if (std.mem.eql(u8, kind.string, "boolean")) return w.writeAll("boolean");
443- if (std.mem.eql(u8, kind.string, "array")) return w.writeAll("unknown[]");
444- if (std.mem.eql(u8, kind.string, "object")) return writeObjectType(w, obj);
445- return w.writeAll("unknown");
446-}
447-
448-fn isRequired(v: ?std.json.Value, key: []const u8) bool {
449- const required = v orelse return false;
450- if (required != .array) return false;
451- for (required.array.items) |item| {
452- if (item != .string) continue;
453- if (std.mem.eql(u8, item.string, key)) return true;
454- }
455- return false;
456-}