Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

mcp-events-session.ts

117 lines3.5 KB

1import { createMCPClient } from '@tanstack/ai-mcp'
2import {
3 createMCPEventWebhook,
4 inMemoryMCPEventStore,
5} from '@tanstack/ai-mcp/events'
6import type { MCPClient } from '@tanstack/ai-mcp'
7import type { MCPEvents, MCPEventOccurrence } from '@tanstack/ai-mcp/events'
8// One SEP-3415 test server, shared with the ai-mcp unit tests on purpose.
9import {
10 createTestEventsServer,
11 eventsHttpFetch,
12} from '../../../../packages/ai-mcp/tests/helpers/events-server'
13​
14type EventsClient = MCPClient & { readonly experimental_events: MCPEvents }
15​
16type Session = {
17 store: ReturnType<typeof inMemoryMCPEventStore>
18 events: ReturnType<typeof createTestEventsServer>
19 mcpFetch: (request: Request) => Promise<Response>
20 webhook: (request: Request) => Promise<Response>
21 received: Array<MCPEventOccurrence>
22 gaps: Array<{ cursor: string }>
23 terminations: Array<{ code: number; message: string }>
24 errors: Array<string>
25 client?: EventsClient
27​
28const sessions = new Map<string, Session>()
29​
30function createSession(origin: string): Session {
31 const store = inMemoryMCPEventStore()
32 const received: Array<MCPEventOccurrence> = []
33 const gaps: Array<{ cursor: string }> = []
34 const terminations: Array<{ code: number; message: string }> = []
35 const errors: Array<string> = []
36 const webhook = createMCPEventWebhook({
37 store,
38 onEvent: ({ event }) => {
39 received.push(event)
40 },
41 onGap: ({ gap }) => {
42 gaps.push(gap)
43 },
44 onTerminated: ({ termination }) => {
45 terminations.push({
46 code: termination.code,
47 message: termination.message,
48 })
49 },
50 onError: (error) => {
51 errors.push(`${error.stage}: ${error.message}`)
52 },
53 })
54 const events = createTestEventsServer({
55 // The client only accepts a 127.0.0.1 http callback, but Vite may bind
56 // `localhost` to IPv6 only. Post to the same path on the app origin so
57 // each delivery goes over HTTP through the webhook route.
58 deliver: async (request) => {
59 const url = new URL(request.url)
60 return fetch(`${origin}${url.pathname}${url.search}`, {
61 method: 'POST',
62 headers: request.headers,
63 body: await request.arrayBuffer(),
64 })
65 },
66 allowHttpLoopback: true,
67 verify: 'challenge',
68 ttlMs: { default: 60_000, min: 1 },
69 maxAttempts: 3,
70 })
71 return {
72 store,
73 events,
74 mcpFetch: eventsHttpFetch(events),
75 webhook,
76 received,
77 gaps,
78 terminations,
79 errors,
80 }
82​
83export function getMcpEventsSession(id: string, origin: string): Session {
84 const existing = sessions.get(id)
85 if (existing) return existing
86 const created = createSession(origin)
87 sessions.set(id, created)
88 return created
90​
91export async function resetMcpEventsSession(id: string): Promise<void> {
92 const existing = sessions.get(id)
93 if (existing?.client) await existing.client.close().catch(() => undefined)
94 sessions.delete(id)
96​
97export async function mcpEventsClient(
98 session: Session,
99 origin: string,
100 sessionId: string,
101): Promise<EventsClient> {
102 if (!session.client) {
103 session.client = await createMCPClient({
104 transport: {
105 type: 'http',
106 url: `${origin}/api/mcp-events-server?session=${encodeURIComponent(sessionId)}`,
107 },
108 experimental_events: { store: session.store },
109 })
110 }
111 return session.client
113​
114export function sessionIdFromRequest(request: Request): string | undefined {
115 const value = new URL(request.url).searchParams.get('session')
116 return value === null || value === '' ? undefined : value