- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/mcp.ts?version=261&format=json
273 linesFirst import 74% · pinch 22% · review 1% · speed 1% · groups 1% · rename 1% · devops 1%Last change groups in version 256, 15 versions changed it
You're reading version 261. The newest is 318, and 1 version since then changed this file.
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 abso -- abso 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 "pull",
39 "push",
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 "reply",
57 "groups",
58 "group",
59 "orgs",
60 "org",
61 "whoami",
62 "doctor",
63] as const;
65const PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"];
67interface Tool {
68 readonly name: string;
69 readonly description: string;
70 readonly inputSchema: Record<string, unknown>;
71}
73/** A tool's name: the command, with _ for - (check-ignore is check_ignore). */
74const toolName = (command: string): string => command.replace(/-/g, "_");
76export function mcpTools(): Tool[] {
77 const table = commandTable();
78 return MCP_COMMANDS.map((command) => {
79 const def = table[command]!;
80 const flags = Object.fromEntries(
81 Object.entries(def.flags).map(([flag, kind]) => [
82 flag,
83 kind === "boolean"
84 ? { type: "boolean", description: `--${flag}` }
85 : {
86 type: "string",
87 description: kind === "optional" ? `--${flag} "<value>"; "" gives --${flag} alone` : `--${flag} <value>`,
88 },
89 ]),
90 );
91 return {
92 name: toolName(command),
93 description: `${def.usage}\n${def.about}`,
94 inputSchema: {
95 type: "object",
96 properties: {
97 args: {
98 type: "array",
99 items: { type: "string" },
100 description: "The words after the command, as on the command line: files, versions, text.",
101 },
102 folder: {
103 type: "string",
104 description:
105 "The abso folder to run in: the folder this server started in (the default), or one inside it.",
106 },
107 json: { type: "boolean", description: "Answer with the command's JSON (as --json) instead of its text." },
108 ...flags,
109 },
110 additionalProperties: false,
111 },
112 };
113 });
114}
116/** A path as it really is (through links), or as given when it doesn't exist. */
117function real(path: string): string {
118 try {
119 return realpathSync.native(path);
120 } catch {
121 return path;
122 }
123}
125/** Whether `path` is `start` or inside it, after links are followed. */
126function inside(start: string, path: string): boolean {
127 const rel = relative(real(start), real(path));
128 return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
129}
131/** The tool inputs that name files or folders on this machine to read or write, comma-separated: each is confined like the folder. */
132export const FILE_INPUTS = ["attach", "clean", "save-attachments"] as const;
134/**
135 * Where a tool call runs, and what it may read: its folder and
136 * every file a FILE_INPUTS input names stay inside the folder the server
137 * started in. A relative path that climbs out (..), an absolute one elsewhere,
138 * or a link out is refused, so no tool reads a file outside the project.
139 * Answers the folder, or why the call is refused.
140 */
141export function confineCall(
142 start: string,
143 input: Readonly<Record<string, unknown>>,
144): { folder: string } | { refused: string } {
145 const named = typeof input.folder === "string" && input.folder !== "" ? input.folder : undefined;
146 const folder = named === undefined ? start : resolve(start, named);
147 if (!inside(start, folder))
148 return {
149 refused: `folder ${JSON.stringify(named)} is outside ${start}, the folder this server started in; tools run there or below`,
150 };
151 for (const flag of FILE_INPUTS) {
152 const value = input[flag];
153 if (typeof value !== "string") continue;
154 for (const p of value
155 .split(",")
156 .map((x) => x.trim())
157 .filter((x) => x !== ""))
158 if (!inside(start, resolve(folder, p)))
159 return {
160 refused: `--${flag} ${p} is outside ${start}, the folder this server started in; a tool reads and writes files only there or below`,
161 };
162 }
163 return { folder };
164}
166/** The command line a tool call stands for: flags as --name=value, then the words after --. */
167export function argvFor(command: string, input: Readonly<Record<string, unknown>>): string[] {
168 const def = commandTable()[command]!;
169 const argv = [command];
170 for (const [flag, kind] of Object.entries(def.flags)) {
171 const value = input[flag];
172 if (value === undefined || value === null || value === false) continue;
173 if (kind === "boolean") argv.push(`--${flag}`);
174 else argv.push(`--${flag}=${String(value)}`);
175 }
176 const words = Array.isArray(input.args) ? input.args.map(String) : [];
177 if (words.length > 0) argv.push("--", ...words);
178 return argv;
179}
181type Message = { jsonrpc?: string; id?: string | number | null; method?: string; params?: Record<string, unknown> };
183/**
184 * Serve MCP on `lines` (each one JSON-RPC message), answering through `send`.
185 * Calls run one at a time, since a command's news is gathered process-wide.
186 */
187export async function serveMcp(
188 input: AsyncIterable<Buffer | string>,
189 send: (line: string) => void,
190 cwd: string,
191 env: Readonly<Record<string, string | undefined>>,
192): Promise<void> {
193 let queue: Promise<void> = Promise.resolve();
194 const reply = (id: Message["id"], result: unknown) => send(JSON.stringify({ jsonrpc: "2.0", id, result }));
195 const fail = (id: Message["id"], code: number, message: string) =>
196 send(JSON.stringify({ jsonrpc: "2.0", id: id ?? null, error: { code, message } }));
198 const handle = async (msg: Message): Promise<void> => {
199 const { id, method, params = {} } = msg;
200 const isRequest = id !== undefined && id !== null;
201 switch (method) {
202 case "initialize": {
203 const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
204 return reply(id, {
205 protocolVersion: PROTOCOLS.includes(asked) ? asked : PROTOCOLS[0],
206 capabilities: { tools: {} },
207 serverInfo: { name: "abso", version: clientVersion() },
208 instructions:
209 "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.",
210 });
211 }
212 case "ping":
213 return reply(id, {});
214 case "tools/list":
215 return reply(id, { tools: mcpTools() });
216 case "tools/call": {
217 const name = typeof params.name === "string" ? params.name : "";
218 const command = MCP_COMMANDS.find((c) => toolName(c) === name);
219 if (command === undefined) return fail(id, -32602, `no tool ${JSON.stringify(name)}; tools/list names them`);
220 const args = (params.arguments ?? {}) as Record<string, unknown>;
221 const where = confineCall(cwd, args);
222 if ("refused" in where) return reply(id, { content: [{ type: "text", text: where.refused }], isError: true });
223 const folder = where.folder;
224 let streamed = "";
225 const result = await main(argvFor(command, args), {
226 cwd: folder,
227 env,
228 write: (t) => (streamed += t),
229 writeErr: (t) => (streamed += t),
230 });
231 // Text only: Claude Code shows the model structuredContent in place of the text when both are there,
232 // and the point is the command line's words. json: true answers with the JSON instead.
233 const text =
234 args.json === true && result.data
235 ? JSON.stringify({ ...result.data, exit: result.exit }, null, 2)
236 : [streamed, result.stdout, result.stderr]
237 .map((t) => t.replace(/\n+$/, ""))
238 .filter((t) => t !== "")
239 .join("\n");
240 return reply(id, {
241 content: [{ type: "text", text: text === "" ? "(no output)" : text }],
242 // Exit 1 is a failure; 2 (refused) and 3 (still queued) are answers the text explains.
243 isError: result.exit === 1,
244 });
245 }
246 default:
247 // Notifications (no id) need no answer; an unknown request does.
248 if (isRequest) fail(id, -32601, `abso mcp doesn't know ${JSON.stringify(method)}`);
249 }
250 };
252 let buffer = "";
253 for await (const chunk of input) {
254 buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
255 let nl: number;
256 while ((nl = buffer.indexOf("\n")) >= 0) {
257 const line = buffer.slice(0, nl).trim();
258 buffer = buffer.slice(nl + 1);
259 if (line === "") continue;
260 let msg: Message;
261 try {
262 msg = JSON.parse(line) as Message;
263 } catch {
264 fail(null, -32700, "not JSON");
265 continue;
266 }
267 queue = queue
268 .then(() => handle(msg))
269 .catch((e: unknown) => fail(msg.id, -32603, e instanceof Error ? e.message : String(e)));
270 }
271 }
272 await queue;
273}