import { AgentError, agentSessions, type Answer } from "./sessions.ts"; const PROTOCOL_VERSION = "2025-06-18"; type Json = Record; type Sessions = ReturnType; interface Tool { readonly name: string; readonly description: string; readonly inputSchema: Json; run(sessions: Sessions, args: Json): Promise; } const NO_ARGS = { type: "object", properties: {} }; const TOOLS: readonly Tool[] = [ { name: "refs_connect", description: "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 / in //.git). It returns the git configuration that makes your clone authenticate as this session, and the rules for working here.", inputSchema: { type: "object", properties: { repo: { type: "string", description: "Repository name" }, client_session: { type: "string", description: "Your client's conversation id, as the refs hooks print it. Lets refs keep your session across reconnects." }, resume: { type: "string", description: "Your previous refs session id, to pick that session back up" }, }, required: ["repo"], }, run: (sessions, args) => sessions.connect({ repo: args.repo, resume: args.resume, machine: args.machine, parent: args.parent, credentials: args.credentials }), }, { name: "refs_take", 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.", inputSchema: { type: "object", properties: { pull: { type: "integer", minimum: 1, description: "Pull request number" }, branch: { type: "string", description: "Branch name, new or existing" }, }, }, run: (sessions, args) => sessions.take({ pull: args.pull, branch: args.branch }, args.credentials), }, { name: "refs_release", description: "Release your current branch. You stay online, idle, and can be given new work.", inputSchema: NO_ARGS, run: (sessions) => sessions.release(), }, { name: "refs_events", 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.", inputSchema: { type: "object", properties: { event: { type: "string", description: "Set only by a Claude Code hook: the hook event to answer for" }, client_session: { type: "string", description: "Set only by a Claude Code hook: the conversation id" }, }, }, run: (sessions, args) => sessions.events(typeof args.event === "string" && args.event ? args.event : undefined), }, { name: "refs_reply", description: "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/. 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.", inputSchema: { type: "object", properties: { mention: { type: "integer", description: "The mention you are answering" }, body: { type: "string", description: "Markdown" }, addressed_in: { type: "string", description: "Full hash of the pushed commit that addresses the review thread you were mentioned in" }, }, required: ["mention", "body"], }, run: (sessions, args) => sessions.reply(args.mention, args.body, args.addressed_in), }, { name: "refs_open_pull", description: "Open a pull request from the branch you hold, after you push it.", inputSchema: { type: "object", properties: { title: { type: "string" }, body: { type: "string", description: "Markdown" }, base: { type: "string", description: "The branch to merge into. Defaults to the repository's default branch." }, head: { type: "string", description: "The branch to merge. Defaults to the branch you hold." }, }, required: ["title"], }, run: (sessions, args) => sessions.openPull(args.title, args.body, args.base, args.head), }, { name: "refs_approve", 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.", inputSchema: { type: "object", properties: { tool_name: { type: "string" }, input: { type: "object" }, tool_use_id: { type: "string" }, request_id: { type: "string" }, withdraw: { type: "boolean" } }, required: ["tool_name", "input"], }, run: (sessions, args) => sessions.approve(args.tool_name, args.input, args.request_id, args.withdraw === true), }, { name: "refs_status", description: "Show whether you are online, on which repository, and which branch you hold.", inputSchema: NO_ARGS, run: (sessions) => sessions.status(), }, { name: "refs_end", description: "Go offline: end your session and revoke its git token. To finish your work but stay available, use refs_release.", inputSchema: { type: "object", properties: { outcome: { type: "string", enum: ["finished", "failed"] }, reason: { type: "string" } } }, 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."), }, ]; function newConnection(clientInfo: unknown): string { const name = typeof (clientInfo as Json | undefined)?.name === "string" ? ((clientInfo as Json).name as string) : "agent"; return `${crypto.randomUUID()}.${name.replace(/[^A-Za-z0-9:._-]/g, "-").slice(0, 64) || "agent"}`; } function runtimeOf(connection: string): string { return connection.slice(connection.indexOf(".") + 1) || "agent"; } /** The OAuth grant behind the request's access token, which the provider issues as `{userId}:{grantId}:{secret}`. */ function grantOf(request: Request): string | null { const parts = (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").split(":"); return parts.length === 3 && parts[1] ? parts[1] : null; } function reply(body: Json, headers: Record = {}): Response { return new Response(JSON.stringify(body), { headers: { "content-type": "application/json", ...headers } }); } /** The MCP server, over Streamable HTTP with JSON responses. Every request carries an OAuth access token, checked before this handler runs. */ export const mcpApi = { async fetch(request, env, ctx) { const userId = (ctx as ExecutionContext & { props?: { userId?: string } }).props?.userId; if (!userId) return new Response("Unauthorized\n", { status: 401 }); const connection = request.headers.get("mcp-session-id"); const origin = new URL(request.url).origin; if (request.method === "DELETE") { if (connection) await agentSessions(env, ctx, userId, connection, runtimeOf(connection), origin).detach(); return new Response(null, { status: 204 }); } if (request.method !== "POST") return new Response("Method not allowed\n", { status: 405, headers: { allow: "POST, DELETE" } }); let message: Json; try { message = (await request.json()) as Json; } catch { return reply({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }); } const id = message.id; if (id === undefined || id === null) return new Response(null, { status: 202 }); const params = (message.params ?? {}) as Json; const result = (value: Json, headers?: Record) => reply({ jsonrpc: "2.0", id, result: value }, headers); switch (message.method) { case "initialize": return result( { protocolVersion: typeof params.protocolVersion === "string" ? params.protocolVersion : PROTOCOL_VERSION, capabilities: { tools: {} }, serverInfo: { name: "refs", version: "1.0.0" }, instructions: "Call refs_connect with the repository's full name (/) at the start of a session in a clone of this refs server.", }, { "mcp-session-id": newConnection(params.clientInfo) }, ); case "ping": return result({}); case "tools/list": return result({ tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) }); case "tools/call": { const tool = TOOLS.find((candidate) => candidate.name === params.name); if (!tool) return reply({ jsonrpc: "2.0", id, error: { code: -32602, message: `Unknown tool ${String(params.name)}` } }); if (!connection) return result({ content: [{ type: "text", text: "This client did not send an Mcp-Session-Id. Reconnect the refs MCP server." }], isError: true }); const args = (params.arguments ?? {}) as Json; const clientSession = typeof args.client_session === "string" && args.client_session ? args.client_session.slice(0, 128) : null; const sessions = agentSessions(env, ctx, userId, connection, runtimeOf(connection), origin, clientSession, grantOf(request)); try { const answer = await tool.run(sessions, args); const { text, refs, session } = typeof answer === "string" ? { text: answer } : answer; ctx.waitUntil(sessions.touch()); const meta = { ...(refs ? { refs } : {}), ...(session ? { session } : {}) }; return result({ content: [{ type: "text", text }], ...(Object.keys(meta).length ? { _meta: meta } : {}) }); } catch (error) { if (!(error instanceof AgentError)) console.error("refs mcp tool failed", tool.name, error); return result({ content: [{ type: "text", text: error instanceof AgentError ? error.message : "Something went wrong on the refs server." }], isError: true }); } } default: return reply({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${String(message.method)}` } }); } }, } satisfies ExportedHandler;