Open History to see the last commit
1---
2title: Subscribe to MCP Events
3id: subscribe-mcp-events
4order: 6
5description: "Subscribe to an MCP Events webhook in a TanStack Start app and receive a signed delivery."
6keywords:
7 - tanstack ai
8 - tutorial
9 - mcp
10 - mcp events
11 - webhook
12 - sep-3415
13 - tanstack start
14---
15
16An MCP server can push work to you: a new incident, a finished job. Polling that server is slow and easy to miss.
17
18This tutorial subscribes to `incident.created` from a TanStack Start app. A POST route verifies the Standard Webhooks signature with `createMCPEventWebhook`. The page then shows the event.
19
20The sample app also hosts a small in-process MCP Events server so you can emit a delivery without a live remote. Production apps subscribe to the real server over HTTP.
21
22The short guide is [MCP Events](../tools/mcp-events).
23
24## 1. Create a Start app
25
26```bash
27npx @tanstack/cli@latest create
28```
29
30Pick React. For more options, see [Start getting started](https://tanstack.com/start/latest/docs/framework/react/quick-start).
31
32Then install this package:
33
34<!-- ::start:tabs variant="package-manager" mode="install" -->
35
36react: @tanstack/ai-mcp
37
38<!-- ::end:tabs -->
39
40## The webhook, the helper, and the page
41
42The webhook route is the callback URL you pass to `subscribe`.
43
44The helper file keeps the store, the webhook handler, and a loopback MCP Events server.
45
46The page calls subscribe, then emit, and shows the verified event.
47
48## 2. Receive the webhook
49
50Create `src/routes/api.mcp-events.ts`.
51
52`createMCPEventWebhook` reads the raw body and checks the HMAC. Do not parse JSON and stringify it again.
53
54```ts ignore
55import { createFileRoute } from '@tanstack/react-router'
56import { handleWebhook } from '../lib/desk'
57
58export const Route = createFileRoute('/api/mcp-events')({
59 server: {
60 handlers: {
61 POST: ({ request }) => handleWebhook(request),
62 },
63 },
64})
65```
66
67## 3. Subscribe and emit
68
69Create `src/lib/desk.ts`. Copy it from the example app.
70
71That file does three jobs:
72
73- Share one `inMemoryMCPEventStore` between subscribe and the webhook.
74- Host a small MCP Events server so you can click Emit without a remote.
75- Sign a Standard Webhooks body and pass it to `createMCPEventWebhook`.
76
77`subscribeDesk` uses a loopback `Transport` so the page does not fetch itself. Use `allowInsecureLocalhost: true` only for `http://127.0.0.1` in local tests.
78
79`inMemoryMCPEventStore` is for this sample. Put a durable store in production.
80
81The subscribe call inside `subscribeDesk` is:
82
83```ts ignore
84const sub = await client.experimental_events.subscribe({
85 name: 'incident.created',
86 delivery: {
87 mode: 'webhook',
88 url: 'http://127.0.0.1/api/mcp-events',
89 allowInsecureLocalhost: true,
90 },
91})
92```
93
94## 4. Show the event
95
96Create `src/routes/index.tsx`.
97
98The page calls `subscribeDesk`, then `emitDesk`, and prints the last verified event.
99
100```tsx ignore
101import { createFileRoute } from '@tanstack/react-router'
102import { useState } from 'react'
103import { emitDesk, subscribeDesk } from '@/lib/desk'
104import type { DeskSnapshot } from '@/lib/desk'
105
106function McpEventsPage() {
107 const [snapshot, setSnapshot] = useState<DeskSnapshot | null>(null)
108 const [error, setError] = useState('')
109 const [pending, setPending] = useState<'subscribe' | 'emit' | ''>('')
110
111 async function onSubscribe() {
112 setError('')
113 setPending('subscribe')
114 try {
115 setSnapshot(await subscribeDesk())
116 } catch (caught) {
117 setSnapshot(null)
118 setError(caught instanceof Error ? caught.message : 'Subscribe failed.')
119 } finally {
120 setPending('')
121 }
122 }
123
124 async function onEmit() {
125 setError('')
126 setPending('emit')
127 try {
128 setSnapshot(await emitDesk())
129 } catch (caught) {
130 setError(caught instanceof Error ? caught.message : 'Emit failed.')
131 } finally {
132 setPending('')
133 }
134 }
135
136 const last = snapshot?.events[snapshot.events.length - 1]
137
138 return (
139 <main className="mx-auto max-w-2xl p-6">
140 <h1 className="mb-2 text-3xl font-bold text-white">Incident desk</h1>
141 <p className="mb-6 text-gray-300">
142 Subscribe to <code>incident.created</code>, then emit a signed webhook.
143 This page shows the event that <code>createMCPEventWebhook</code>{' '}
144 verified.
145 </p>
146 <div className="flex gap-3">
147 <button
148 type="button"
149 className="rounded bg-white px-4 py-2 font-semibold text-gray-900 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white disabled:opacity-60"
150 disabled={pending !== ''}
151 onClick={() => {
152 void onSubscribe()
153 }}
154 >
155 {pending === 'subscribe' ? 'Subscribing' : 'Subscribe'}
156 </button>
157 <button
158 type="button"
159 className="rounded bg-emerald-400 px-4 py-2 font-semibold text-gray-900 focus-visible:outline focus-visible:outline-offset-2 focus-visible:outline-white disabled:opacity-60"
160 disabled={pending !== '' || snapshot === null}
161 onClick={() => {
162 void onEmit()
163 }}
164 >
165 {pending === 'emit' ? 'Emitting' : 'Emit incident'}
166 </button>
167 </div>
168 {error !== '' ? (
169 <p className="mt-4 text-red-300" role="alert">
170 {error}
171 </p>
172 ) : null}
173 {snapshot !== null ? (
174 <div className="mt-8 space-y-6 text-gray-100">
175 <section>
176 <h2 className="text-xl font-semibold">Catalog</h2>
177 <p>{snapshot.names.join(', ')}</p>
178 </section>
179 <section>
180 <h2 className="text-xl font-semibold">Subscription</h2>
181 <p>{snapshot.subscriptionId ?? 'none'}</p>
182 </section>
183 <section>
184 <h2 className="text-xl font-semibold">Last event</h2>
185 {last === undefined ? (
186 <p>No delivery yet. Click Emit incident.</p>
187 ) : (
188 <pre className="whitespace-pre-wrap rounded bg-gray-800 p-4">
189 {JSON.stringify(last, null, 2)}
190 </pre>
191 )}
192 </section>
193 </div>
194 ) : null}
195 </main>
196 )
197}
198
199export const Route = createFileRoute('/')({
200 component: McpEventsPage,
201})
202```
203
204## 5. Run the app
205
2061. In the app folder, run `pnpm dev`.
2072. Open http://127.0.0.1:3101.
2083. Click Subscribe, then Emit incident.
209
210The page shows `incident.created`, a subscription id, and the verified payload with `id: "inc_desk"`.
211
212<!-- ::client-example library=ai framework=react slug=mcp-events -->
213
214The full example is on GitHub: [TanStack/ai `examples/react/mcp-events`](https://github.com/TanStack/ai/tree/main/examples/react/mcp-events).
215
216For leases, gaps, and status codes, open [MCP Events](../tools/mcp-events).