203 lines · 10.4 KBRaw
| 1 | import { AgentError, agentSessions, type Answer } from "./sessions.ts"; |
| 2 | |
| 3 | const PROTOCOL_VERSION = "2025-06-18"; |
| 4 | |
| 5 | type Json = Record<string, unknown>; |
| 6 | type Sessions = ReturnType<typeof agentSessions>; |
| 7 | |
| 8 | interface Tool { |
| 9 | readonly name: string; |
| 10 | readonly description: string; |
| 11 | readonly inputSchema: Json; |
| 12 | run(sessions: Sessions, args: Json): Promise<string | Answer>; |
| 13 | } |
| 14 | |
| 15 | const NO_ARGS = { type: "object", properties: {} }; |
| 16 | |
| 17 | const 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 | }, |
| 88 | required: ["title"], |
| 89 | }, |
| 90 | run: (sessions, args) => sessions.openPull(args.title, args.body, args.base), |
| 91 | }, |
| 92 | { |
| 93 | name: "refs_view_pull", |
| 94 | description: "Show the open pull request of the branch you hold: whether it merges cleanly, the review threads a human has not resolved with their last comment, and its latest CI run with the end of each failed job's log.", |
| 95 | inputSchema: NO_ARGS, |
| 96 | run: (sessions) => sessions.viewPull(), |
| 97 | }, |
| 98 | { |
| 99 | name: "refs_approve", |
| 100 | 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.", |
| 101 | inputSchema: { |
| 102 | type: "object", |
| 103 | properties: { tool_name: { type: "string" }, input: { type: "object" }, tool_use_id: { type: "string" }, request_id: { type: "string" }, withdraw: { type: "boolean" } }, |
| 104 | required: ["tool_name", "input"], |
| 105 | }, |
| 106 | run: (sessions, args) => sessions.approve(args.tool_name, args.input, args.request_id, args.withdraw === true), |
| 107 | }, |
| 108 | { |
| 109 | name: "refs_status", |
| 110 | description: "Show whether you are online, on which repository, and which branch you hold.", |
| 111 | inputSchema: NO_ARGS, |
| 112 | run: (sessions) => sessions.status(), |
| 113 | }, |
| 114 | { |
| 115 | name: "refs_end", |
| 116 | description: "Go offline: end your session and revoke its git token. To finish your work but stay available, use refs_release.", |
| 117 | inputSchema: { type: "object", properties: { outcome: { type: "string", enum: ["finished", "failed"] }, reason: { type: "string" } } }, |
| 118 | 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."), |
| 119 | }, |
| 120 | ]; |
| 121 | |
| 122 | function newConnection(clientInfo: unknown): string { |
| 123 | const name = typeof (clientInfo as Json | undefined)?.name === "string" ? ((clientInfo as Json).name as string) : "agent"; |
| 124 | return `${crypto.randomUUID()}.${name.replace(/[^A-Za-z0-9:._-]/g, "-").slice(0, 64) || "agent"}`; |
| 125 | } |
| 126 | |
| 127 | function runtimeOf(connection: string): string { |
| 128 | return connection.slice(connection.indexOf(".") + 1) || "agent"; |
| 129 | } |
| 130 | |
| 131 | /** The OAuth grant behind the request's access token, which the provider issues as `{userId}:{grantId}:{secret}`. */ |
| 132 | function grantOf(request: Request): string | null { |
| 133 | const parts = (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").split(":"); |
| 134 | return parts.length === 3 && parts[1] ? parts[1] : null; |
| 135 | } |
| 136 | |
| 137 | function reply(body: Json, headers: Record<string, string> = {}): Response { |
| 138 | return new Response(JSON.stringify(body), { headers: { "content-type": "application/json", ...headers } }); |
| 139 | } |
| 140 | |
| 141 | /** The MCP server, over Streamable HTTP with JSON responses. Every request carries an OAuth access token, checked before this handler runs. */ |
| 142 | export const mcpApi = { |
| 143 | async fetch(request, env, ctx) { |
| 144 | const userId = (ctx as ExecutionContext & { props?: { userId?: string } }).props?.userId; |
| 145 | if (!userId) return new Response("Unauthorized\n", { status: 401 }); |
| 146 | const connection = request.headers.get("mcp-session-id"); |
| 147 | const origin = new URL(request.url).origin; |
| 148 | |
| 149 | if (request.method === "DELETE") { |
| 150 | if (connection) await agentSessions(env, ctx, userId, connection, runtimeOf(connection), origin).detach(); |
| 151 | return new Response(null, { status: 204 }); |
| 152 | } |
| 153 | if (request.method !== "POST") return new Response("Method not allowed\n", { status: 405, headers: { allow: "POST, DELETE" } }); |
| 154 | |
| 155 | let message: Json; |
| 156 | try { |
| 157 | message = (await request.json()) as Json; |
| 158 | } catch { |
| 159 | return reply({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }); |
| 160 | } |
| 161 | const id = message.id; |
| 162 | if (id === undefined || id === null) return new Response(null, { status: 202 }); |
| 163 | const params = (message.params ?? {}) as Json; |
| 164 | const result = (value: Json, headers?: Record<string, string>) => reply({ jsonrpc: "2.0", id, result: value }, headers); |
| 165 | |
| 166 | switch (message.method) { |
| 167 | case "initialize": |
| 168 | return result( |
| 169 | { |
| 170 | protocolVersion: typeof params.protocolVersion === "string" ? params.protocolVersion : PROTOCOL_VERSION, |
| 171 | capabilities: { tools: {} }, |
| 172 | serverInfo: { name: "refs", version: "1.0.0" }, |
| 173 | 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.", |
| 174 | }, |
| 175 | { "mcp-session-id": newConnection(params.clientInfo) }, |
| 176 | ); |
| 177 | case "ping": |
| 178 | return result({}); |
| 179 | case "tools/list": |
| 180 | return result({ tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) }); |
| 181 | case "tools/call": { |
| 182 | const tool = TOOLS.find((candidate) => candidate.name === params.name); |
| 183 | if (!tool) return reply({ jsonrpc: "2.0", id, error: { code: -32602, message: `Unknown tool ${String(params.name)}` } }); |
| 184 | if (!connection) return result({ content: [{ type: "text", text: "This client did not send an Mcp-Session-Id. Reconnect the refs MCP server." }], isError: true }); |
| 185 | const args = (params.arguments ?? {}) as Json; |
| 186 | const clientSession = typeof args.client_session === "string" && args.client_session ? args.client_session.slice(0, 128) : null; |
| 187 | const sessions = agentSessions(env, ctx, userId, connection, runtimeOf(connection), origin, clientSession, grantOf(request)); |
| 188 | try { |
| 189 | const answer = await tool.run(sessions, args); |
| 190 | const { text, refs, session } = typeof answer === "string" ? { text: answer } : answer; |
| 191 | ctx.waitUntil(sessions.touch()); |
| 192 | const meta = { ...(refs ? { refs } : {}), ...(session ? { session } : {}) }; |
| 193 | return result({ content: [{ type: "text", text }], ...(Object.keys(meta).length ? { _meta: meta } : {}) }); |
| 194 | } catch (error) { |
| 195 | if (!(error instanceof AgentError)) console.error("refs mcp tool failed", tool.name, error); |
| 196 | return result({ content: [{ type: "text", text: error instanceof AgentError ? error.message : "Something went wrong on the refs server." }], isError: true }); |
| 197 | } |
| 198 | } |
| 199 | default: |
| 200 | return reply({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${String(message.method)}` } }); |
| 201 | } |
| 202 | }, |
| 203 | } satisfies ExportedHandler<Env>; |