-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathroute.ts
More file actions
141 lines (124 loc) · 5.8 KB
/
route.ts
File metadata and controls
141 lines (124 loc) · 5.8 KB
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
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { createMcpServer } from '@/features/mcp/server';
import { withOptionalAuth } from '@/middleware/withAuth';
import { isServiceError } from '@/lib/utils';
import { notAuthenticated, serviceErrorResponse, ServiceError } from '@/lib/serviceError';
import { ErrorCode } from '@/lib/errorCodes';
import { StatusCodes } from 'http-status-codes';
import { NextRequest } from 'next/server';
import { sew } from "@/middleware/sew";
import { apiHandler } from '@/lib/apiHandler';
import { env, hasEntitlement } from '@sourcebot/shared';
// On 401, tell MCP clients where to find the OAuth protected resource metadata (RFC 9728)
// so they can discover the authorization server and initiate the authorization code flow.
// Only advertised when the oauth entitlement is active.
// @see: https://modelcontextprotocol.io/specification/2025-03-26/basic/authentication
// @see: https://datatracker.ietf.org/doc/html/rfc9728
function mcpErrorResponse(error: ServiceError): Response {
const response = serviceErrorResponse(error);
if (error.statusCode === StatusCodes.UNAUTHORIZED && hasEntitlement('oauth')) {
const issuer = env.AUTH_URL.replace(/\/$/, '');
response.headers.set(
'WWW-Authenticate',
`Bearer realm="Sourcebot", resource_metadata_uri="${issuer}/.well-known/oauth-protected-resource/api/mcp"`
);
}
return response;
}
// @see: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management
interface McpSession {
server: McpServer;
transport: WebStandardStreamableHTTPServerTransport;
ownerId: string | null; // null for anonymous sessions
}
const MCP_SESSION_ID_HEADER = 'MCP-Session-Id';
// Module-level session store. Persists across requests within the same Node.js process.
// Suitable for containerized/single-instance deployments.
const sessions = new Map<string, McpSession>();
export const POST = apiHandler(async (request: NextRequest) => {
const response = await sew(() =>
withOptionalAuth(async ({ user }) => {
if (env.EXPERIMENT_ASK_GH_ENABLED === 'true' && !user) {
return notAuthenticated();
}
const ownerId = user?.id ?? null;
const sessionId = request.headers.get(MCP_SESSION_ID_HEADER);
// Return existing session if available
if (sessionId && sessions.has(sessionId)) {
const session = sessions.get(sessionId)!;
if (session.ownerId !== ownerId) {
return {
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS,
message: 'Session does not belong to the authenticated user.',
} satisfies ServiceError;
}
return session.transport.handleRequest(request);
}
// Create a new session
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: () => crypto.randomUUID(),
onsessioninitialized: (newSessionId) => {
sessions.set(newSessionId, { server: mcpServer, transport, ownerId });
},
onsessionclosed: async (closedSessionId) => {
const session = sessions.get(closedSessionId);
if (session) {
await session.server.close();
await session.transport.close();
}
sessions.delete(closedSessionId);
},
});
const mcpServer = await createMcpServer({ userId: user?.id });
await mcpServer.connect(transport);
return transport.handleRequest(request);
})
);
if (isServiceError(response)) {
return mcpErrorResponse(response);
}
return response;
});
export const DELETE = apiHandler(async (request: NextRequest) => {
const result = await sew(() =>
withOptionalAuth(async ({ user }) => {
if (env.EXPERIMENT_ASK_GH_ENABLED === 'true' && !user) {
return notAuthenticated();
}
const ownerId = user?.id ?? null;
const sessionId = request.headers.get(MCP_SESSION_ID_HEADER);
if (!sessionId || !sessions.has(sessionId)) {
return {
statusCode: StatusCodes.NOT_FOUND,
errorCode: ErrorCode.NOT_FOUND,
message: 'Session not found.',
} satisfies ServiceError;
}
const session = sessions.get(sessionId)!;
if (session.ownerId !== ownerId) {
return {
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS,
message: 'Session does not belong to the authenticated user.',
} satisfies ServiceError;
}
return session.transport.handleRequest(request);
})
);
if (isServiceError(result)) {
return mcpErrorResponse(result);
}
return result;
});
// Sourcebot does not send server-initiated messages, so the GET SSE stream is not
// supported. Per the MCP Streamable HTTP spec, servers that do not offer a GET SSE
// stream MUST return 405 Method Not Allowed.
// @see: https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#listening-for-messages-from-the-server
export const GET = apiHandler(async (_request: NextRequest) => {
return new Response(null, {
status: StatusCodes.METHOD_NOT_ALLOWED,
headers: { Allow: 'POST, DELETE' },
});
});