Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
Blame · Line-by-line history

mcp.ts

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

mcp.tsBlame146 lines · 2 contributors
2c2163eClaude1/**
2 * Model Context Protocol HTTP transport.
3 *
4 * POST /mcp — JSON-RPC 2.0 requests; body is a single request
5 * or an array (batch). Response shape mirrors.
6 * GET /mcp — Lightweight discovery: returns server info +
7 * protocol version + tool count.
8 *
9 * Auth: softAuth — `userId` in the McpContext is the cookie/PAT/OAuth
10 * user when present, null otherwise. v1 tools are read-only and public-
11 * only, so anonymous works; write tools (v2) will require requireAuth +
12 * write-access on the target repo.
13 *
14 * Streamable-HTTP-mode is the recommended MCP transport for stateless
15 * cloud servers. We don't emit server-sent notifications yet, so the
16 * route is plain JSON in / JSON out.
17 */
18
19import { Hono } from "hono";
20import { softAuth } from "../middleware/auth";
21import type { AuthEnv } from "../middleware/auth";
22import {
23 routeMcpRequest,
24 MCP_PROTOCOL_VERSION,
25 MCP_SERVER_NAME,
26 MCP_SERVER_VERSION,
27} from "../lib/mcp";
28import { defaultTools } from "../lib/mcp-tools";
0a6ebcdccanty labs29import { config } from "../lib/config";
2c2163eClaude30
31const mcp = new Hono<AuthEnv>();
32
33mcp.use("*", softAuth);
34
0a6ebcdccanty labs35/**
36 * MCP authorization challenge (MCP auth spec + RFC 9728).
37 *
38 * When an anonymous client attempts to CALL a tool, respond 401 with a
39 * `WWW-Authenticate: Bearer resource_metadata="…"` header pointing at our
40 * protected-resource metadata. This is the signal a remote connector
41 * (claude.ai, Cursor, Copilot, …) follows to start the OAuth flow — so adding
42 * `<host>/mcp` as a connector and invoking a tool prompts sign-in, then works
43 * end to end.
44 *
45 * The handshake (initialize / tools/list / ping / notifications) stays open so
46 * any client can introspect the server unauthenticated — only `tools/call`
47 * requires an identity. Session cookie / PAT (`glc_`) / OAuth bearer (`glct_`)
48 * all satisfy it, so token clients (.mcp.json, CLI, VS Code extension) are
49 * unaffected. GET /mcp discovery also stays open.
50 */
51function authChallenge(c: Parameters<Parameters<typeof mcp.post>[1]>[0], id: unknown) {
52 const rm = `${config.appBaseUrl}/.well-known/oauth-protected-resource`;
53 c.header("WWW-Authenticate", `Bearer resource_metadata="${rm}"`);
54 return c.json(
55 {
56 jsonrpc: "2.0",
57 id: id ?? null,
58 error: { code: -32001, message: "Authentication required" },
59 },
60 401
61 );
62}
63
64/** True when the JSON-RPC envelope (single or batch) invokes a tool. */
65function invokesTool(body: unknown): boolean {
66 const isCall = (e: unknown): boolean =>
67 !!e &&
68 typeof e === "object" &&
69 (e as { method?: unknown }).method === "tools/call";
70 if (Array.isArray(body)) return body.some(isCall);
71 return isCall(body);
72}
73
2c2163eClaude74mcp.get("/mcp", (c) => {
75 const tools = defaultTools();
76 return c.json({
77 protocolVersion: MCP_PROTOCOL_VERSION,
78 serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION },
79 transport: "http",
80 toolCount: Object.keys(tools).length,
81 docs:
82 "POST /mcp with a JSON-RPC 2.0 envelope to call. See https://spec.modelcontextprotocol.io/",
83 });
84});
85
86mcp.post("/mcp", async (c) => {
87 const user = c.get("user") ?? null;
0feb720Claude88 // Scope derivation mirrors the API-auth middleware:
89 // - OAuth bearer (glct_) → oauthScopes from middleware
90 // - PAT (glc_) → oauthScopes from middleware
91 // - Session cookie → full ["repo","user","admin"]
92 // - Anonymous → []
93 const oauthScopes = c.get("oauthScopes");
94 let scopes: string[] = [];
95 if (Array.isArray(oauthScopes)) {
96 scopes = oauthScopes;
97 } else if (user) {
98 scopes = ["repo", "user", "admin"];
99 }
100 const ctx = { userId: user?.id ?? null, scopes };
2c2163eClaude101 const tools = defaultTools();
102
103 let body: unknown;
104 try {
105 body = await c.req.json();
106 } catch {
107 return c.json(
108 {
109 jsonrpc: "2.0",
110 id: null,
111 error: { code: -32700, message: "Parse error" },
112 },
113 400
114 );
115 }
116
0a6ebcdccanty labs117 // Anonymous tool calls trigger the OAuth discovery challenge so connectors
118 // sign in. The handshake (initialize/tools-list/ping/notifications) is left
119 // open above so clients can introspect without a token.
120 if (!user && invokesTool(body)) {
121 const id =
122 !Array.isArray(body) && body && typeof body === "object"
123 ? (body as { id?: unknown }).id ?? null
124 : null;
125 return authChallenge(c, id);
126 }
127
2c2163eClaude128 if (Array.isArray(body)) {
129 // Batched request — pass each through, drop nulls (notifications).
130 const out = await Promise.all(
131 body.map((entry) => routeMcpRequest(entry, { ctx, tools }))
132 );
133 const filtered = out.filter((r): r is NonNullable<typeof r> => r !== null);
134 if (filtered.length === 0) return c.body(null, 204);
135 return c.json(filtered);
136 }
137
138 const result = await routeMcpRequest(body, { ctx, tools });
139 if (result === null) {
140 // Notification — no response body, 204.
141 return c.body(null, 204);
142 }
143 return c.json(result);
144});
145
146export default mcp;