- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/mcp.ts?draft=login-timeout&format=json
268 linesFirst import 76% · pinch 22% · review 1% · devops 1%0 versions changed it
1// abso mcp: an MCP server on stdin and stdout (#42, #44). Each tool is one avcs
2// command, run by the same code as the command line and answering with the
3// same text, so the CLI and the tools can't drift apart and an agent learns
4// one set of words. The folder and the token come from where the server runs,
5// as for the CLI: .avcs/config.json, and ABSO_TOKEN or ~/.abso/token.
6//
7// claude mcp add avcs -- node <repo>/client/avcs.ts mcp
8//
9// The protocol is JSON-RPC 2.0, one message per line, with no library: the
10// client uses nothing outside Node.
12import { realpathSync } from "node:fs";
13import { isAbsolute, relative, resolve, sep } from "node:path";
14import { clientVersion } from "./client-version.ts";
15import { commandTable, main } from "./main.ts";
17/**
18 * The commands served as tools: reading, and the writes an agent makes every
19 * day. The box commands (run, shot, bisect, prep, logs, fetch) stream for
20 * minutes and stay in the shell, as do setting a folder up (init, join) and
21 * the ones that rewrite history or move between drafts.
22 */
23export const MCP_COMMANDS = [
24 "status",
25 "log",
26 "show",
27 "diff",
28 "files",
29 "who",
30 "where",
31 "blame",
32 "why",
33 "ci",
34 "news",
35 "announce",
36 "start",
37 "record",
38 "sync",
39 "publish",
40 "unqueue",
41 "restore",
42 "settle",
43 "check-ignore",
44 "labels",
45 "mv",
46 "review",
47 "note",
48 "notes",
49 "issues",
50 "issue",
51 "search",
52 "ask",
53 "waiting",
54 "answer",
55 "ack",
56 "orgs",
57 "org",
58] as const;
60const PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"];
62interface Tool {
63 readonly name: string;
64 readonly description: string;
65 readonly inputSchema: Record<string, unknown>;
66}
68/** A tool's name: the command, with _ for - (check-ignore is check_ignore). */
69const toolName = (command: string): string => command.replace(/-/g, "_");
71export function mcpTools(): Tool[] {
72 const table = commandTable();
73 return MCP_COMMANDS.map((command) => {
74 const def = table[command]!;
75 const flags = Object.fromEntries(
76 Object.entries(def.flags).map(([flag, kind]) => [
77 flag,
78 kind === "boolean"
79 ? { type: "boolean", description: `--${flag}` }
80 : {
81 type: "string",
82 description: kind === "optional" ? `--${flag} "<value>"; "" gives --${flag} alone` : `--${flag} <value>`,
83 },
84 ]),
85 );
86 return {
87 name: toolName(command),
88 description: `${def.usage}\n${def.about}`,
89 inputSchema: {
90 type: "object",
91 properties: {
92 args: {
93 type: "array",
94 items: { type: "string" },
95 description: "The words after the command, as on the command line: files, versions, text.",
96 },
97 folder: {
98 type: "string",
99 description:
100 "The abso folder to run in: the folder this server started in (the default), or one inside it.",
101 },
102 json: { type: "boolean", description: "Answer with the command's JSON (as --json) instead of its text." },
103 ...flags,
104 },
105 additionalProperties: false,
106 },
107 };
108 });
109}
111/** A path as it really is (through links), or as given when it doesn't exist. */
112function real(path: string): string {
113 try {
114 return realpathSync.native(path);
115 } catch {
116 return path;
117 }
118}
120/** Whether `path` is `start` or inside it, after links are followed. */
121function inside(start: string, path: string): boolean {
122 const rel = relative(real(start), real(path));
123 return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
124}
126/** The tool inputs that name files or folders on this machine to read or write, comma-separated: each is confined like the folder. */
127export const FILE_INPUTS = ["attach", "clean", "save-attachments"] as const;
129/**
130 * Where a tool call runs, and what it may read: its folder and
131 * every file a FILE_INPUTS input names stay inside the folder the server
132 * started in. A relative path that climbs out (..), an absolute one elsewhere,
133 * or a link out is refused, so no tool reads a file outside the project.
134 * Answers the folder, or why the call is refused.
135 */
136export function confineCall(
137 start: string,
138 input: Readonly<Record<string, unknown>>,
139): { folder: string } | { refused: string } {
140 const named = typeof input.folder === "string" && input.folder !== "" ? input.folder : undefined;
141 const folder = named === undefined ? start : resolve(start, named);
142 if (!inside(start, folder))
143 return {
144 refused: `folder ${JSON.stringify(named)} is outside ${start}, the folder this server started in; tools run there or below`,
145 };
146 for (const flag of FILE_INPUTS) {
147 const value = input[flag];
148 if (typeof value !== "string") continue;
149 for (const p of value
150 .split(",")
151 .map((x) => x.trim())
152 .filter((x) => x !== ""))
153 if (!inside(start, resolve(folder, p)))
154 return {
155 refused: `--${flag} ${p} is outside ${start}, the folder this server started in; a tool reads and writes files only there or below`,
156 };
157 }
158 return { folder };
159}
161/** The command line a tool call stands for: flags as --name=value, then the words after --. */
162export function argvFor(command: string, input: Readonly<Record<string, unknown>>): string[] {
163 const def = commandTable()[command]!;
164 const argv = [command];
165 for (const [flag, kind] of Object.entries(def.flags)) {
166 const value = input[flag];
167 if (value === undefined || value === null || value === false) continue;
168 if (kind === "boolean") argv.push(`--${flag}`);
169 else argv.push(`--${flag}=${String(value)}`);
170 }
171 const words = Array.isArray(input.args) ? input.args.map(String) : [];
172 if (words.length > 0) argv.push("--", ...words);
173 return argv;
174}
176type Message = { jsonrpc?: string; id?: string | number | null; method?: string; params?: Record<string, unknown> };
178/**
179 * Serve MCP on `lines` (each one JSON-RPC message), answering through `send`.
180 * Calls run one at a time, since a command's news is gathered process-wide.
181 */
182export async function serveMcp(
183 input: AsyncIterable<Buffer | string>,
184 send: (line: string) => void,
185 cwd: string,
186 env: Readonly<Record<string, string | undefined>>,
187): Promise<void> {
188 let queue: Promise<void> = Promise.resolve();
189 const reply = (id: Message["id"], result: unknown) => send(JSON.stringify({ jsonrpc: "2.0", id, result }));
190 const fail = (id: Message["id"], code: number, message: string) =>
191 send(JSON.stringify({ jsonrpc: "2.0", id: id ?? null, error: { code, message } }));
193 const handle = async (msg: Message): Promise<void> => {
194 const { id, method, params = {} } = msg;
195 const isRequest = id !== undefined && id !== null;
196 switch (method) {
197 case "initialize": {
198 const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
199 return reply(id, {
200 protocolVersion: PROTOCOLS.includes(asked) ? asked : PROTOCOLS[0],
201 capabilities: { tools: {} },
202 serverInfo: { name: "abso", version: clientVersion() },
203 instructions:
204 "abso, the agent-first version control client. Each tool is the abso command of the same name and answers with the command line's text. Box runs (abso run, shot, bisect) stay in the shell.",
205 });
206 }
207 case "ping":
208 return reply(id, {});
209 case "tools/list":
210 return reply(id, { tools: mcpTools() });
211 case "tools/call": {
212 const name = typeof params.name === "string" ? params.name : "";
213 const command = MCP_COMMANDS.find((c) => toolName(c) === name);
214 if (command === undefined) return fail(id, -32602, `no tool ${JSON.stringify(name)}; tools/list names them`);
215 const args = (params.arguments ?? {}) as Record<string, unknown>;
216 const where = confineCall(cwd, args);
217 if ("refused" in where) return reply(id, { content: [{ type: "text", text: where.refused }], isError: true });
218 const folder = where.folder;
219 let streamed = "";
220 const result = await main(argvFor(command, args), {
221 cwd: folder,
222 env,
223 write: (t) => (streamed += t),
224 writeErr: (t) => (streamed += t),
225 });
226 // Text only: Claude Code shows the model structuredContent in place of the text when both are there,
227 // and the point is the command line's words. json: true answers with the JSON instead.
228 const text =
229 args.json === true && result.data
230 ? JSON.stringify({ ...result.data, exit: result.exit }, null, 2)
231 : [streamed, result.stdout, result.stderr]
232 .map((t) => t.replace(/\n+$/, ""))
233 .filter((t) => t !== "")
234 .join("\n");
235 return reply(id, {
236 content: [{ type: "text", text: text === "" ? "(no output)" : text }],
237 // Exit 1 is a failure; 2 (refused) and 3 (still queued) are answers the text explains.
238 isError: result.exit === 1,
239 });
240 }
241 default:
242 // Notifications (no id) need no answer; an unknown request does.
243 if (isRequest) fail(id, -32601, `abso mcp doesn't know ${JSON.stringify(method)}`);
244 }
245 };
247 let buffer = "";
248 for await (const chunk of input) {
249 buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
250 let nl: number;
251 while ((nl = buffer.indexOf("\n")) >= 0) {
252 const line = buffer.slice(0, nl).trim();
253 buffer = buffer.slice(nl + 1);
254 if (line === "") continue;
255 let msg: Message;
256 try {
257 msg = JSON.parse(line) as Message;
258 } catch {
259 fail(null, -32700, "not JSON");
260 continue;
261 }
262 queue = queue
263 .then(() => handle(msg))
264 .catch((e: unknown) => fail(msg.id, -32603, e instanceof Error ? e.message : String(e)));
265 }
266 }
267 await queue;
268}