> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mcp-use.com/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP Events

> Let clients subscribe to changes on your server and receive them by webhook or by polling.

> [!WARNING]
>
> MCP Events are experimental. The API may change in a minor release.

MCP is request-driven: a client asks, and your server answers. MCP Events add the
other direction. A client subscribes to something that may happen later, such as
"a new message in #general", and your server tells it when it does. The event can
wake an agent so it acts on the change, instead of calling a tool every few
minutes to check.

For the concept and when to pick an event over a tool or an MCP Task, read
[What are MCP events?](https://manufact.com/blog/what-are-mcp-events).

## How it works

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant C as Client (ChatGPT, agent, app)
    participant S as Your mcp-use server
    participant T as Your tool or backend

    opt Webhook delivery only
        C->>S: events/subscribe message.created { channel_id: "c1" }
        Note over S: onSubscribe(ctx, args) checks access,<br/>then the subscription is stored
        S-->>C: { id, refreshBefore }
    end

    T->>S: messageCreated.emit({ channel_id: "c1", ... })
    Note over S: match(ctx, event, args) picks<br/>the subscriptions that get it

    alt Webhook delivery
        S->>C: POST signed event to the callback URL
    else Poll delivery
        C->>S: events/poll { cursor }
        Note over S: onSubscribe(ctx, args) runs on every poll
        S-->>C: { events, cursor, nextPollMs }
    end
```

1. **The client subscribes** to an event by name, with arguments that narrow it
   (here, one channel). Your `onSubscribe` hook can refuse.
2. **Your code emits** the event when something changes, usually from a tool
   callback or a backend job.
3. **mcp-use delivers it** to every matching subscription, either as a signed
   HTTP POST to the client's callback URL (webhook) or on the client's next
   `events/poll` request (poll).

You write steps 1 and 2. mcp-use handles the protocol, storage, signing,
retries and polling.

## Define and emit an event

Declare the event once with `server.event()`. It returns a handle you call
`emit()` on.

```ts theme={null}
import { MCPServer } from "mcp-use";
import { z } from "zod";

const server = new MCPServer({ name: "chat", version: "1.0.0" });

const messageCreated = server.event({
  name: "message.created",
  description: "A message was posted in a channel you follow.",
  // What a client can filter on when it subscribes
  inputSchema: z.object({ channel_id: z.string() }),
  // What each event carries
  payloadSchema: z.object({
    channel_id: z.string(),
    message_id: z.string(),
    preview: z.string(),
  }),
});

// Later, when a message is posted:
await messageCreated.emit(
  { channel_id: "c1", message_id: "m42", preview: "Hi" },
  { eventId: "m42" },
);
```

| Option | Purpose |
| - | - |
| `name` | The event name clients subscribe to, such as `message.created`. |
| `description` | Shown to users choosing what to monitor. |
| `inputSchema` | The subscription arguments (filters). Defaults to an empty object. |
| `payloadSchema` | The event data. `emit()` validates against it. |
| `onSubscribe` | Optional. Refuse a subscription. See [Control who receives an event](#control-who-receives-an-event). |
| `match` | Optional. Decide which subscriptions get an event. |

### What `emit()` does

* Validates the data against `payloadSchema` and rejects bodies over 256 KiB.
* Sends the event to every matching webhook subscription and adds it to the
  log that `events/poll` reads.
* Resolves with `{ eventId, deliveries }` after the first delivery attempt.
  Failed deliveries are retried in the background.

Pass an `eventId` that stays the same for the same change (a message id, a
deployment id). Clients use it to ignore duplicates. One is generated if you
leave it out.

`emit()` throws if it can't read the subscriptions or queue the deliveries in
the store. A failed write to the poll log is logged instead. When the event
follows a write that already succeeded, catch the error so the tool call still succeeds:

```ts theme={null}
await messageCreated
  .emit({ channel_id, message_id, preview }, { eventId: message_id })
  .catch((err) => console.error(`message.created emit failed: ${err}`));
```

## Control who receives an event

By default, a subscription receives an event when each subscription argument
that also appears in `data` has the same value there. A client subscribed with
`{ channel_id: "c1" }` gets every event whose `data.channel_id` is `"c1"`.

The client chooses those arguments, so they narrow a stream but don't prove the
client may read it. When events carry one user's data, add two hooks:

* **`onSubscribe(ctx, args)`** runs when a client subscribes, renews a webhook
  subscription or polls, so revoked access takes effect at the next renewal.
  Throw `new EventsError("forbidden", message)` to refuse.
* **`match(ctx, event, args)`** runs for each subscription when you emit, and
  for each logged event when a client polls. Return `true` to deliver.

```ts theme={null}
import { EventsError } from "mcp-use";

// On a server with OAuth configured. `canRead` stands for your own access check.
const noteCreated = server.event({
  name: "note.created",
  inputSchema: z.object({ folder: z.string().optional() }),
  payloadSchema: z.object({
    ownerId: z.string(),
    folder: z.string(),
    noteId: z.string(),
  }),

  // Refuse anonymous clients and folders the user can't read
  onSubscribe: async (ctx, { folder }) => {
    if (ctx.userId === null) {
      throw new EventsError("forbidden", "Sign in to follow notes");
    }
    if (folder && !(await canRead(ctx.userId, folder))) {
      throw new EventsError("forbidden", "No access to this folder");
    }
  },

  // Only deliver the subscriber's own notes
  match: (ctx, { data }, { folder }) =>
    data.ownerId === ctx.userId && (!folder || data.folder === folder),
});
```

When you emit, record the owner with the same id that `ctx.userId` holds:

```ts theme={null}
server.tool({ name: "create_note" /* ... */ }, async (input, ctx) => {
  const noteId = await saveNote(input);
  await noteCreated.emit({
    ownerId: String(ctx.auth.payload.sub ?? ctx.auth.user.id),
    folder: input.folder,
    noteId,
  });
  // ...
});
```

`onSubscribe` runs on every poll, so keep it fast. A `match` that throws skips
that subscription and is logged. Receiving an event never lets a client act:
its tool calls still go through normal [authorization](https://docs.mcp-use.com/typescript/server/authentication/index.md).

### The `ctx` argument

| Field | Value |
| - | - |
| `userId` | The subscriber's user id: the token's `sub` claim (what tools read as `ctx.auth.payload.sub`), else `ctx.auth.user.id`. `null` without auth. |
| `principal` | A stable id for the subscriber: `issuer\|sub`, `user:<id>`, or `client:<id>` when only the OAuth client is known. `null` without auth. |
| `mode` | `"webhook"` or `"poll"`. |
| `name` | The event name. |

Webhook subscriptions store the subscriber, so `match` sees the same `ctx` on
every later emit, on any server instance.

## Delivery: webhook or poll

The client picks how it receives events. Your server code is the same for both.

| | Webhook | Poll |
| - | - | - |
| How | Your server POSTs each event to the client's HTTPS callback URL. | The client calls `events/poll` with a cursor. |
| Client needs | A public HTTPS endpoint. | Nothing beyond the MCP connection. |
| State on server | A stored subscription, renewed before `refreshBefore`. | None. The cursor is a position in a short event log. |
| Used by | ChatGPT, servers and backends. | Apps, scripts, the CLI and React (`useMcpEvent`). |

### Webhooks

* When a subscriber first subscribes with a callback URL, the server sends a
  signed verification challenge during `events/subscribe` and expects the
  client to echo it back. A passed check is remembered for that subscriber and
  URL for an hour.
* Each event is one POST, signed with HMAC-SHA256 using the client's `whsec_`
  secret (`webhook-id`, `webhook-timestamp` and `webhook-signature` headers).
* Failed deliveries are retried after 10 s, 1 min, 5 min, 30 min and 2 h with
  the same `eventId`. A `410` response removes the subscription.
* Subscriptions last 24 hours by default (`events.defaultTtlMs`). Clients renew
  by subscribing again.
* By default, callbacks must be HTTPS and can't point at private or loopback
  addresses. `mcp-use dev` relaxes this, as does `events.allowInsecureCallbacks`,
  which is for trusted local development only.

Retries run on an in-process timer, so they need a long-running server (`mcp-use dev`,
`node`, a container). On serverless hosts, a due retry runs on the next `emit()`.

### Webhooks need an authenticated client

A webhook subscription outlives the request that created it: the server stores
it and keeps POSTing events to its URL until it expires. So the server needs to
know who owns it. mcp-use stores each subscription under the caller's
*principal*, the identity it reads from the access token (`ctx.principal`).
Only that principal can renew or cancel it, and `onSubscribe` and `match`
decide what it may receive.

A request without an access token has the principal `anonymous`. If anonymous
webhooks were allowed, anyone who can reach the server could register their
own URL and receive every event, including events that carry other users'
data. So by default the official dialect refuses them:

```json theme={null}
{
  "code": -32024,
  "message": "Webhook subscriptions need an authenticated client, and this request has no access token. ...",
  "data": {
    "reason": "unauthenticated",
    "docs": "https://mcp-use.com/docs/typescript/server/events#webhooks-need-an-authenticated-client"
  }
}
```

To receive webhooks from a server, do one of these:

* **Add OAuth to the server** ([Authentication](https://docs.mcp-use.com/typescript/server/authentication.md)).
  Clients sign in and each subscription belongs to that user.
* **Poll instead.** `events/poll` stores nothing, so it works without sign-in.
  `onSubscribe` and `match` still run on every poll.
* **Allow anonymous webhooks for testing.** `MCP_USE_EVENTS_INSECURE=1` or
  `events.allowInsecureCallbacks: true` allows them, along with `http:` and
  private callback URLs. `mcp-use dev` sets `MCP_USE_EVENTS_INSECURE=1` when it
  listens on localhost without `--tunnel`; with a tunnel or a non-loopback
  host, anonymous webhooks stay refused. Never enable it on a production
  server.

The ChatGPT dialect isn't gated this way, which is why ChatGPT works with
servers that have no OAuth.

### Polling

Every emitted event is kept in a per-event log for 1 hour (up to 1000 events).
The client polls with the last cursor it got and receives what happened since:

* `cursor: null` starts from now.
* `hasMore: true` means poll again right away. Otherwise wait `nextPollMs`
  (5000 by default, `events.pollIntervalMs`).
* `truncated: true` means some events may have been missed, for example because
  the cursor is older than the log.

Polled events go through the same `onSubscribe` and `match` as webhooks.

## Storage

Subscriptions and the poll log live in a store. mcp-use picks one for you:

| Where you run | Store used |
| - | - |
| `mcp-use dev` | A JSON file in `.mcp-use/state/events/`, so subscriptions survive hot reloads. `http:` callbacks are allowed. |
| Manufact Cloud | Managed Redis. Turn on **MCP Events storage** in the server settings and redeploy. |
| Anywhere else | In memory, lost on restart. Set `events.store` for production. |

To use your own Redis, pass an Upstash REST store:

```ts theme={null}
import { upstashEventsStore } from "mcp-use/events";

const server = new MCPServer({
  name: "chat",
  version: "1.0.0",
  events: {
    store: upstashEventsStore({
      url: process.env.UPSTASH_REDIS_REST_URL!,
      token: process.env.UPSTASH_REDIS_REST_TOKEN!,
    }),
  },
});
```

`mcp-use/events` also exports `memoryEventsStore()` (for tests) and
`fileEventsStore(dir)`. The server logs which store is active when it starts.

On Manufact Cloud, list the current subscriptions with:

```bash theme={null}
mcp-use events subscriptions
```

## Receive events in a client

### Webhook

```ts theme={null}
import {
  createWebhookReceiver,
  generateWebhookSecret,
  subscribeEvent,
} from "@mcp-use/client";

const secret = generateWebhookSecret();

// A Fetch handler: serve it at https://example.com/hooks/mcp
const handler = createWebhookReceiver({
  secrets: [secret],
  onEvent: (event) => console.log(event.name, event.data),
});

await subscribeEvent(session, {
  name: "message.created",
  arguments: { channel_id: "c1" },
  url: "https://example.com/hooks/mcp",
  secret,
});
```

The receiver checks signatures, answers the verification challenge and drops
duplicates. Call `subscribeEvent` again before `refreshBefore` to keep the
subscription, and `unsubscribeEvent` to stop it.

### Poll

```ts theme={null}
import { pollEvents } from "@mcp-use/client";

let cursor: string | null = null;
for (;;) {
  const page = await pollEvents(session, {
    name: "message.created",
    arguments: { channel_id: "c1" },
    cursor,
  });
  for (const event of page.events) console.log(event.eventId, event.data);
  cursor = page.cursor;
  if (!page.hasMore) {
    await new Promise((r) => setTimeout(r, Math.max(page.nextPollMs, 1000)));
  }
}
```

### React

`useMcpEvent` runs the poll loop for a `useMcp` connection:

```tsx theme={null}
import { useMcp, useMcpEvent } from "@mcp-use/client/react";

function Messages() {
  const mcp = useMcp({ url: "http://localhost:3000/mcp" });
  const { events } = useMcpEvent(mcp, "message.created", {
    arguments: { channel_id: "c1" },
  });
  return (
    <ul>
      {events.map((e) => (
        <li key={e.eventId}>{JSON.stringify(e.data)}</li>
      ))}
    </ul>
  );
}
```

### CLI

```bash theme={null}
mcp-use client connect my-server http://localhost:3000/mcp
mcp-use client my-server events list
mcp-use client my-server events poll message.created channel_id=c1 --follow
mcp-use client my-server events subscribe message.created channel_id=c1 --url https://example.com/hooks/mcp
mcp-use client my-server events unsubscribe message.created channel_id=c1 --url https://example.com/hooks/mcp
```

`subscribe` generates and prints a `whsec_` secret unless you pass `--secret`.

![mcp-use client subscribing a webhook to note.created, receiving a delivery, and unsubscribing](https://mintcdn.com/mcpuse/CPLxdNw8fQIj7tj8/images/events/cli-subscribe.gif?s=d9f3da8a6c81b42094438201c4373363)

Subscribe a local receiver, create a note, see the delivery, then unsubscribe.

![mcp-use client polling note.created with a cursor](https://mintcdn.com/mcpuse/CPLxdNw8fQIj7tj8/images/events/cli-poll.gif?s=70a89e526673dfe8ceee5b3965b09356)

Poll from a cursor: only the inbox note is returned.

### Inspector

The Inspector's **Events** tab lists your server's events and subscribes with a
built-in webhook inbox. Each delivery shows its `webhook-id`, signature check
and body. Under `mcp-use dev --tunnel`, the inbox is reachable through the
tunnel.

When the server runs with insecure events, as under `mcp-use dev` on localhost,
the tab shows a banner saying anonymous webhook subscriptions are allowed. A
deployed server without that setting refuses them, and the tab explains why.

![Inspector Events tab subscribing to note.created and showing a signed delivery](https://mintcdn.com/mcpuse/CPLxdNw8fQIj7tj8/images/events/inspector-events.gif?s=7b3eefccb45475c3fc0b72b587d7fdde)

Subscribe from the Events tab, call create\_note from Tools, inspect the delivery, then unsubscribe.

## Use with ChatGPT

ChatGPT supports [MCP Events](https://developers.openai.com/plugins/build/mcp-events)
with webhook delivery. Each event starts one automation run.

* Subscriptions are created from ChatGPT **Work** chats with **Cloud** selected.
  A local Codex chat hands the subscription to a Work Cloud chat.
* The workspace needs **Developer mode** and **Allow event-triggered scheduled
  tasks** turned on.
* Servers without OAuth work.

## Protocol details

mcp-use speaks two versions of the protocol from the same `server.event()`
definitions and picks one per client, so you don't configure anything.

| | ChatGPT | Official extension |
| - | - | - |
| Spec | [OpenAI MCP Events](https://developers.openai.com/plugins/build/mcp-events) | [`io.modelcontextprotocol/events`](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/seps/3415-events-extension.md) (SEP-3415) |
| Delivery | Webhook | Webhook and poll |
| Chosen when | Client name starts with `openai-mcp`, the callback is on `openai.com`, or the protocol revision is before 2026-07-28 | The client declares the extension or sends an `Mcp-Name` header |
| Anonymous webhooks | Allowed | Refused with `-32024` (allowed under `mcp-use dev`) |

Push delivery (`events/stream`) and webhook replay are not implemented.

> [accordion] Methods
>
> | Method | Behavior |
> | - | - |
> | `events/list` | Event names, descriptions, `delivery`, `inputSchema` and `payloadSchema`. With insecure events, `_meta["com.mcp-use/events"]` is `{ insecure: true }`. |
> | `events/subscribe` | Validates the name, arguments and `whsec_` secret (24 to 64 bytes), verifies the callback and stores the subscription. Returns `{ id, refreshBefore, cursor: null, truncated: false }`. |
> | `events/unsubscribe` | Removes the subscription with the same name, arguments and callback URL. Returns `{}`. |
> | `events/poll` | Official extension only. Takes `{ name, arguments, cursor, maxEvents?, maxAgeMs? }` and returns `{ events, cursor, truncated, hasMore, nextPollMs }`. |
>
> Registering an event advertises `capabilities.events` (ChatGPT) and
> `capabilities.extensions["io.modelcontextprotocol/events"]` (official) on
> `initialize` and `server/discover`.

> [accordion] Error codes
>
> | | ChatGPT | Official |
> | - | - | - |
> | Unknown event | `-32602` | `-32023` `NotFound` |
> | Callback verification failed | `-32015` | `-32027` `CallbackEndpointError` |
> | `data.reason` | `challenge_failed`, `timeout` | `challenge_failed`, `timeout`, `connection_refused`, `tls_error` |
> | `onSubscribe` refused | `-32024` `Forbidden` | `-32024` `Forbidden` |

> [accordion] Webhook delivery format
>
> Each POST has the body `{ eventId, name, timestamp, data, cursor: null }` and
> the headers `webhook-id`, `webhook-timestamp`, `webhook-signature`
> (`v1,<base64 HMAC-SHA256>`) and `X-MCP-Subscription-Id`.
>
> * `webhook-id` is the `eventId` for ChatGPT, and a generated `msg_...` id
>   (kept across retries) for the official extension.
> * The verification request body is `{"type":"verification","challenge":"..."}`
>   and expects a 2xx response with `{"challenge":"..."}`. Success is cached
>   for an hour per subscriber and URL.
> * `410` and `413` responses are not retried.
> * When a client subscribes again with a new secret, deliveries are signed
>   with both secrets for 24 hours.
> * On Node, the sender resolves the callback host, rejects private, loopback
>   and link-local addresses, and connects to the checked address. Redirects
>   are not followed and each request times out after 10 s.

> [accordion] Subscription identity and lifetime
>
> A subscription's id comes from the subscriber, callback URL, event name and
> arguments, so subscribing again with the same values renews it. `ttlMs`
> omitted grants 24 hours, a positive number is clamped between 1 minute and 30
> days, `0` or a negative number is rejected, and `null` means no expiry (`refreshBefore: null`).

> [accordion] Routing headers
>
> On `events/subscribe`, `events/unsubscribe` and `events/poll`, an `Mcp-Name`
> header must equal `params.name`. An `Mcp-Param-<Header>` header must equal
> the argument whose `inputSchema` property declares `"x-mcp-header": "<Header>"`
> (Base64 values `=?base64?...?=` are decoded). A mismatch is HTTP 400 with `-32020`
> (`HeaderMismatch`). Missing headers are accepted with a warning. The `@mcp-use/client` HTTP connector sets `Mcp-Name`.

> [accordion] Event list changes
>
> The server answers a `subscriptions/listen` request whose filter sets
> `eventsListChanged: true`, and sends `notifications/events/list_changed` when
> the event catalog changes: on a hot reload in `mcp-use dev`, or after a deploy
> on instances that share the store (checked every 30 seconds).

> [accordion] Platform environment variables
>
> On Manufact Cloud the store is configured from `MCP_USE_PLATFORM_STORAGE_URL`,
> `MCP_USE_PLATFORM_STORAGE_TOKEN` and `MCP_USE_PLATFORM_STORAGE_PREFIX`.
> `MCP_USE_PLATFORM_NAMESPACE` sets the key namespace, and
> `MCP_USE_PLATFORM_SECRET` encrypts stored webhook secrets (comma-separated for
> rotation).

> [accordion] Delivery failure logs
>
> A failed attempt is logged as
> `[mcp-use] events delivery failed: <name> <subscriptionId> -> <origin> <status|error> attempt <n>`.

See [`examples/mcp-events`](https://github.com/mcp-use/mcp-use/tree/main/libraries/typescript/packages/server/examples/mcp-events) for a complete server.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.