Skip to content
refs
198 lines · 10.2 KBRaw
1import { AgentError, agentSessions, type Answer } from "./sessions.ts";
2
3const PROTOCOL_VERSION = "2025-06-18";
4
5type Json = Record<string, unknown>;
6type Sessions = ReturnType<typeof agentSessions>;
7
8interface Tool {
9 readonly name: string;
10 readonly description: string;
11 readonly inputSchema: Json;
12 run(sessions: Sessions, args: Json): Promise<string | Answer>;
13}
14
15const NO_ARGS = { type: "object", properties: {} };
16
17const TOOLS: readonly Tool[] = [
18 {
19 name: "refs_connect",
20 description:
21 "Come online on a refs repository as the human who signed this client in. Call it at the start of every session in a clone whose origin is this refs server, with the repository's full name (the <namespace>/<repo> in <origin>/<namespace>/<repo>.git). It returns the git configuration that makes your clone authenticate as this session, and the rules for working here.",
22 inputSchema: {
23 type: "object",
24 properties: {
25 repo: { type: "string", description: "Repository name" },
26 client_session: { type: "string", description: "Your client's conversation id, as the refs hooks print it. Lets refs keep your session across reconnects." },
27 resume: { type: "string", description: "Your previous refs session id, to pick that session back up" },
28 },
29 required: ["repo"],
30 },
31 run: (sessions, args) => sessions.connect({ repo: args.repo, resume: args.resume, machine: args.machine, parent: args.parent, credentials: args.credentials }),
32 },
33 {
34 name: "refs_take",
35 description: "Take work in the connected repository: a pull request (its head branch), or any branch by name except the default branch. Give exactly one. You may then push only that branch.",
36 inputSchema: {
37 type: "object",
38 properties: {
39 pull: { type: "integer", minimum: 1, description: "Pull request number" },
40 branch: { type: "string", description: "Branch name, new or existing" },
41 },
42 },
43 run: (sessions, args) => sessions.take({ pull: args.pull, branch: args.branch }, args.credentials),
44 },
45 {
46 name: "refs_release",
47 description: "Release your current branch. You stay online, idle, and can be given new work.",
48 inputSchema: NO_ARGS,
49 run: (sessions) => sessions.release(),
50 },
51 {
52 name: "refs_events",
53 description: "Read updates: pushes to your branch by others, instructions and mentions from humans and agents, and stop. Call it before every push if your client has no refs hooks.",
54 inputSchema: {
55 type: "object",
56 properties: {
57 event: { type: "string", description: "Set only by a Claude Code hook: the hook event to answer for" },
58 client_session: { type: "string", description: "Set only by a Claude Code hook: the conversation id" },
59 },
60 },
61 run: (sessions, args) => sessions.events(typeof args.event === "string" && args.event ? args.event : undefined),
62 },
63 {
64 name: "refs_reply",
65 description:
66 "Post a comment as yourself, acting for your human. Answer a mention by its id, and the reply goes where you were mentioned: the pull request, or the review thread. Mention others with @agent/<session>. When you have pushed a fix for a review thread, pass addressed_in with that commit's full hash: the thread is marked addressed, and a human confirms and resolves it. You cannot resolve threads.",
67 inputSchema: {
68 type: "object",
69 properties: {
70 mention: { type: "integer", description: "The mention you are answering" },
71 body: { type: "string", description: "Markdown" },
72 addressed_in: { type: "string", description: "Full hash of the pushed commit that addresses the review thread you were mentioned in" },
73 },
74 required: ["mention", "body"],
75 },
76 run: (sessions, args) => sessions.reply(args.mention, args.body, args.addressed_in),
77 },
78 {
79 name: "refs_open_pull",
80 description: "Open a pull request from the branch you hold, after you push it.",
81 inputSchema: {
82 type: "object",
83 properties: {
84 title: { type: "string" },
85 body: { type: "string", description: "Markdown" },
86 base: { type: "string", description: "The branch to merge into. Defaults to the repository's default branch." },
87 head: { type: "string", description: "The branch to merge. Defaults to the branch you hold." },
88 },
89 required: ["title"],
90 },
91 run: (sessions, args) => sessions.openPull(args.title, args.body, args.base, args.head),
92 },
93 {
94 name: "refs_approve",
95 description: "Asks your human to approve a tool call on the refs portal and waits for the answer. With withdraw, takes back request_id because it was answered elsewhere.",
96 inputSchema: {
97 type: "object",
98 properties: { tool_name: { type: "string" }, input: { type: "object" }, tool_use_id: { type: "string" }, request_id: { type: "string" }, withdraw: { type: "boolean" } },
99 required: ["tool_name", "input"],
100 },
101 run: (sessions, args) => sessions.approve(args.tool_name, args.input, args.request_id, args.withdraw === true),
102 },
103 {
104 name: "refs_status",
105 description: "Show whether you are online, on which repository, and which branch you hold.",
106 inputSchema: NO_ARGS,
107 run: (sessions) => sessions.status(),
108 },
109 {
110 name: "refs_end",
111 description: "Go offline: end your session and revoke its git token. To finish your work but stay available, use refs_release.",
112 inputSchema: { type: "object", properties: { outcome: { type: "string", enum: ["finished", "failed"] }, reason: { type: "string" } } },
113 run: (sessions, args) => sessions.end(args.outcome === "failed" ? "failed" : "finished", typeof args.reason === "string" && args.reason ? args.reason.slice(0, 500) : "Ended by the agent."),
114 },
115];
116
117function newConnection(clientInfo: unknown): string {
118 const name = typeof (clientInfo as Json | undefined)?.name === "string" ? ((clientInfo as Json).name as string) : "agent";
119 return `${crypto.randomUUID()}.${name.replace(/[^A-Za-z0-9:._-]/g, "-").slice(0, 64) || "agent"}`;
120}
121
122function runtimeOf(connection: string): string {
123 return connection.slice(connection.indexOf(".") + 1) || "agent";
124}
125
126/** The OAuth grant behind the request's access token, which the provider issues as `{userId}:{grantId}:{secret}`. */
127function grantOf(request: Request): string | null {
128 const parts = (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").split(":");
129 return parts.length === 3 && parts[1] ? parts[1] : null;
130}
131
132function reply(body: Json, headers: Record<string, string> = {}): Response {
133 return new Response(JSON.stringify(body), { headers: { "content-type": "application/json", ...headers } });
134}
135
136/** The MCP server, over Streamable HTTP with JSON responses. Every request carries an OAuth access token, checked before this handler runs. */
137export const mcpApi = {
138 async fetch(request, env, ctx) {
139 const userId = (ctx as ExecutionContext & { props?: { userId?: string } }).props?.userId;
140 if (!userId) return new Response("Unauthorized\n", { status: 401 });
141 const connection = request.headers.get("mcp-session-id");
142 const origin = new URL(request.url).origin;
143
144 if (request.method === "DELETE") {
145 if (connection) await agentSessions(env, ctx, userId, connection, runtimeOf(connection), origin).detach();
146 return new Response(null, { status: 204 });
147 }
148 if (request.method !== "POST") return new Response("Method not allowed\n", { status: 405, headers: { allow: "POST, DELETE" } });
149
150 let message: Json;
151 try {
152 message = (await request.json()) as Json;
153 } catch {
154 return reply({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
155 }
156 const id = message.id;
157 if (id === undefined || id === null) return new Response(null, { status: 202 });
158 const params = (message.params ?? {}) as Json;
159 const result = (value: Json, headers?: Record<string, string>) => reply({ jsonrpc: "2.0", id, result: value }, headers);
160
161 switch (message.method) {
162 case "initialize":
163 return result(
164 {
165 protocolVersion: typeof params.protocolVersion === "string" ? params.protocolVersion : PROTOCOL_VERSION,
166 capabilities: { tools: {} },
167 serverInfo: { name: "refs", version: "1.0.0" },
168 instructions: "Call refs_connect with the repository's full name (<namespace>/<repo>) at the start of a session in a clone of this refs server.",
169 },
170 { "mcp-session-id": newConnection(params.clientInfo) },
171 );
172 case "ping":
173 return result({});
174 case "tools/list":
175 return result({ tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
176 case "tools/call": {
177 const tool = TOOLS.find((candidate) => candidate.name === params.name);
178 if (!tool) return reply({ jsonrpc: "2.0", id, error: { code: -32602, message: `Unknown tool ${String(params.name)}` } });
179 if (!connection) return result({ content: [{ type: "text", text: "This client did not send an Mcp-Session-Id. Reconnect the refs MCP server." }], isError: true });
180 const args = (params.arguments ?? {}) as Json;
181 const clientSession = typeof args.client_session === "string" && args.client_session ? args.client_session.slice(0, 128) : null;
182 const sessions = agentSessions(env, ctx, userId, connection, runtimeOf(connection), origin, clientSession, grantOf(request));
183 try {
184 const answer = await tool.run(sessions, args);
185 const { text, refs, session } = typeof answer === "string" ? { text: answer } : answer;
186 ctx.waitUntil(sessions.touch());
187 const meta = { ...(refs ? { refs } : {}), ...(session ? { session } : {}) };
188 return result({ content: [{ type: "text", text }], ...(Object.keys(meta).length ? { _meta: meta } : {}) });
189 } catch (error) {
190 if (!(error instanceof AgentError)) console.error("refs mcp tool failed", tool.name, error);
191 return result({ content: [{ type: "text", text: error instanceof AgentError ? error.message : "Something went wrong on the refs server." }], isError: true });
192 }
193 }
194 default:
195 return reply({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${String(message.method)}` } });
196 }
197 },
198} satisfies ExportedHandler<Env>;