Fix Claude Desktop MCP handshake on /mcp.

GET holds a short SSE stream, auth failures return JSON-RPC 401, and OAuth discovery advertises bearer-only.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Towsty
2026-11-02 22:00:29 -06:00
co-authored by Cursor
parent 96776ed493
commit 1834ac4af9
6 changed files with 105 additions and 30 deletions
+22 -9
View File
@@ -1,12 +1,14 @@
import { assertAigenApiAccess } from '~/server/utils/aigenApi'
import {
MCP_PROTOCOL_VERSION,
MCP_SERVER_INFO,
MCP_TOOLS,
applyMcpCors,
callMcpTool,
jsonRpcError,
jsonRpcResult
jsonRpcResult,
mcpAssertAccess,
mcpBearerOk,
mcpUnauthorized,
resolveMcpProtocolVersion
} from '~/server/utils/aigenMcp'
export default defineEventHandler(async (event) => {
@@ -19,17 +21,28 @@ export default defineEventHandler(async (event) => {
}
if (method === 'GET') {
setResponseHeader(event, 'Allow', 'POST')
throw createError({ statusCode: 405, statusMessage: 'Method Not Allowed' })
if (!mcpBearerOk(event)) {
return mcpUnauthorized(event)
}
setResponseStatus(event, 200)
setResponseHeader(event, 'Content-Type', 'text/event-stream')
setResponseHeader(event, 'Cache-Control', 'no-cache, no-transform')
setResponseHeader(event, 'Connection', 'keep-alive')
// Short SSE stream Claude opens after initialize; comment then end.
return ': connected\n\n'
}
if (method !== 'POST') {
setResponseHeader(event, 'Allow', 'POST')
setResponseHeader(event, 'Allow', 'GET, POST, OPTIONS')
throw createError({ statusCode: 405, statusMessage: 'Method Not Allowed' })
}
setResponseHeader(event, 'Content-Type', 'application/json')
assertAigenApiAccess(event)
if (!mcpBearerOk(event)) {
return mcpUnauthorized(event)
}
mcpAssertAccess(event)
let body: any
try {
@@ -49,6 +62,7 @@ export default defineEventHandler(async (event) => {
const rpcMethod = String(body.method || '')
const id = Object.prototype.hasOwnProperty.call(body, 'id') ? body.id : undefined
const isNotification = id === undefined
const params = body.params && typeof body.params === 'object' ? body.params as Record<string, unknown> : {}
if (rpcMethod === 'notifications/initialized') {
setResponseStatus(event, 202)
@@ -57,7 +71,7 @@ export default defineEventHandler(async (event) => {
if (rpcMethod === 'initialize') {
return jsonRpcResult(id, {
protocolVersion: MCP_PROTOCOL_VERSION,
protocolVersion: resolveMcpProtocolVersion(params.protocolVersion),
capabilities: { tools: {} },
serverInfo: MCP_SERVER_INFO
})
@@ -72,7 +86,6 @@ export default defineEventHandler(async (event) => {
}
if (rpcMethod === 'tools/call') {
const params = body.params && typeof body.params === 'object' ? body.params as Record<string, unknown> : {}
const name = String(params.name || '')
const args = params.arguments && typeof params.arguments === 'object' && !Array.isArray(params.arguments)
? params.arguments as Record<string, unknown>