# How to Add MCP Events to an mcp-handler Server: Storage and Webhook Delivery

> **Source:** https://upstash.com/kb/mcp-handler-events-storage-delivery
> **Date:** 2026-11-23
> **Author(s):** Cahid Arda Oz
> **Topic:** Redis
> **Format:** text/markdown, machine-readable content for agents and LLMs

mcp-handler registers the MCP Events methods but leaves subscription storage and webhook delivery to you. This shows how to write both adapters, with Redis for storage and QStash for signed, retried delivery, and runs them with a real MCP client.

---

ChatGPT [can subscribe](https://developers.openai.com/plugins/build/mcp-events) to events from an MCP server and run actions when they occur. The server takes a callback URL and signing secret from ChatGPT and POSTs a signed event every time there is a match.

As of [version 2.3.0](https://github.com/vercel-labs/mcp-handler/releases/tag/v2.3.0), Vercel's mcp-handler exposes a helper function `experimental_registerMcpEvents` to respond to the three event methods on the same route as your tools. It doesn't actually store a subscription or deliver a webhook, though; its [docs](https://github.com/vercel-labs/mcp-handler/blob/main/docs/MCP_EVENTS.md) import its backend from a file called `./events-backend`, labeled "application code, not an included adapter." The repo contains only an in-memory test fixture.

This implementation can use any key-value store that supports expiration and compare-and-set and any message queue that retries. In the remainder of this post we will use Upstash Redis for subscriptions and QStash for message delivery. We provide most of the implementation details below and run it with Redis, QStash and an actual MCP client in the last section.

## What mcp-handler does and what it leaves to you

The helper owns the protocol side. You pass it your event definitions, a function that names the caller, and two adapters. Everything that touches storage or the network is yours:

| Piece | Who does it |
| --- | --- |
| `events/list`, `events/subscribe`, `events/unsubscribe` | mcp-handler |
| Checking arguments against the event's schema, the `whsec_` secret and the callback URL format | mcp-handler |
| A stable subscription ID from the user, callback URL, event and arguments | mcp-handler |
| Granting a lifetime (1 hour by default, 1 day at most) | mcp-handler |
| Storing subscriptions so they survive restarts | you: the `subscriptions` adapter |
| Sending the signed challenge that proves the callback is real | you: the `delivery` adapter |
| Finding the subscriptions that match an event | you |
| Signing, sending and retrying each delivery | you |

There is a strict contract on these adapters. On a subscribe, mcp-handler runs `prepare`, `verifyEndpoint`, and `upsert`. `upsert` cannot save if the operation token returned by `prepare` is no longer the current operation, which prevents slow subscribes from resurrecting cancelled subscriptions.

## How the pieces fit

ChatGPT subscribes using the MCP route, which creates the subscription in Redis with the encrypted secret. At this point, your app can call `emit()` when something happens. This reads the subscriptions from Redis and publishes a message to QStash for each one. QStash triggers a delivery route on your server, which signs the event and makes a POST request to ChatGPT:

![](https://cdn.bydefault.so/image-MgUWrkQ4w-miErUfhvuq_.png)

This round trip is necessary for a few reasons. Standard Webhooks signatures include the message ID, timestamp of the attempt and the body. Each retry [gets a new attempt timestamp](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md) to let receivers reject replays. OpenAI asks servers to [re-sign every retry](https://developers.openai.com/plugins/build/mcp-events) using a new timestamp.

The signature can't be generated at the time of the event because it might be outdated when QStash retries with backoff. It can't be generated in QStash without making the subscriber's secret available there.

The subscriber delivery route can also make checks at the time of delivery. Is the subscription expired? Does the user still have access? Does ChatGPT return 410, meaning it unsubscribed? QStash doesn't understand these responses, so the route maps them to "done" or "retry".

## Store subscriptions in Redis

For the implementation, we can translate these three adapter methods to the following simple Redis operations:

1. `prepare` stores a random operation token with an expiration time of 60 seconds.
2. `upsert` uses a Lua script to store the record if the operation token remains in Redis. It also deletes the operation token.
3. `remove` deletes the operation token, the record, and the index entry. It always returns `true`.

Subscriptions themselves take two Redis keys: one for the JSON payload and one for the entry in a sorted set per event. The sorted set is ranked by expiry time, allowing easy range queries from "now" to the end. These entries both automatically expire if ChatGPT stops refreshing them.

We use AES-GCM, an encryption mode that also detects tampering, to encrypt the signing secret (the sensitive bit that would allow events to be forged to this callback) before storing it in Redis. We pass the subscription ID as extra authenticated data to prevent ciphertext from being copied onto another record.

Here are the three methods. The `seal`/`open` encryption helpers and the lookup that `emit()` uses live in the same file:

```ts
// lib/redis-store.ts (excerpt)
import { randomUUID } from 'node:crypto'
import { Redis } from '@upstash/redis'
import type { ExperimentalMcpSubscriptionKey, ExperimentalMcpWebhookSubscription } from 'mcp-handler'

const redis = Redis.fromEnv()
export const key = (kind: 'op' | 'sub' | 'idx', id: string) => `mcp-events:${kind}:${id}`

async function prepare(sub: ExperimentalMcpSubscriptionKey) {
  const operationId = randomUUID()
  await redis.set(key('op', sub.id), operationId, { px: 60_000 })
  return operationId
}

const commit = `#!lua flags=allow-key-locking
if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end
redis.call('SET', KEYS[2], ARGV[2], 'PXAT', ARGV[3])
redis.call('ZADD', KEYS[3], ARGV[3], ARGV[4])
redis.call('DEL', KEYS[1])
return 1`

async function upsert(sub: ExperimentalMcpWebhookSubscription, _ctx: unknown, operationId: string) {
  const expiresAt = Date.parse(sub.refreshBefore!) // mcp-handler grants a finite expiry by default
  const record = { ...sub, secret: await seal(sub.secret, sub.id) }
  const ok = await redis.eval(commit,
    [key('op', sub.id), key('sub', sub.id), key('idx', sub.name)],
    [operationId, JSON.stringify(record), expiresAt, sub.id])
  if (ok !== 1) throw new Error('Subscription operation is no longer current')
  return { cursor: null, truncated: false }
}

const unsubscribe = `#!lua flags=allow-key-locking
redis.call('DEL', KEYS[1], KEYS[2])
redis.call('ZREM', KEYS[3], ARGV[1])
return 1`

async function remove(sub: ExperimentalMcpSubscriptionKey) {
  await redis.eval(unsubscribe, [key('op', sub.id), key('sub', sub.id), key('idx', sub.name)], [sub.id])
  return true // ChatGPT expects unsubscribe to succeed every time
}

export const subscriptions = { prepare, upsert, remove }
```

Both scripts start with `#!lua flags=allow-key-locking`. By default a Lua script on Upstash Redis takes a lock on the whole database, because the engine can't know which keys it will touch. With the flag, it [locks only the keys passed in `KEYS`](https://upstash.com/docs/redis/features/key-locking#lua-scripts), so the rest of your app's Redis traffic keeps running while they do. Subscribes to the same event still wait for each other, because they all write that event's index key. This works because every key the scripts use is in `KEYS`. Global and Fly databases also have a [Lua Strict Key Locking](https://upstash.com/docs/redis/features/key-locking#lua-strict-key-locking) setting that applies the same rule to every script without the flag.

The requirement that reservations be reclaimed after crashes is also handled by Redis expiry: reservations expire in 60 seconds if they are not completed. The `remove` operation can always return `true`, even if there's no match, to ensure unsubscribe is successful, as [ChatGPT expects](https://developers.openai.com/plugins/build/mcp-events).

The scenario to watch out for is this:

![](https://cdn.bydefault.so/image-TJD3Y0hLAqxo8le3glAQX.png)

This is why the `upsert` script verifies that the operation token matches the one received from `prepare` before upserting the record.

## Verify the callback before storing it

Servers must verify callback URLs belong to the subscriber before sending real data. ChatGPT sends a [signed POST](https://developers.openai.com/plugins/build/mcp-events) containing `{"type":"verification","challenge":"..."}` then expects the challenge echoed back. In mcp-handler, `verifyEndpoint` is invoked between `prepare` and `upsert` so invalid callbacks are never stored.

Both the challenge and real events go through one `signedPost` helper. It signs with the `standardwebhooks` package, sets the `webhook-id`, `webhook-timestamp`, `webhook-signature` and `X-MCP-Subscription-Id` headers, never follows redirects and gives up after 10 seconds. The check itself:

```ts
// lib/webhooks.ts (excerpt)
import { randomUUID } from 'node:crypto'
import type { ExperimentalMcpWebhookDelivery } from 'mcp-handler'

export const verifyEndpoint: ExperimentalMcpWebhookDelivery['verifyEndpoint'] = async (target) => {
  const challenge = randomUUID()
  try {
    const res = await signedPost(target, `msg_verification_${randomUUID()}`, JSON.stringify({ type: 'verification', challenge }))
    if (!res.ok) return { verified: false, reason: res.status >= 500 ? 'http_5xx' : 'http_4xx' }
    const reply = await res.json() as { challenge?: string }
    return reply.challenge === challenge ? { verified: true } : { verified: false, reason: 'challenge_failed' }
  } catch {
    return { verified: false, reason: 'connection_refused' }
  }
}
```

The same file exports `sendEvent`, which calls `signedPost` with the event envelope and returns the status code.

mcp-handler blocks `http://` callbacks before calling the adapter. This applies even on localhost, so tests will need a localhost listener with HTTPS.

`signedPost` also refuses IP addresses and `localhost` as callback hosts, but a public name can still resolve to a private address. OpenAI suggests that servers [verify the resolved address on connect](https://developers.openai.com/plugins/build/mcp-events) and block private addresses. This will require egress filtering in front of `fetch` in production.

If the check fails, the adapter returns a reason such as `http_4xx` or `challenge_failed`. mcp-handler passes this to ChatGPT as a `-32015` error and discards the rest, preventing leak of response text from the callback.

## Emit an event and deliver it through QStash

The example event is `deploy.finished`. A subscriber picks a project, and only the project's owner may subscribe. The definition is plain mcp-handler, with zod schemas for the arguments and the payload:

```ts
// lib/events.ts
import { z } from 'zod'
import type {
  ExperimentalMcpEventAuthorizationContext,
  ExperimentalMcpEventDefinition,
} from 'mcp-handler'

const owners: Record<string, string> = { web: 'alice', api: 'bob' }

export const deployPayload = z.object({
  project: z.string(),
  status: z.enum(['ready', 'error']),
  url: z.string(),
})

function ownsProject(args: Record<string, unknown>, context: ExperimentalMcpEventAuthorizationContext) {
  return typeof args.project === 'string' && owners[args.project] === context.principal
}

export const deployFinished: ExperimentalMcpEventDefinition = {
  name: 'deploy.finished',
  description: 'A deployment finished in a project you own.',
  inputSchema: z.strictObject({ project: z.string() }),
  payloadSchema: deployPayload,
  authorize: ownsProject,
}
```

Your app calls `emitDeployFinished()` wherever the event happens, such as the end of a deploy job. It builds the envelope ChatGPT expects and publishes one QStash message per matching subscription:

```ts
// lib/emit.ts
import { randomUUID } from 'node:crypto'
import { Client } from '@upstash/qstash'
import type { z } from 'zod'
import { deployPayload } from './events.js'
import { findSubscriptions } from './redis-store.js'

export type EventEnvelope = {
  eventId: string
  name: string
  timestamp: string
  data: z.infer<typeof deployPayload>
  cursor: null
}

const qstash = new Client({ token: process.env.QSTASH_TOKEN!, baseUrl: process.env.QSTASH_URL })

export async function emitDeployFinished(payload: z.infer<typeof deployPayload>) {
  const data = deployPayload.parse(payload)
  const envelope: EventEnvelope = {
    eventId: `evt_${randomUUID()}`, // stays the same across retries
    name: 'deploy.finished',
    timestamp: new Date().toISOString(),
    data,
    cursor: null,
  }
  const matches = (await findSubscriptions('deploy.finished')).filter(sub => sub.arguments.project === data.project)
  for (const sub of matches) {
    await qstash.publishJSON({ url: process.env.DELIVERY_URL!, body: { subscriptionId: sub.id, envelope }, retries: 3 })
  }
  return matches.length
}
```

The message to QStash only contains the ID of the subscription and the envelope. The secret remains encrypted in Redis until we send it.

QStash then calls the delivery route. The route checks QStash's own signature first, so nobody else can make your server send events. Then it loads the subscription and runs mcp-handler's `experimental_validateMcpEventDelivery`, which checks the expiry and the payload schema and calls `authorize` again. A user who lost access to the project stops getting events here, even though their subscription is still in Redis:

```ts
// lib/deliver.ts
import { Receiver } from '@upstash/qstash'
import { ExperimentalMcpEventDeliveryError, experimental_validateMcpEventDelivery } from 'mcp-handler'
import { deployFinished } from './events.js'
import type { EventEnvelope } from './emit.js'
import { getSubscription, open, subscriptions } from './redis-store.js'
import { sendEvent } from './webhooks.js'

const receiver = new Receiver({
  currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY!,
  nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY!,
})

export async function deliver(request: Request) {
  const body = await request.text()
  const signature = request.headers.get('upstash-signature') ?? ''
  if (!await receiver.verify({ signature, body }).catch(() => false)) {
    return new Response('Invalid signature', { status: 401 })
  }
  const { subscriptionId, envelope } = JSON.parse(body) as { subscriptionId: string, envelope: EventEnvelope }
  const stored = await getSubscription(subscriptionId)
  try {
    // Checks the expiry and the payload schema, and runs authorize() again.
    await experimental_validateMcpEventDelivery({ event: deployFinished, subscription: stored, payload: envelope.data })
  } catch (error) {
    if (error instanceof ExperimentalMcpEventDeliveryError) return new Response() // nothing to send
    throw error // a backend error: QStash retries
  }
  const status = await sendEvent(await open(stored!), envelope)
  if (status === 410) await subscriptions.remove(stored!)
  const done = (status >= 200 && status < 300) || status === 410 || status === 413
  return new Response(null, { status: done ? 200 : 500 })
}
```

The status the route returns is how it talks to QStash:

| ChatGPT's answer | Route returns | QStash does |
| --- | --- | --- |
| 2xx | 200 | Stops. The event is delivered. |
| 410 (subscription gone) | 200, after deleting the subscription | Stops. |
| 413 (payload too large) | 200 | Stops. Retrying would fail the same way. |
| Anything else, or no answer | 500 | [Retries with backoff](https://upstash.com/docs/qstash/features/retry), up to 3 times: after 12 seconds, 2.5 minutes and 30 minutes. |
| Subscription expired, removed or no longer authorized | 200 | Stops. Nothing is sent. |

The table incorporates several of OpenAI's recommendations, like [not retrying 410 or 413](https://developers.openai.com/plugins/build/mcp-events).

## Mount it in mcp-handler

The server file passes the event, the Redis adapter and the callback check to `experimental_registerMcpEvents`. It also mounts the delivery route that QStash calls. The example uses Hono on Node. Both handlers take a web `Request` and return a `Response`, so they move to other frameworks with little change:

```ts
// server.ts (excerpt)
import type { AuthInfo, McpServer } from '@modelcontextprotocol/server'
import { createMcpHandler, experimental_registerMcpEvents, withMcpAuth } from 'mcp-handler'
import { deployFinished } from './lib/events.js'
import { subscriptions } from './lib/redis-store.js'
import { verifyEndpoint } from './lib/webhooks.js'

function registerEvents(server: McpServer) {
  experimental_registerMcpEvents(server, {
    events: [deployFinished],
    getPrincipal,
    subscriptions,
    delivery: { verifyEndpoint },
  })
}

function getPrincipal(auth: AuthInfo) {
  const subject = auth.extra?.sub
  if (typeof subject !== 'string' || !subject) throw new Error('Missing subject')
  return subject
}

const mcp = withMcpAuth(createMcpHandler(registerEvents), verifyToken, { required: true })
```

The rest of the file is routing: `/mcp` goes to `mcp`, and `/api/mcp-events/deliver` goes to `deliver`.

The server-side implementation has a demo function `verifyToken` that accepts any `user:<name>` token. You should use some actual verification of tokens in your own server. Your `getPrincipal` function must use that verified token to identify who owns the subscription, and you use that to create a subscription ID.

The server reads these environment variables:

| Variable | What it is |
| --- | --- |
| `UPSTASH_REDIS_REST_URL`, `UPSTASH_REDIS_REST_TOKEN` | The Redis database for subscriptions |
| `QSTASH_TOKEN` | Publishes delivery messages |
| `QSTASH_CURRENT_SIGNING_KEY`, `QSTASH_NEXT_SIGNING_KEY` | Checks that a delivery request came from QStash |
| `DELIVERY_URL` | The public URL of `/api/mcp-events/deliver` |
| `MCP_EVENTS_SECRET_KEY` | 32 random bytes in base64, from `openssl rand -base64 32` |

## Run it end to end

We hosted the server in an [Upstash Box](https://upstash.com/docs/box/overall/getstarted) with a public HTTPS preview URL, connecting to a live Upstash Redis database and live QStash. We used a real MCP client: the AI SDK's `createMCPClient` with [experimental events support](https://ai-sdk.dev/cookbook/node/mcp-events). It received events via the `experimental_createMCPEventWebhook` handler, also exposed via a public URL, responding to the challenge and verifying each event's signature. For the retry step we put a lightweight wrapper in front of this, returning 503 once.

The client side is short:

```ts
// test/live-client.ts (excerpt)
const alice = await client('alice')
const { events } = await alice.experimental_events.list()
console.log('1. events/list:', events.map(e => `${e.name} (delivery: ${e.delivery.join(',')})`).join('; '))

const sub = await alice.experimental_events.subscribe({
  name: 'deploy.finished', arguments: { project: 'web' },
  delivery: { mode: 'webhook', url: CALLBACK },
})
```

The script then emits events from the app side, makes the receiver fail once, tries to subscribe as Mallory, and unsubscribes. This is the output:

```text
1. events/list: deploy.finished (delivery: webhook)
2. events/subscribe (callback verified): {"id":"sub_ac69046b8fbf5f6e121797b28fbb4274481a0bcc585a0360f4bd7c9095bb1f32","refreshBefore":"2026-11-23T12:56:19.068Z"}
3. Redis keys: mcp-events:idx:deploy.finished, mcp-events:sub:sub_ac69046b8fbf5f6e121797b28fbb4274481a0bcc585a0360f4bd7c9095bb1f32
   stored secret: {"iv":"8BRwtxYSmso5jQQk","data":"rBF1ShAjCpm8ZUhGk...
4. emit web -> 1 QStash message(s), emit api -> 0
   received via live QStash: true after 477 ms -> [{"project":"web","eventId":"evt_f77b68d5-b4fb-42ab-b7f1-e8a4f6e4ee39"}]
5. receiver answered 503 once; delivered after retry: true (14 s)
   attempt: status 503, webhook-id evt_909b4b98-3f4a-4695-9160-64cae3468434, webhook-timestamp 1795434980
   attempt: status 204, webhook-id evt_909b4b98-3f4a-4695-9160-64cae3468434, webhook-timestamp 1795434993
6. mallory subscribe refused: -32012 Forbidden
7. events/unsubscribe: ok; Redis keys left: 0
8. emit after unsubscribe -> 0 QStash message(s); new deliveries: 0
```

The callback URL the AI SDK sends is different from the one you pass it, because it adds a `mcp_event_subscription` query parameter. The subscription ID is generated from the URL as sent, so refreshes from the same client land on the same subscription.

In step 5, QStash sent the retry 13 seconds later. The retry had the same `webhook-id` (allowing client to ignore the retry as duplicate) and a different timestamp. The retry was re-signed, so it passed signature verification. AI SDK responds with status 204 only after signature is verified.

Overall, it took at most 477 ms for the first event to reach the client after the first `emitDeployFinished()` call, going through QStash and the delivery route.

## What ChatGPT expects from this server

This server implements the [webhook portion of the MCP Events draft](https://developers.openai.com/plugins/build/mcp-events) to match what ChatGPT implements:

- **delivery** only supports `"webhook"`. ChatGPT only supports this delivery mode, so mcp-handler exposes `delivery: ["webhook"]` on all events and rejects other delivery modes.
- **unsubscribe** must always succeed. The Redis store always returns `true` on `remove`
- **retries** will have the same `eventId` but updated timestamp and signature. 410 or 413 stops retries.
- **payload limits** ChatGPT supports up to 256 KiB payload per event. This example emits a few small fields, but if you have larger payloads you would check the size in `emit()` and instead emit a summary and provide a tool to retrieve the full record.
- **replay** isn't supported. The store returns `cursor: null` to tell ChatGPT that missed events can't be replayed.

mcp-handler advertises a top-level `events` capability that ChatGPT checks, but [SEP-3415](https://modelcontextprotocol.io/extensions/events/overview) is now Final with the extension in Beta and uses an `io.modelcontextprotocol/events` key in `extensions`. A client based on SEP-3415 won't find the events on this server yet. mcp-handler has a [draft pull request](https://github.com/vercel-labs/mcp-handler/pull/199) that adds support for both shapes as well as the built-in Redis store, but it has not been merged.

If you have a server that uses the standard MCP TypeScript SDK instead of mcp-handler, [`@upstash/mcp-toolkit`](https://upstash.com/blog/mcp-tasks-and-events) has the same Redis and QStash backend with the event methods.

---

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_4cf2adc7846aa874f833b068&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.
