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

desk.ts

226 lines6.1 KB

1import { createMCPClient } from '@tanstack/ai-mcp'
2import type { Transport } from '@tanstack/ai-mcp'
3import {
4 createMCPEventWebhook,
5 MCP_EVENTS_EXTENSION,
6 inMemoryMCPEventStore,
7 signMCPEventPayload,
8} from '@tanstack/ai-mcp/events'
9import type { MCPEventOccurrence } from '@tanstack/ai-mcp/events'
10import { createServerFn } from '@tanstack/react-start'
11​
12type RpcMessage = Parameters<NonNullable<Transport['onmessage']>>[0]
13type RpcRequest = Extract<RpcMessage, { method: string }>
14​
15type StoredSub = {
16 id: string
17 name: string
18 url: string
19 secret: string
21​
22function isRecord(value: unknown): value is Record<string, unknown> {
23 return typeof value === 'object' && value !== null && !Array.isArray(value)
25​
26const handshakeResult = {
27 protocolVersion: '2025-11-25',
28 capabilities: {
29 extensions: {
30 [MCP_EVENTS_EXTENSION]: {},
31 },
32 },
33 serverInfo: { name: 'desk-events', version: '1.0.0' },
35​
36const catalog = {
37 events: [
38 {
39 name: 'incident.created',
40 delivery: ['webhook'],
41 inputSchema: { type: 'object' },
42 payloadSchema: true,
43 },
44 ],
46​
47const subscriptions = new Map<string, StoredSub>()
48const received: Array<MCPEventOccurrence> = []
49const store = inMemoryMCPEventStore()
50​
51const webhook = createMCPEventWebhook({
52 store,
53 onEvent: ({ event }) => {
54 received.push(event)
55 },
56 onError: (error) => console.error(error),
57})
58​
59function requestId(message: RpcRequest): string | number | undefined {
60 if (!('id' in message)) return undefined
61 return typeof message.id === 'string' || typeof message.id === 'number'
62 ? message.id
63 : undefined
65​
66function jsonRpcResult(
67 message: RpcRequest,
68 result: Record<string, unknown>,
69): RpcMessage | undefined {
70 const id = requestId(message)
71 if (id === undefined) return undefined
72 return { jsonrpc: '2.0', id, result }
74​
75function jsonRpcError(
76 message: RpcRequest,
77 code: number,
78 errorMessage: string,
79): RpcMessage | undefined {
80 const id = requestId(message)
81 if (id === undefined) return undefined
82 return {
83 jsonrpc: '2.0',
84 id,
85 error: { code, message: errorMessage },
86 }
88​
89function replyTo(message: RpcMessage): RpcMessage | undefined {
90 if (!('method' in message)) return undefined
91 const rpc: RpcRequest = message
92 if (rpc.method === 'initialize' || rpc.method === 'server/discover') {
93 return jsonRpcResult(rpc, handshakeResult)
94 }
95 if (rpc.method === 'ping') return jsonRpcResult(rpc, {})
96 if (rpc.method === 'notifications/initialized') return undefined
97 if (rpc.method === 'events/list') {
98 return jsonRpcResult(rpc, catalog)
99 }
100 if (rpc.method === 'events/subscribe') {
101 const params = isRecord(rpc.params) ? rpc.params : {}
102 const name = typeof params.name === 'string' ? params.name : ''
103 if (name !== 'incident.created') {
104 return jsonRpcError(rpc, -32023, 'Event not found')
105 }
106 const delivery = isRecord(params.delivery) ? params.delivery : {}
107 const { url, secret } = delivery
108 if (typeof url !== 'string' || typeof secret !== 'string') {
109 return jsonRpcError(rpc, -32602, 'delivery.url and secret are required')
110 }
111 const id = 'sub_desk'
112 subscriptions.set(id, { id, name, url, secret })
113 return jsonRpcResult(rpc, {
114 id,
115 refreshBefore: new Date(Date.now() + 3_600_000).toISOString(),
116 cursor: null,
117 truncated: false,
118 })
119 }
120 if (rpc.method === 'events/unsubscribe') {
121 subscriptions.delete('sub_desk')
122 return jsonRpcResult(rpc, {})
123 }
124 return jsonRpcError(rpc, -32601, 'Method not found')
126​
127function createDeskTransport(): Transport {
128 const transport: Transport = {
129 async start() {},
130 async close() {},
131 async send(message) {
132 const reply = replyTo(message)
133 if (reply !== undefined) {
134 transport.onmessage?.(reply)
135 }
136 },
137 }
138 return transport
140​
141export function handleWebhook(request: Request) {
142 return webhook(request)
144​
145async function signAndDeliver(sub: StoredSub, bodyObj: unknown) {
146 const raw = new TextEncoder().encode(JSON.stringify(bodyObj))
147 const timestamp = Math.floor(Date.now() / 1000)
148 const messageId =
149 isRecord(bodyObj) && typeof bodyObj.eventId === 'string'
150 ? bodyObj.eventId
151 : `msg_${crypto.randomUUID()}`
152 const signature = await signMCPEventPayload({
153 secret: sub.secret,
154 messageId,
155 timestamp,
156 body: raw,
157 })
158 const res = await webhook(
159 new Request(sub.url, {
160 method: 'POST',
161 headers: {
162 'content-type': 'application/json',
163 'webhook-id': messageId,
164 'webhook-timestamp': String(timestamp),
165 'webhook-signature': signature,
166 'x-mcp-subscription-id': sub.id,
167 },
168 body: raw,
169 }),
170 )
171 if (!res.ok) throw new Error(`Webhook rejected the delivery: ${res.status}`)
173​
174export type DeskSnapshot = {
175 names: Array<string>
176 subscriptionId: string | null
177 events: Array<MCPEventOccurrence>
179​
180export const subscribeDesk = createServerFn({ method: 'POST' }).handler(
181 async (): Promise<DeskSnapshot> => {
182 const client = await createMCPClient({
183 transport: createDeskTransport(),
184 experimental_events: { store },
185 })
186 try {
187 const listed = await client.experimental_events.list()
188 const sub = await client.experimental_events.subscribe({
189 name: 'incident.created',
190 delivery: {
191 mode: 'webhook',
192 url: 'http://127.0.0.1/api/mcp-events',
193 allowInsecureLocalhost: true,
194 },
195 })
196 return {
197 names: listed.map((event) => event.name),
198 subscriptionId: sub.id,
199 events: [...received],
200 }
201 } finally {
202 await client.close()
203 }
204 },
206​
207export const emitDesk = createServerFn({ method: 'POST' }).handler(
208 async (): Promise<DeskSnapshot> => {
209 const sub = subscriptions.get('sub_desk')
210 if (sub === undefined) {
211 throw new Error('Subscribe before you emit.')
212 }
213 const eventId = `evt_${crypto.randomUUID()}`
214 await signAndDeliver(sub, {
215 eventId,
216 name: 'incident.created',
217 timestamp: new Date().toISOString(),
218 data: { id: 'inc_desk', summary: 'Disk is full' },
219 })
220 return {
221 names: ['incident.created'],
222 subscriptionId: sub.id,
223 events: [...received],
224 }
225 },