CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | /**
* MCP (Model Context Protocol) HTTP endpoint — 2024-11-05 spec.
*
* Single endpoint: POST /mcp
* Discovery: GET /mcp
*
* Authentication: Bearer token in the Authorization header.
* - Tokens prefixed `glc_` → PAT (api_tokens table)
* - Tokens prefixed `glct_` → OAuth access token (oauth_access_tokens table)
* - No token → unauthenticated (only certain read-only methods are allowed)
*
* JSON-RPC 2.0 methods:
* initialize
* notifications/initialized
* tools/list
* tools/call
* resources/list
*/
import { Hono } from "hono";
import { eq } from "drizzle-orm";
import { db } from "../db";
import { apiTokens, users, oauthAccessTokens } from "../db/schema";
import type { User } from "../db/schema";
import { sha256Hex } from "../lib/oauth";
import {
MCP_TOOLS,
MCP_TOOL_MAP,
McpToolError,
serializeTool,
} from "../lib/mcp-tools";
const mcp = new Hono();
// --------------------------------------------------------------------------
// Constants
// --------------------------------------------------------------------------
const PROTOCOL_VERSION = "2024-11-05";
const SERVER_INFO = { name: "gluecron", version: "1.0.0" };
// JSON-RPC error codes
const E_PARSE = -32700;
const E_INVALID_REQUEST = -32600;
const E_METHOD_NOT_FOUND = -32601;
const E_INVALID_PARAMS = -32602;
const E_INTERNAL = -32603;
const E_UNAUTHORIZED = -32001;
const E_NOT_FOUND = -32004;
// Methods that do NOT require authentication
const PUBLIC_METHODS = new Set([
"initialize",
"notifications/initialized",
"tools/list",
"resources/list",
]);
// --------------------------------------------------------------------------
// Auth helpers (inline — no middleware, raw handler)
// --------------------------------------------------------------------------
async function loadUserFromPat(token: string): Promise<User | null> {
if (!token.startsWith("glc_")) return null;
try {
const hash = await sha256Hex(token);
const [row] = await db
.select()
.from(apiTokens)
.where(eq(apiTokens.tokenHash, hash))
.limit(1);
if (!row) return null;
if (row.expiresAt && new Date(row.expiresAt) < new Date()) return null;
const [user] = await db
.select()
.from(users)
.where(eq(users.id, row.userId))
.limit(1);
if (!user) return null;
// Best-effort: update lastUsedAt
db.update(apiTokens)
.set({ lastUsedAt: new Date() })
.where(eq(apiTokens.id, row.id))
.catch(() => {});
return user;
} catch {
return null;
}
}
async function loadUserFromOauthBearer(token: string): Promise<User | null> {
if (!token.startsWith("glct_")) return null;
try {
const hash = await sha256Hex(token);
const [row] = await db
.select()
.from(oauthAccessTokens)
.where(eq(oauthAccessTokens.accessTokenHash, hash))
.limit(1);
if (!row) return null;
if (row.revokedAt) return null;
if (new Date(row.expiresAt) < new Date()) return null;
const [user] = await db
.select()
.from(users)
.where(eq(users.id, row.userId))
.limit(1);
if (!user) return null;
db.update(oauthAccessTokens)
.set({ lastUsedAt: new Date() })
.where(eq(oauthAccessTokens.id, row.id))
.catch(() => {});
return user;
} catch {
return null;
}
}
/**
* Extract the authenticated user (or null) from the Authorization header.
* Accepts both PAT (`glc_`) and OAuth bearer (`glct_`) tokens.
*/
async function resolveUser(authHeader: string | undefined): Promise<User | null> {
if (!authHeader) return null;
const lower = authHeader.toLowerCase();
if (!lower.startsWith("bearer ")) return null;
const token = authHeader.slice(7).trim();
if (!token) return null;
if (token.startsWith("glct_")) return loadUserFromOauthBearer(token);
if (token.startsWith("glc_")) return loadUserFromPat(token);
return null;
}
// --------------------------------------------------------------------------
// JSON-RPC helpers
// --------------------------------------------------------------------------
type JsonRpcId = string | number | null;
function rpcOk(id: JsonRpcId, result: unknown) {
return { jsonrpc: "2.0", id, result };
}
function rpcError(id: JsonRpcId, code: number, message: string, data?: unknown) {
const error: Record<string, unknown> = { code, message };
if (data !== undefined) error.data = data;
return { jsonrpc: "2.0", id, error };
}
// --------------------------------------------------------------------------
// Method handlers
// --------------------------------------------------------------------------
function handleInitialize() {
return {
protocolVersion: PROTOCOL_VERSION,
capabilities: {
tools: {},
resources: { subscribe: false },
},
serverInfo: SERVER_INFO,
};
}
function handleToolsList() {
return { tools: MCP_TOOLS.map(serializeTool) };
}
function handleResourcesList() {
return { resources: [] };
}
async function handleToolsCall(
params: Record<string, unknown>,
user: User | null
): Promise<unknown> {
const toolName = params.name as string | undefined;
if (!toolName) {
throw new McpToolError(E_INVALID_PARAMS, "params.name is required for tools/call");
}
const tool = MCP_TOOL_MAP.get(toolName);
if (!tool) {
throw new McpToolError(E_NOT_FOUND, `Unknown tool: '${toolName}'`);
}
const args = (params.arguments ?? {}) as Record<string, unknown>;
const result = await tool.handler(args, user);
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
}
// --------------------------------------------------------------------------
// POST /mcp — main JSON-RPC dispatcher
// --------------------------------------------------------------------------
mcp.post("/mcp", async (c) => {
// Resolve authenticated user (may be null for public requests)
const authHeader = c.req.header("authorization");
const user = await resolveUser(authHeader);
// Parse body
let body: Record<string, unknown>;
try {
body = await c.req.json();
} catch {
return c.json(rpcError(null, E_PARSE, "Parse error: invalid JSON"), 200);
}
// Validate JSON-RPC envelope
if (body.jsonrpc !== "2.0" || !body.method) {
return c.json(
rpcError(body.id as JsonRpcId ?? null, E_INVALID_REQUEST, "Invalid JSON-RPC request"),
200
);
}
const id = (body.id as JsonRpcId) ?? null;
const method = body.method as string;
const params = (body.params ?? {}) as Record<string, unknown>;
// Auth gate: tools/call that mutate or read private data require auth
// (public methods are allowed without a token)
if (!PUBLIC_METHODS.has(method) && method !== "tools/call") {
// Any unknown method — we'll return method-not-found below, not an auth error
}
// For tools/call: auth is enforced at the tool level (each tool decides)
// but we still need a user object passed through.
try {
let result: unknown;
switch (method) {
case "initialize":
result = handleInitialize();
break;
case "notifications/initialized":
// Client acknowledgement — no-op, return empty result
result = {};
break;
case "tools/list":
result = handleToolsList();
break;
case "tools/call":
result = await handleToolsCall(params, user);
break;
case "resources/list":
result = handleResourcesList();
break;
default:
return c.json(rpcError(id, E_METHOD_NOT_FOUND, `Method not found: '${method}'`), 200);
}
return c.json(rpcOk(id, result), 200);
} catch (err) {
if (err instanceof McpToolError) {
return c.json(rpcError(id, err.code, err.message), 200);
}
// Unexpected error
console.error("[mcp] unhandled error:", err);
return c.json(rpcError(id, E_INTERNAL, "Internal error"), 200);
}
});
// --------------------------------------------------------------------------
// GET /mcp — server discovery (no auth required)
// --------------------------------------------------------------------------
mcp.get("/mcp", async (c) => {
return c.json({
name: "gluecron",
version: "1.0.0",
description: "AI-native code intelligence platform",
transport: "http",
endpoint: "/mcp",
protocolVersion: PROTOCOL_VERSION,
tools: MCP_TOOLS.map((t) => ({
name: t.name,
description: t.description,
})),
});
});
export default mcp;
|