|
| 1 | +/** |
| 2 | + * SSE endpoint for MCP tool-change events. |
| 3 | + * |
| 4 | + * Pushes `tools_changed` events to the browser when: |
| 5 | + * - An external MCP server sends `notifications/tools/list_changed` (via connection manager) |
| 6 | + * - A workflow CRUD route modifies workflow MCP server tools (via pub/sub) |
| 7 | + * |
| 8 | + * Auth is handled via session cookies (EventSource sends cookies automatically). |
| 9 | + */ |
| 10 | + |
| 11 | +import { createLogger } from '@sim/logger' |
| 12 | +import type { NextRequest } from 'next/server' |
| 13 | +import { getSession } from '@/lib/auth' |
| 14 | +import { SSE_HEADERS } from '@/lib/core/utils/sse' |
| 15 | +import { mcpConnectionManager } from '@/lib/mcp/connection-manager' |
| 16 | +import { mcpPubSub } from '@/lib/mcp/pubsub' |
| 17 | +import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' |
| 18 | + |
| 19 | +const logger = createLogger('McpEventsSSE') |
| 20 | + |
| 21 | +export const dynamic = 'force-dynamic' |
| 22 | + |
| 23 | +const HEARTBEAT_INTERVAL_MS = 30_000 |
| 24 | + |
| 25 | +export async function GET(request: NextRequest) { |
| 26 | + const session = await getSession() |
| 27 | + if (!session?.user?.id) { |
| 28 | + return new Response('Unauthorized', { status: 401 }) |
| 29 | + } |
| 30 | + |
| 31 | + const { searchParams } = new URL(request.url) |
| 32 | + const workspaceId = searchParams.get('workspaceId') |
| 33 | + if (!workspaceId) { |
| 34 | + return new Response('Missing workspaceId query parameter', { status: 400 }) |
| 35 | + } |
| 36 | + |
| 37 | + const permissions = await getUserEntityPermissions(session.user.id, 'workspace', workspaceId) |
| 38 | + if (!permissions) { |
| 39 | + return new Response('Access denied to workspace', { status: 403 }) |
| 40 | + } |
| 41 | + |
| 42 | + const encoder = new TextEncoder() |
| 43 | + const unsubscribers: Array<() => void> = [] |
| 44 | + |
| 45 | + const stream = new ReadableStream({ |
| 46 | + start(controller) { |
| 47 | + const send = (eventName: string, data: Record<string, unknown>) => { |
| 48 | + try { |
| 49 | + controller.enqueue( |
| 50 | + encoder.encode(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`) |
| 51 | + ) |
| 52 | + } catch { |
| 53 | + // Stream already closed |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + // Subscribe to external MCP server tool changes |
| 58 | + if (mcpConnectionManager) { |
| 59 | + const unsub = mcpConnectionManager.subscribe((event) => { |
| 60 | + if (event.workspaceId !== workspaceId) return |
| 61 | + send('tools_changed', { |
| 62 | + source: 'external', |
| 63 | + serverId: event.serverId, |
| 64 | + timestamp: event.timestamp, |
| 65 | + }) |
| 66 | + }) |
| 67 | + unsubscribers.push(unsub) |
| 68 | + } |
| 69 | + |
| 70 | + // Subscribe to workflow CRUD tool changes |
| 71 | + if (mcpPubSub) { |
| 72 | + const unsub = mcpPubSub.onWorkflowToolsChanged((event) => { |
| 73 | + if (event.workspaceId !== workspaceId) return |
| 74 | + send('tools_changed', { |
| 75 | + source: 'workflow', |
| 76 | + serverId: event.serverId, |
| 77 | + timestamp: Date.now(), |
| 78 | + }) |
| 79 | + }) |
| 80 | + unsubscribers.push(unsub) |
| 81 | + } |
| 82 | + |
| 83 | + // Heartbeat to keep the connection alive |
| 84 | + const heartbeat = setInterval(() => { |
| 85 | + try { |
| 86 | + controller.enqueue(encoder.encode(': heartbeat\n\n')) |
| 87 | + } catch { |
| 88 | + clearInterval(heartbeat) |
| 89 | + } |
| 90 | + }, HEARTBEAT_INTERVAL_MS) |
| 91 | + unsubscribers.push(() => clearInterval(heartbeat)) |
| 92 | + |
| 93 | + // Cleanup when client disconnects |
| 94 | + request.signal.addEventListener('abort', () => { |
| 95 | + for (const unsub of unsubscribers) { |
| 96 | + unsub() |
| 97 | + } |
| 98 | + try { |
| 99 | + controller.close() |
| 100 | + } catch { |
| 101 | + // Already closed |
| 102 | + } |
| 103 | + logger.info(`SSE connection closed for workspace ${workspaceId}`) |
| 104 | + }) |
| 105 | + |
| 106 | + logger.info(`SSE connection opened for workspace ${workspaceId}`) |
| 107 | + }, |
| 108 | + }) |
| 109 | + |
| 110 | + return new Response(stream, { headers: SSE_HEADERS }) |
| 111 | +} |
0 commit comments