xonecas.io
79113
Ma

mini-coding-agent / commit 57c0485

feat: drop siwc and mcp (unused)

xonecas2026-10-25 57c048580a153ae64ccf03ea788531205a1838bd parent 95dbd0a

10 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

README.md+4−44
@@ -17,7 +17,6 @@ it with `python3 tools/gen_models_dev.py`.
1717 mini # interactive TUI
1818 mini -p '<prompt>' # one turn, print the reply, exit
1919 mini -c <file> # overlay a config file for this run
20- mini login # sign in with ChatGPT to use your plan
2120
2221 Arguments:
2322
@@ -67,23 +66,6 @@ error.
6766 | `edit` | replaces `oldText`, which must occur exactly once; an empty `oldText` creates a new file and fails if it exists; prints a unified diff |
6867 | `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 |
6968
70-## MCP
71-
72-`mini mcp` speaks the stateless MCP protocol to the servers in `mcpServers`.
73-It probes a revision and, when a server rejects it, retries with the newest
74-revision that server advertises, so no single revision is pinned. It lets the
75-`bash` tool reach MCP tools without any MCP tool description entering the
76-model's context: the model discovers and calls them with three commands,
77-composing them like any other shell command.
78-
79- mini mcp search <query> # ranked { path, description } matches
80- mini mcp describe <path> # the description and input signature
81- mini mcp invoke <path> <json> # call a tool with a JSON argument object
82-
83-A tool path is `<server>.<tool>`, for example
84-`mini mcp invoke context7.resolve-library-id '{"libraryName":"zig"}'`. Absent
85-`mcpServers`, every command reports that no servers are configured.
86-
8769 ## Configure
8870
8971 The config is one JSON object. It is read from
@@ -104,13 +86,6 @@ A full example:
10486 "discoverAgentFiles": true,
10587 "skillsDirs": ["/home/me/.agents/skills"],
10688 "tools": ["edit", "read", "bash"],
107- "mcpServers": {
108- "context7": { "url": "https://mcp.context7.com/mcp" },
109- "firecrawl": {
110- "url": "https://mcp.firecrawl.dev/v2/mcp",
111- "headers": { "Authorization": "Bearer fc-YOUR-API-KEY" }
112- }
113- },
11489 "snapshotIgnoreDirs": [".git"],
11590 "snapshotUsesGitignore": true,
11691 "historySize": 100,
@@ -144,7 +119,7 @@ Keys:
144119
145120 | Key | Default | Meaning |
146121 |---|---|---|
147-| `provider` | unset | provider id; built-ins are `opencode`, `opencode-go` and `openai` (after `mini login`), or a `customProviders` id |
122+| `provider` | unset | provider id; built-ins are `opencode` and `opencode-go`, or a `customProviders` id |
148123 | `model` | unset | model id |
149124 | `thinkingEffort` | unset | one of `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`; unset sends no reasoning parameter and clamps to what the model accepts |
150125 | `showImages` | `false` | display PNGs the `read` tool returns inline using the kitty graphics protocol; requires kitty 0.28+ |
@@ -154,7 +129,6 @@ Keys:
154129 | `skillsDirs` | `[]` | directories holding `<name>/SKILL.md` skills; each `SKILL.md` needs a `name` in its frontmatter (optional `description`) |
155130 | `tools` | `["edit", "read", "bash"]` | which tools the model sees |
156131 | `customProviders` | `[]` | in-tree provider definitions |
157-| `mcpServers` | `{}` | named MCP servers (`<name>: { url, headers }`) the `mini mcp` subcommand talks to |
158132 | `snapshotIgnoreDirs` | `[]` | directory names skipped when the `bash` tool snapshots the cwd for diffs |
159133 | `snapshotUsesGitignore` | `true` | also skip directories named in `.gitignore` when snapshotting |
160134 | `historySize` | `100` | past inputs kept in `<state dir>/mini-coding-agent/history` for `Ctrl+R` |
@@ -192,23 +166,9 @@ so one provider may mix APIs and base URLs:
192166 ## Environment
193167
194168 The built-in providers are named, keyed and described by the embedded models.dev
195-document; the agent itself only knows how each one authenticates. `opencode` and
196-`opencode-go` read the first present variable in their `env` list
197-(`OPENCODE_API_KEY`). A provider without a key is listed but fails at request
198-time.
199-
200-## Sign in with ChatGPT
201-
202-`mini login` runs the Sign in with ChatGPT flow and writes
203-`$XDG_CONFIG_HOME/mini-coding-agent/auth.json` (0600). It is the credential for
204-the `openai` provider, which then appears in `/provider` next to the keyed ones;
205-set `provider` to `openai` and pick any model from `/model`. The record is
206-refreshed under one lock per request, so a rotating refresh token is never
207-raced. A record that cannot be refreshed stops the turn with `sign-in expired;
208-run mini login` instead of sending an unauthenticated request.
209-
210-The account decides what is available: the model list comes from the provider
211-and models the account hides are never offered.
169+document. `opencode` and `opencode-go` read the first present variable in their
170+`env` list (`OPENCODE_API_KEY`). A provider without a key is listed but fails at
171+request time.
212172
213173 ## Sessions
214174
src/agent.zig+1−11
@@ -6,7 +6,6 @@ const platform = @import("platform.zig");
66 const tools = @import("tools.zig");
77 const session = @import("session.zig");
88 const config = @import("config.zig");
9-const auth = @import("auth.zig");
109 const time = @import("time.zig");
1110
1211 pub const Phase = enum { preparing, waiting_model, streaming, running_tool, snapshotting, pausing, idle };
@@ -171,15 +170,6 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(message_mod.Message), int
171170 };
172171
173172 if (cancelled(opts, listener)) return;
174- // An OAuth bearer expires, so it is renewed per step, not per session. A
175- // record that cannot be renewed stops the turn before it is persisted.
176- var wire_model = model.*;
177- if (wire_model.oauth) {
178- wire_model.api_key = auth.token(opts.cancel) orelse {
179- listener.emit(.{ .err = "sign-in expired; run `mini login`" });
180- return;
181- };
182- }
183173 listener.emit(.{ .phase = .{ .phase = .preparing } });
184174 opts.session.appendRequest(scratch, .{
185175 .provider = model.provider,
@@ -203,7 +193,7 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(message_mod.Message), int
203193 assistant.* = api.stream(.{
204194 .pers = opts.a,
205195 .scratch = scratch,
206- .model = &wire_model,
196+ .model = model,
207197 .system_prompt = opts.system_prompt,
208198 .tools_json = opts.tools_json,
209199 .messages = messages.items,
src/auth.zig+0−170
@@ -1,170 +0,0 @@
1-const std = @import("std");
2-const platform = @import("platform.zig");
3-const config = @import("config.zig");
4-const filesystem = @import("filesystem.zig");
5-const http = @import("http.zig");
6-const time = @import("time.zig");
7-
8-pub const token_url = "https://auth.openai.com/api/accounts/oauth/token";
9-pub const scope_url = "https://auth.openai.com/api/accounts/authorize";
10-pub const resource = "https://api.openai.com/v1";
11-pub const plan_scope = "chatgpt.tokens.use.direct";
12-
13-/// The credential `mini login` writes. Keys are camelCase to match the other
14-/// files in the config directory.
15-pub const Record = struct {
16- email: ?[]const u8 = null,
17- clientId: []const u8,
18- accessToken: []const u8,
19- refreshToken: ?[]const u8 = null,
20- idToken: ?[]const u8 = null,
21- expiresAt: i64 = 0,
22- scope: []const u8 = "",
23-};
24-
25-pub fn path(a: std.mem.Allocator) []const u8 {
26- return filesystem.join(a, &.{ config.configDir(a), "auth.json" }) catch "auth.json";
27-}
28-
29-pub fn load(a: std.mem.Allocator) ?Record {
30- const text = filesystem.readFileAlloc(a, path(a), 1 << 20) catch return null;
31- return std.json.parseFromSliceLeaky(Record, a, text, .{ .ignore_unknown_fields = true }) catch null;
32-}
33-
34-/// Written to a temporary file and renamed, so a crash mid-write cannot leave a
35-/// truncated credential with the refresh token already rotated.
36-pub fn save(a: std.mem.Allocator, record: Record) !void {
37- const json = try std.json.Stringify.valueAlloc(a, record, .{ .whitespace = .indent_2 });
38- const out = try std.fmt.allocPrint(a, "{s}\n", .{json});
39- const target = path(a);
40- const temp = try std.fmt.allocPrint(a, "{s}.tmp", .{target});
41- try filesystem.writeFile(temp, out);
42- try std.Io.Dir.cwd().rename(temp, std.Io.Dir.cwd(), target, platform.io);
43-}
44-
45-pub fn available(a: std.mem.Allocator) bool {
46- return filesystem.fileExists(path(a));
47-}
48-
49-/// True when the granted `scope` string contains `name`.
50-pub fn granted(scope: []const u8, name: []const u8) bool {
51- var it = std.mem.tokenizeAny(u8, scope, " +");
52- while (it.next()) |s| {
53- if (std.mem.eql(u8, s, name)) return true;
54- }
55- return false;
56-}
57-
58-pub const TokenResponse = struct {
59- access_token: ?[]const u8 = null,
60- refresh_token: ?[]const u8 = null,
61- id_token: ?[]const u8 = null,
62- expires_in: ?u64 = null,
63- scope: ?[]const u8 = null,
64-};
65-
66-var no_cancel = std.atomic.Value(bool).init(false);
67-
68-/// POSTs an already encoded grant to the token endpoint. Null on any failure;
69-/// the reason is printed once and never retried.
70-pub fn tokenRequest(a: std.mem.Allocator, body: []const u8, cancel: ?*const std.atomic.Value(bool)) ?TokenResponse {
71- const response = http.post(a, token_url, &.{
72- .{ .name = "Content-Type", .value = "application/x-www-form-urlencoded" },
73- .{ .name = "Accept", .value = "application/json" },
74- }, body, cancel orelse &no_cancel) catch {
75- platform.printErr("sign-in: token request failed\n", .{});
76- return null;
77- };
78- if (response.status != 200) {
79- platform.printErr("sign-in: token endpoint returned {d} {s}\n", .{ response.status, response.body });
80- return null;
81- }
82- return std.json.parseFromSliceLeaky(TokenResponse, a, response.body, .{ .ignore_unknown_fields = true }) catch null;
83-}
84-
85-/// RFC 3986 percent encoding. A space becomes `%20`, which is also valid in an
86-/// `application/x-www-form-urlencoded` body, so one encoder serves both.
87-pub fn appendEncoded(a: std.mem.Allocator, out: *std.ArrayList(u8), value: []const u8) !void {
88- const hex = "0123456789ABCDEF";
89- for (value) |c| {
90- switch (c) {
91- 'A'...'Z', 'a'...'z', '0'...'9', '-', '.', '_', '~' => try out.append(a, c),
92- else => {
93- try out.append(a, '%');
94- try out.append(a, hex[c >> 4]);
95- try out.append(a, hex[c & 0xf]);
96- },
97- }
98- }
99-}
100-
101-pub fn form(a: std.mem.Allocator, pairs: []const [2][]const u8) ![]u8 {
102- var out: std.ArrayList(u8) = .empty;
103- for (pairs, 0..) |pair, i| {
104- if (i > 0) try out.append(a, '&');
105- try appendEncoded(a, &out, pair[0]);
106- try out.append(a, '=');
107- try appendEncoded(a, &out, pair[1]);
108- }
109- return out.toOwnedSlice(a);
110-}
111-
112-/// One credential, one lock. Refreshes are serialized so two turns cannot race
113-/// the rotating refresh token.
114-pub const Session = struct {
115- mutex: std.Io.Mutex = .init,
116- record: Record,
117-
118- /// The record owns its strings for the life of the process, so a caller's
119- /// scratch allocator can be reset between requests without dangling it.
120- pub fn access(self: *Session, cancel: *const std.atomic.Value(bool)) ?[]const u8 {
121- const a = platform.gpa;
122- self.mutex.lockUncancelable(platform.io);
123- defer self.mutex.unlock(platform.io);
124- if (self.record.expiresAt - time.nowMs() > 60_000) return self.record.accessToken;
125- const next = self.renew(a, cancel) orelse return null;
126- save(a, next) catch platform.printErr("sign-in: could not persist the refreshed credential\n", .{});
127- self.record = next;
128- return self.record.accessToken;
129- }
130-
131- fn renew(self: *Session, a: std.mem.Allocator, cancel: *const std.atomic.Value(bool)) ?Record {
132- const refresh = self.record.refreshToken orelse return null;
133- const body = form(a, &.{
134- .{ "grant_type", "refresh_token" },
135- .{ "client_id", self.record.clientId },
136- .{ "refresh_token", refresh },
137- .{ "resource", resource },
138- }) catch return null;
139- const response = tokenRequest(a, body, cancel) orelse return null;
140- const bearer = response.access_token orelse return null;
141- return .{
142- .email = self.record.email,
143- .clientId = self.record.clientId,
144- .accessToken = bearer,
145- .refreshToken = response.refresh_token orelse self.record.refreshToken,
146- .idToken = response.id_token orelse self.record.idToken,
147- .expiresAt = time.nowMs() + @as(i64, @intCast(response.expires_in orelse 3600)) * 1000,
148- .scope = response.scope orelse self.record.scope,
149- };
150- }
151-};
152-
153-var session: ?Session = null;
154-var init_mutex: std.Io.Mutex = .init;
155-
156-/// The process-wide credential, loaded on first use and then kept in memory for
157-/// the life of the process. A `mini login` in another process is only visible to
158-/// a new one.
159-pub fn token(cancel: *const std.atomic.Value(bool)) ?[]const u8 {
160- init_mutex.lockUncancelable(platform.io);
161- if (session == null) {
162- const record = load(platform.gpa) orelse {
163- init_mutex.unlock(platform.io);
164- return null;
165- };
166- session = .{ .record = record };
167- }
168- init_mutex.unlock(platform.io);
169- return session.?.access(cancel);
170-}
src/config.zig+0−14
@@ -22,7 +22,6 @@ pub const CustomModel = struct {
2222 reasoning: bool,
2323 effort: []const []const u8 = &.{},
2424 cost: [3]f64,
25- oauth: bool = false,
2625 };
2726
2827 pub const CustomProvider = struct {
@@ -33,11 +32,6 @@ pub const CustomProvider = struct {
3332 headers: ?std.json.ArrayHashMap([]const u8) = null,
3433 };
3534
36-pub const McpServer = struct {
37- url: []const u8,
38- headers: ?std.json.ArrayHashMap([]const u8) = null,
39-};
40-
4135 pub const Config = struct {
4236 path: []const u8,
4337 sessions_dir: []const u8,
@@ -52,12 +46,10 @@ pub const Config = struct {
5246 herdr: bool,
5347 show_images: bool,
5448 custom_providers: []const CustomProvider,
55- mcp_servers: std.json.ArrayHashMap(McpServer),
5649 snapshot_ignore_dirs: []const []const u8,
5750 snapshot_uses_gitignore: bool,
5851 history_size: usize,
5952 max_diff_lines: usize,
60- oauth_redirect_brand: ?[]const u8,
6153 };
6254
6355 const File = struct {
@@ -72,13 +64,11 @@ const File = struct {
7264 model: ?[]const u8 = null,
7365 thinkingEffort: ?[]const u8 = null,
7466 customProviders: ?[]const CustomProvider = null,
75- mcpServers: ?std.json.ArrayHashMap(McpServer) = null,
7667 programStatus: ?bool = null,
7768 herdr: ?bool = null,
7869 showImages: ?bool = null,
7970 snapshotIgnoreDirs: ?[]const []const u8 = null,
8071 snapshotUsesGitignore: ?bool = null,
81- oauthRedirectBrand: ?[]const u8 = null,
8272 };
8373
8474 /// An empty environment variable is treated as unset, per the XDG spec.
@@ -151,7 +141,6 @@ fn readInto(a: std.mem.Allocator, path: []const u8, required: bool, cfg: *Config
151141 if (file.skillsDirs) |v| cfg.skills_dirs = v;
152142 if (file.tools) |v| cfg.tools = v;
153143 if (file.customProviders) |v| cfg.custom_providers = v;
154- if (file.mcpServers) |v| cfg.mcp_servers = v;
155144 if (file.thinkingEffort) |v| cfg.thinking_effort = v;
156145 if (file.programStatus) |v| cfg.program_status = v;
157146 if (file.herdr) |v| cfg.herdr = v;
@@ -160,7 +149,6 @@ fn readInto(a: std.mem.Allocator, path: []const u8, required: bool, cfg: *Config
160149 if (file.snapshotUsesGitignore) |v| cfg.snapshot_uses_gitignore = v;
161150 if (file.historySize) |v| cfg.history_size = v;
162151 if (file.maxDiffLines) |v| cfg.max_diff_lines = v;
163- if (file.oauthRedirectBrand) |v| cfg.oauth_redirect_brand = v;
164152 }
165153
166154 pub const Update = struct {
@@ -210,11 +198,9 @@ fn defaults(a: std.mem.Allocator) !Config {
210198 .herdr = false,
211199 .show_images = false,
212200 .custom_providers = &.{},
213- .mcp_servers = .{},
214201 .snapshot_ignore_dirs = &.{},
215202 .snapshot_uses_gitignore = true,
216203 .history_size = 100,
217204 .max_diff_lines = 2000,
218- .oauth_redirect_brand = null,
219205 };
220206 }
src/http.zig+0−52
@@ -75,58 +75,6 @@ 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 = @backingInt(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-
13078 pub fn postSse(
13179 a: std.mem.Allocator,
13280 url: []const u8,
src/main.zig+1−40
@@ -6,11 +6,9 @@ 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");
109 const tui = @import("tui/tui.zig");
1110 const term = @import("tui/term.zig");
1211 const headless = @import("headless.zig");
13-const siwc = @import("siwc.zig");
1412
1513 pub const panic = std.debug.FullPanic(panicRestore);
1614
@@ -28,7 +26,7 @@ pub const debug = struct {
2826
2927 var cancel = std.atomic.Value(bool).init(false);
3028
31-const ParsedArgs = struct { print: ?[]const u8 = null, config: ?[]const u8 = null, login: bool = false };
29+const ParsedArgs = struct { print: ?[]const u8 = null, config: ?[]const u8 = null };
3230
3331 fn parseArgs(a: std.mem.Allocator) !ParsedArgs {
3432 var it = std.process.Args.Iterator.init(platform.args);
@@ -44,8 +42,6 @@ fn parseArgs(a: std.mem.Allocator) !ParsedArgs {
4442 result.print = try a.dupe(u8, value);
4543 } else if (std.mem.startsWith(u8, arg, "--config=")) {
4644 result.config = try a.dupe(u8, arg["--config=".len..]);
47- } else if (std.mem.eql(u8, arg, "login")) {
48- result.login = true;
4945 } else if (std.mem.eql(u8, arg, "-c") or std.mem.eql(u8, arg, "--config")) {
5046 const value = it.next() orelse return error.MissingConfig;
5147 result.config = try a.dupe(u8, value);
@@ -66,39 +62,9 @@ pub fn main(init: std.process.Init) void {
6662 std.process.exit(code);
6763 }
6864
69-/// Splits a leading `mcp` subcommand from any configuration flags that precede
70-/// it, so `mini -c <file> mcp …` behaves like every other mode. Returns null
71-/// when `mcp` is not the subcommand.
72-fn mcpArgs(a: std.mem.Allocator) !?struct { config: ?[]const u8, args: []const []const u8 } {
73- var it = std.process.Args.Iterator.init(platform.args);
74- _ = it.next();
75- var config_path: ?[]const u8 = null;
76- while (it.next()) |arg| {
77- if (std.mem.startsWith(u8, arg, "--config=")) {
78- config_path = try a.dupe(u8, arg["--config=".len..]);
79- continue;
80- }
81- if (std.mem.eql(u8, arg, "-c") or std.mem.eql(u8, arg, "--config")) {
82- config_path = try a.dupe(u8, it.next() orelse return null);
83- continue;
84- }
85- if (!std.mem.eql(u8, arg, "mcp")) return null;
86-
87- var rest: std.ArrayList([]const u8) = .empty;
88- while (it.next()) |sub| try rest.append(a, sub);
89- return .{ .config = config_path, .args = try rest.toOwnedSlice(a) };
90- }
91- return null;
92-}
93-
9465 fn run() !u8 {
9566 const a = platform.gpa;
9667
97- if (try mcpArgs(a)) |mcp_call| {
98- const cfg = config.load(a, mcp_call.config) catch return 1;
99- return mcp.run(a, &cfg, mcp_call.args);
100- }
101-
10268 const args = parseArgs(a) catch |e| {
10369 switch (e) {
10470 error.MissingPrompt => platform.printErr("a prompt is required\n", .{}),
@@ -110,11 +76,6 @@ fn run() !u8 {
11076
11177 const cfg = config.load(a, args.config) catch return 1;
11278
113- if (args.login) {
114- siwc.login(a, &cfg) catch return 1;
115- return 0;
116- }
117-
11879 var resolve_err: ?[]const u8 = null;
11980 const model = models.resolve(a, &cfg, &resolve_err);
12081 if (resolve_err) |message| {
src/mcp.zig+0−456
@@ -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-}
src/models.zig+15−59
@@ -3,7 +3,6 @@ const platform = @import("platform.zig");
33 const modelsdev = @import("models_dev.zig");
44 const http = @import("http.zig");
55 const config = @import("config.zig");
6-const auth = @import("auth.zig");
76
87 pub const Thinking = enum { off, budget, effort };
98
@@ -24,24 +23,19 @@ pub const Model = struct {
2423 session_header: ?[]const u8,
2524 headers: []const [2][]const u8 = &.{},
2625 thinking: Thinking = .budget,
27- /// The bearer comes from the OAuth credential record, not from the environment.
28- oauth: bool = false,
2926 };
3027
31-/// How a provider proves who the user is. Everything else about it — name,
32-/// environment keys, API root, models — comes from the models.dev document.
33-const Credential = enum { env, chatgpt };
34-
28+/// A built-in provider is one whose models.dev entry the agent knows how to
29+/// request: name, environment keys, API root and models all come from the
30+/// document.
3531 const Builtin = struct {
3632 id: []const u8,
37- credential: Credential,
3833 session_header: ?[]const u8 = null,
3934 };
4035
4136 const builtins = [_]Builtin{
42- .{ .id = "opencode", .credential = .env, .session_header = "x-opencode-session" },
43- .{ .id = "opencode-go", .credential = .env, .session_header = "x-opencode-session" },
44- .{ .id = "openai", .credential = .chatgpt },
Cut short: this commit's diff is over 1000 lines.
src/prompt.zig+0−18
Cut short: this commit's diff is over 1000 lines.
src/siwc.zig+0−444
Cut short: this commit's diff is over 1000 lines.