Events options
A server serves events as soon as one of its apps declares one, with no option set. @FrontMcp({ events }) changes the defaults: which delivery modes the server performs, how long a subscription lasts, how webhook deliveries are retried, where subscriptions are kept, whether other services may publish over HTTP, and which dialect callers are answered in. New in 1.12.0.
@FrontMcp({
events: {
enabled?, compat?, bridge?,
poll?, push?, buffer?, // reading by request and by stream
webhook?, subscriptions?, store?, // webhook subscriptions and where they're kept
publishEndpoint?, // POST /events/publish
},
})
Reference
events
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | not set | Events are on once an app declares one. false turns them off: nothing is served, and publish() throws EventsNotEnabledError. true starts events on a server that declares none. |
compat | "auto" | "sep-3415" | "sketch" | "auto" | The dialect callers are answered in. "auto" picks per caller: the sketch for a caller recognized as OpenAI, SEP-3415 for everyone else. |
bridge | boolean | true | Also emits each published occurrence on the server's event bus, under the event's name, where a workflow with trigger: "event" listens. |
poll | object | on | events/poll. |
push | object | on | events/stream. |
buffer | object | 10 minutes, 10000 per event | What a poll or a stream can still read of published occurrences. |
webhook | object | on, where callers sign in | Webhook subscriptions and their deliveries. |
subscriptions | object | 1 hour, 100 per caller | Lifetimes and limits. |
store | object | memory | Where subscriptions and pending deliveries are kept. |
publishEndpoint | object | off | Publishing over HTTP. |
Which delivery modes a server performs
An event is offered in the modes its server performs, within the event's own delivery:
| Mode | Performed when |
|---|---|
poll | Always, unless events.poll.enabled is false. On every runtime and in every auth mode. |
push | Unless events.push.enabled is false, and except in a serverless deployment, where no process lives long enough to hold a stream. |
webhook | When the server's auth mode signs callers in (any auth.mode other than public), unless events.webhook.enabled is false. |
A subscription belongs to a caller, which a server in public auth mode doesn't have. Such a server logs at startup, and offers its events by poll and push:
Webhook event delivery is off: the server runs in public auth mode, so a subscription would have no owner. Configure an auth mode that signs callers in to deliver events by webhook.
A server that offers no event in any mode serves no events: it doesn't advertise the capability, and events/list answers -32601. That is a server that performs no mode, or none that its events' own delivery allows. Its events are still registered and checked at startup, and publish() still runs.
A server that serves events advertises them in two places, on every transport, so a client of either dialect finds them:
{ "capabilities": { "events": {}, "extensions": { "io.modelcontextprotocol/events": {} } } }
events.poll, events.push and events.buffer
| Option | Type | Default | Description |
|---|---|---|---|
poll.enabled | boolean | true | false turns events/poll off. |
poll.nextPollMs | number | 30000 | The wait between two polls the server recommends. Also how often an event's check() is called for a stream or a webhook subscription. |
poll.maxEvents | number | 100 | The most occurrences one poll returns, and the cap of a request's maxEvents. |
push.enabled | boolean | true | false turns events/stream off. |
push.heartbeatMs | number | 25000 | How often an open stream sends a heartbeat with its cursor. |
buffer.maxAgeMs | number | 600000 (10 minutes) | How long a published occurrence can still be polled, or replayed on a stream. |
buffer.maxEvents | number | 10000 | How many occurrences are kept for one event. |
The buffer is in the memory of the process that published. It isn't in the store, so it doesn't survive a restart and isn't shared between processes. An event with check() doesn't use it.
events.webhook and events.webhook.delivery
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | false turns webhook delivery off. |
allowedCallbacks | string[] | [] | Callback URLs accepted without a verification request: a URL, or a prefix that ends at a /. For receivers you run yourself. |
verification.cacheTtlMs | number | 3600000 (1 hour) | How long a callback a caller proved stays verified for that caller. |
verification.timeoutMs | number | 10000 | How long the callback has to answer the verification request. |
verification.maxAttemptsPerHost | number | 10 | Verification attempts one callback host may get in a minute, whatever its port. |
rotationGraceMs | number | 300000 (5 minutes) | How long deliveries are also signed with a secret that a refresh replaced. |
unsafeAllowLocalCallbacks | boolean | false | For tests only: also accepts http: callbacks and loopback or private addresses. The server warns at startup when it's on. |
events.webhook.delivery, for each delivery:
| Option | Type | Default | Description |
|---|---|---|---|
timeoutMs | number | 10000 | How long a callback has to answer one attempt. |
maxAttempts | number | 5 | How many times one delivery is attempted. |
retryWindowMs | number | 900000 (15 minutes) | How long after its first attempt a delivery is still retried. |
backoffMs | number | 1000 | The wait before the second attempt. It doubles with each attempt. Must not exceed maxBackoffMs. |
maxBackoffMs | number | 60000 | The longest wait between two attempts. |
concurrency | number | 16 | How many deliveries are in flight at once in one process. |
In a long-lived process, deliveries happen after publish() returned. On a serverless or edge runtime, where nothing runs after the response, the first attempt of each delivery is made before publish() resolves, so publish() can take as long as the slowest callback, up to timeoutMs. A retry there runs during a later publish().
events.subscriptions
| Option | Type | Default | Description |
|---|---|---|---|
defaultTtlMs | number | 3600000 (1 hour) | The lifetime of a webhook subscription that asks for none. |
maxTtlMs | number | 86400000 (24 hours) | The longest lifetime granted. |
minTtlMs | number | 60000 (1 minute) | The shortest lifetime granted, whatever a subscription asks for. |
allowNoExpiry | boolean | false | Grants ttlMs: null, a subscription that never expires, for an event without a ttl.maxMs of its own. Needs store.redis or store.sqlite. |
maxPerPrincipal | number | 100 | How many webhook subscriptions one caller may hold. Also its limit of open streams, and of poll leases, each counted by itself. |
reauthorizeEveryMs | number | 300000 (5 minutes) | How often a subscription's owner is checked again against the event's authorities and authorize(). |
suspendedTtlMs | number | 604800000 (7 days) | How long a suspended subscription without expiry is kept before it's ended. |
The three lifetimes must satisfy minTtlMs <= defaultTtlMs <= maxTtlMs once the defaults are applied. A server that lowers maxTtlMs below one hour sets defaultTtlMs too. An event's own ttl narrows these for that event.
events.store
Where webhook subscriptions, their pending deliveries, and the answers of repeated publish requests are kept:
| Option | Type | Default | Description |
|---|---|---|---|
sqlite | { path, … } | none | A SQLite file. path is required. See SQLite. |
redis | Redis options | none | A Redis server. See Redis. Vercel KV is refused: it has no atomic compare-and-set, which subscription updates need. |
keyPrefix | string | mcp:events: and a hash of the server's name, then : | The prefix of every key the store writes, so servers that share a store don't see each other's subscriptions. |
sqlite or redis, not both. Without either, the store is the process's memory:
| Memory (the default) | sqlite or redis | |
|---|---|---|
| Subscriptions | End with the process. Clients subscribe again | Kept, and shared by every process of the server |
| Pending deliveries | End with the process | Survive a restart. Another process takes over those of one that died |
An event's check() position, for webhook | Forgotten. The client's next events/subscribe replays from the cursor it sends | Kept. A restart continues from it |
| Streams across processes | A stream carries what its own process publishes | With redis, each process relays what it publishes to the others |
The relay between processes runs on the subscription store, so it needs a server that performs the webhook mode, and the push mode. In public auth mode, or with webhook.enabled: false, store.redis relays nothing, and each stream carries what its own process publishes. A server whose streams nothing relays says so at startup, at info level, and why:
| The server has | The line |
|---|---|
No store.redis | Event streams carry what this process publishes. With several processes, set events.store.redis so an event published on one reaches the streams the others hold. |
store.redis, in public auth mode | Event streams carry what this process publishes. events.store.redis is set, but it relays events between processes only with webhook delivery, which is off: the server runs in public auth mode, so configure an auth mode that signs callers in. Then an event published on one process reaches the streams the others hold. |
store.redis and webhook.enabled: false | The same, with the reason events.webhook.enabled is false, so remove that setting. With both, both reasons, separated by ;. |
The three lines were read in Node, from servers made with createFetchHandler(), with a Redis store that was never reached. Changed in 1.12.1: before, a server with store.redis got the first line, which tells it to set what it has.
A store that outlives the process holds webhook secrets, so it encrypts them, and needs a secret to do that with: the MCP_EVENTS_SECRET environment variable, else MCP_SESSION_SECRET, else MCP_SERVER_SECRET. Without one the server doesn't start. Configuration files lists the environment variables FrontMCP reads.
events.publishEndpoint
Lets another service publish an event with one HTTP POST, without linking the SDK: a backend, a queue consumer, a cron container. Off by default.
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Serves the endpoint. |
path | string | /events/publish | Where it's served, at the root of the server, not under the MCP endpoint's path. Starts with /, with literal segments only. |
secret | string | none | At least 32 characters. Every request is then signed with it. Without it, a caller presents the bearer credentials of the MCP endpoint. |
authorities | profile name, names, or a rule | none | The rule a bearer caller must satisfy, with the request's body as the rule's input. Not together with secret. |
The request body is JSON, and POST is the only method:
| Field | Type | Description |
|---|---|---|
name | string | Required. The name of a registered event. |
data | object | Required. Checked against the event's payloadSchema. |
eventId | string | 1 to 255 visible ASCII characters, with no space. Makes the request repeatable. |
timestamp | string | A date, such as 2026-11-02T12:00:00Z. |
audience | { sub?, tenantId?, roles?: { any?, all? } } | As the audience option of publish(). |
subscriptionId | string | As the subscriptionId option of publish(). |
The answer is 202 with what publish() returns: { "eventId": "evt_…", "matched": 0 }. A key the endpoint doesn't know is refused with 400, so a misspelled audience never turns into a publish to everyone.
Who may publish
With secret | Without secret | |
|---|---|---|
| A request carries | X-FrontMCP-Timestamp: the time of signing, in Unix seconds. X-FrontMCP-Signature: v1= and the hex HMAC-SHA256, keyed with the secret, of the timestamp, a ., and the body's bytes as sent | Authorization: Bearer …, the credentials the MCP endpoint takes |
| Refused when | The timestamp is more than 5 minutes from the server's clock, the signature is wrong, or the same signature was accepted before | The token doesn't verify, the caller is anonymous, or authorities refuses it |
Works in public auth mode | Yes | No: the server doesn't start |
The signature is the one a workflow webhook takes. To send a request again, sign it again.
Without secret and without authorities, every signed-in caller may publish every event, to any audience, and the server warns about it at startup. Set authorities unless every signed-in caller is trusted to publish.
What the endpoint answers
The first check that fails answers:
| Status | Body | When |
|---|---|---|
415 | { "error": "The body must be application/json" } | The Content-Type isn't application/json. |
413 | { "error": "Payload too large" } | The body is over 262144 bytes, what one delivery may carry. |
401 | { "error": "Unauthorized" } | With secret: unsigned, outside the 5 minutes, a wrong signature, or sent before. Without: no token, or one the server can't verify. |
400 | { "error": "Invalid publish request", "issues": [{ path, message }] } | The body isn't a JSON object of the fields above. |
403 | { "error": "Forbidden" } | authorities refuses the caller. |
404 | { "error": "Event \"…\" is not registered" } | The server has no event of that name. |
422 | { "error": "data does not match the payloadSchema of event \"…\"", "issues": […] } | data doesn't match payloadSchema. |
409 | { "error": "Event \"…\" with eventId \"…\" is being published; retry for its answer" } | Another request with the same eventId is publishing right now. |
202 | { eventId, matched } | Published, or already published with this eventId. |
issues say where a problem is and what it is. They never repeat a value of the request. With a secret, every refusal of a signature is the same 401, and the server's log says which check refused it. The server's global rate limit and IP filter (throttle) apply before all of these.
Repeated requests
A request that names an eventId is idempotent for 10 minutes, per event name: a repeat within them is answered 202 with the answer of the first request, and nothing is published again. So a sender that retries after a timeout sends the same eventId, and signs the retry again.
- The answers are kept in the store. With
redisorsqlite, every process of the server sees them. - A publish that fails gives its
eventIdback: the retry publishes. - While the first request is still publishing, a repeat is answered
409. - A request without an
eventIdgets a generated one, and is never deduplicated.
Caveats
- A misspelled key under
eventsstops startup, at any level:events: { subscriptions: { maxPerPrincipl: 2 } }fails with aZodErrorwhose issue isUnrecognized key: "maxPerPrincipl", atpath: ["events", "subscriptions"]. So does a value of the wrong type, and a combination that can't work stops it with the option's name. Changed in 1.12.1: before, an unknown key was dropped and its default applied, soevents: { pol: { enabled: false } }started a server that still polled. events.enabled: falseisn't the way to hide one event. It turns every event off. Use the event's ownhideFromDiscovery,availableWhenorauthorities.- On a
splitByAppserver, each app serves its own publish endpoint under its route base, such as/billing/events/publish, for the events of that app. this.scope.eventsis the server's event registry, withgetEvents(),findByName(name),deliveryModesOf(event)andservesEvents(). It'sundefinedwhen events are off. Scope and registries covers the scope.- Counters, traces and the readiness check that events add are listed in Observability and telemetry and Health checks and metrics.
Usage
Turning delivery modes on and off
Each mode has its own switch. Turning one off takes it out of every event's delivery, and its request stops existing:
import { test, expect } from "@frontmcp/testing";
import { App, event, z } from "@frontmcp/sdk";
import { serverWith } from "./client";
// Webhook only, and a public server performs no webhook mode.
const invoicePaid = event({ name: "invoice.paid", payloadSchema: { invoiceId: z.string() }, delivery: ["webhook"] });
@App({ id: "billing", name: "Billing", events: [invoicePaid] })
class BillingApp {}
test("by default a public server polls and streams", async () => {
const rpc = serverWith({});
expect((await rpc("events/list")).result.events[0].delivery).toEqual(["poll", "push"]);
});
test("without poll, events are offered by push only, and events/poll doesn't exist", async () => {
const rpc = serverWith({ poll: { enabled: false } });
expect((await rpc("events/list")).result.events[0].delivery).toEqual(["push"]);
expect((await rpc("events/poll", { name: "ticket.created" })).error).toEqual({ code: -32601, message: "Method not found: events/poll" });
});
test("with no mode left, the server serves no events, but publishing still runs", async () => {
const rpc = serverWith({ poll: { enabled: false }, push: { enabled: false } });
expect((await rpc("events/list")).error).toEqual({ code: -32601, message: "Method not found: events/list" });
expect((await rpc("server/discover")).result.capabilities.events).toBeUndefined();
const created = await rpc("tools/call", { name: "create_ticket", arguments: {} });
expect(created.result.structuredContent).toMatchObject({ eventId: expect.stringMatching(/^evt_/), matched: 0 });
});
test("events that allow only a mode the server doesn't perform aren't served either", async () => {
const rpc = serverWith({}, [BillingApp]);
expect((await rpc("events/list")).error).toEqual({ code: -32601, message: "Method not found: events/list" });
expect((await rpc("server/discover")).result.capabilities.events).toBeUndefined();
});
test("events.enabled: false turns everything off, publishing included", async () => {
const rpc = serverWith({ enabled: false });
expect((await rpc("events/list")).error.code).toBe(-32601);
const created = await rpc("tools/call", { name: "create_ticket", arguments: {} });
expect(created.result.structuredContent).toEqual({
refused: "Events are not enabled on this server, so nothing can be published. List the event in an app's `events`, and remove events.enabled: false if it is set.",
});
});
test("poll options change what a poll answers", async () => {
const rpc = serverWith({ poll: { nextPollMs: 5000 } });
expect((await rpc("events/poll", { name: "ticket.created" })).result.nextPollMs).toBe(5000);
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Publishing over HTTP
With publishEndpoint.enabled and a secret, a service that holds the secret publishes with one signed POST. The request goes through the same publish() as this.events.publish(), so a client that polls afterwards reads the occurrence:
import { test, expect } from "@frontmcp/testing";
import { publishOverHttp, rpc } from "./client";
test("a signed request publishes, and a polling client reads the occurrence", async () => {
const start = (await rpc("events/poll", { name: "ticket.created", cursor: null })).result.cursor;
const published = await publishOverHttp({ name: "ticket.created", data: { ticketId: "T-9" } });
expect(published).toEqual({ status: 202, body: { eventId: expect.stringMatching(/^evt_/), matched: 0 } });
const { events } = (await rpc("events/poll", { name: "ticket.created", cursor: start })).result;
expect(events).toMatchObject([{ eventId: published.body.eventId, data: { ticketId: "T-9" } }]);
});
test("the same eventId sent twice is published once", async () => {
const start = (await rpc("events/poll", { name: "ticket.created", cursor: null })).result.cursor;
const publication = { name: "ticket.created", data: { ticketId: "T-10" }, eventId: "crm-change-771", timestamp: "2026-11-02T12:00:00Z" };
const first = await publishOverHttp(publication);
// A second later, so the retry has another timestamp and another signature.
await new Promise((resolve) => setTimeout(resolve, 1100));
const retry = await publishOverHttp(publication);
expect(first).toEqual({ status: 202, body: { eventId: "crm-change-771", matched: 0 } });
expect(retry).toEqual(first);
const { events } = (await rpc("events/poll", { name: "ticket.created", cursor: start })).result;
expect(events).toMatchObject([{ eventId: "crm-change-771", timestamp: "2026-11-02T12:00:00.000Z" }]);
});
test("a wrong secret, or an old timestamp, is unauthorized", async () => {
const publication = { name: "ticket.created", data: { ticketId: "T-11" } };
const wrongSecret = await publishOverHttp(publication, { secret: "not-the-secret-this-server-was-given" });
const tenMinutesAgo = await publishOverHttp(publication, { timestamp: Math.floor(Date.now() / 1000) - 600 });
expect(wrongSecret).toEqual({ status: 401, body: { error: "Unauthorized" } });
expect(tenMinutesAgo).toEqual(wrongSecret);
});
test("each mistake in the body has its own status", async () => {
const misspelled = await publishOverHttp({ name: "ticket.created", data: { ticketId: "T-12" }, audiense: { sub: "nour" } });
expect(misspelled).toEqual({
status: 400,
body: { error: "Invalid publish request", issues: [{ path: "", message: 'Unrecognized key: "audiense"' }] },
});
const unknown = await publishOverHttp({ name: "ticket.closed", data: {} });
expect(unknown).toEqual({ status: 404, body: { error: 'Event "ticket.closed" is not registered' } });
const invalid = await publishOverHttp({ name: "ticket.created", data: { ticketId: 12 } });
expect(invalid).toEqual({
status: 422,
body: {
error: 'data does not match the payloadSchema of event "ticket.created"',
issues: [{ path: "ticketId", message: "Invalid input: expected string, received number" }],
},
});
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
From a shell, the same request:
body='{"name":"ticket.created","data":{"ticketId":"T-9"}}'
timestamp=$(date +%s)
signature=$(printf '%s.%s' "$timestamp" "$body" | openssl dgst -sha256 -hmac "$EVENTS_PUBLISH_SECRET" -r | cut -d' ' -f1)
curl -X POST https://desk.example.com/events/publish \
-H 'Content-Type: application/json' \
-H "X-FrontMCP-Timestamp: $timestamp" \
-H "X-FrontMCP-Signature: v1=$signature" \
--data-binary "$body"Letting signed-in callers publish
Without a secret, the endpoint takes the bearer credentials of the MCP endpoint, so a service publishes with the token it already has. authorities then decides what each caller may publish. Its rule reads the request's body as input, so this one lets callers publish ticket.created and nothing else:
import { test, expect } from "@frontmcp/testing";
import { publishAs } from "./client";
test("a caller with a key publishes the event the rule allows", async () => {
const published = await publishAs("crm-sync-key", { name: "ticket.created", data: { ticketId: "T-9" } });
expect(published).toMatchObject({ status: 202, body: { matched: 0 } });
});
test("the same caller is refused another event", async () => {
const refused = await publishAs("crm-sync-key", { name: "ticket.closed", data: { ticketId: "T-9" } });
expect(refused).toEqual({ status: 403, body: { error: "Forbidden" }, challenge: null });
});
test("a request without a token, or with a wrong one, is unauthorized", async () => {
const publication = { name: "ticket.created", data: { ticketId: "T-9" } };
expect(await publishAs(undefined, publication)).toEqual({ status: 401, body: { error: "Unauthorized" }, challenge: 'Bearer realm="mcp"' });
expect(await publishAs("not-a-key", publication)).toMatchObject({ status: 401, body: { error: "Unauthorized" } });
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
With an identity provider, a rule can compare the event's name with a claim of the caller's token, such as { path: "input.name", op: "eq", value: { fromClaims: "publishes" } }. Authorities covers rules on input.
Keeping subscriptions across restarts
In memory, a restart ends every webhook subscription, and each client has to subscribe again. Name a store, and set the secret it encrypts webhook secrets with:
@FrontMcp({
info: { name: "help-desk", version: "1.0.0" },
apps: [HelpDeskApp],
auth: { mode: "transparent", provider: "https://auth.example.com" },
events: {
// One file on one machine. With several machines: store: { redis: { host: "redis.internal" } }
store: { sqlite: { path: "./data/events.sqlite" } },
subscriptions: { allowNoExpiry: true },
},
})
export default class Server {}MCP_EVENTS_SECRET=$(openssl rand -hex 32)Changing lifetimes and limits
subscriptions bounds what a client may ask for, and an event's ttl narrows it for one event. This server grants at most two hours, half an hour by default, and two subscriptions per caller:
import { test, expect } from "@frontmcp/testing";
import { rpc } from "./client";
const secret = `whsec_${btoa("0123456789012345678901234567890123")}`;
const delivery = { url: "https://hooks.example.com/mcp/desk", secret };
const minutes = (refreshBefore: string) => Math.round((Date.parse(refreshBefore) - Date.now()) / 60_000);
const subscribe = async (name: string, extra: Record<string, unknown> = {}) => (await rpc("events/subscribe", { name, delivery, ...extra })).result;
test("a subscription that asks for nothing gets the default", async () => {
expect(minutes((await subscribe("ticket.created")).refreshBefore)).toBe(30);
});
test("a request is kept between the minimum and the maximum", async () => {
expect(minutes((await subscribe("ticket.created", { ttlMs: 1_000 })).refreshBefore)).toBe(1);
expect(minutes((await subscribe("ticket.created", { ttlMs: 86_400_000 })).refreshBefore)).toBe(120);
});
test("ttlMs: null gets the maximum, since this server grants no subscription without expiry", async () => {
expect(minutes((await subscribe("ticket.created", { ttlMs: null })).refreshBefore)).toBe(120);
});
test("an event's own ttl narrows the server's", async () => {
expect(minutes((await subscribe("ticket.escalated")).refreshBefore)).toBe(5);
expect(minutes((await subscribe("ticket.escalated", { ttlMs: 3_600_000 })).refreshBefore)).toBe(10);
});
test("a third subscription is over the caller's limit", async () => {
await subscribe("ticket.created");
await subscribe("ticket.escalated");
const third = await rpc("events/subscribe", { name: "ticket.created", arguments: { queue: "billing" }, delivery });
expect(third.error).toMatchObject({
code: -32025,
message: "The limit of 2 webhook subscriptions per caller is reached. Remove one with events/unsubscribe, then retry.",
data: { limit: "subscriptions", max: 2 },
});
});
test("poll leases are counted by themselves, up to the same limit", async () => {
await subscribe("ticket.created");
await subscribe("ticket.escalated");
const poll = (queue: string) => rpc("events/poll", { name: "ticket.watched", arguments: { queue } });
expect((await poll("billing")).result.events).toEqual([]);
expect((await poll("login")).result.events).toEqual([]);
expect((await poll("returns")).error).toMatchObject({ code: -32025, data: { limit: "pollLeases", max: 2 } });
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
maxPerPrincipal counts each kind of subscription by itself. In the last test the caller already holds two webhook subscriptions, and still gets two poll leases before the third is refused, with limit: "pollLeases". An open stream over the limit gets limit: "streams". Each limit has its own message.
Pinning the dialect
With compat: "auto", FrontMCP decides per caller. Pin a dialect when every client of a server speaks the same one, or to see what the other looks like:
import { test, expect } from "@frontmcp/testing";
import { serverWith } from "./client";
const notFound = async (compat: string | undefined, clientName: string) => {
const rpc = serverWith(compat ? { compat } : {});
return (await rpc("events/poll", { name: "ticket.closed" }, clientName)).error.code;
};
test("auto answers each caller in its own dialect", async () => {
expect(await notFound(undefined, "desk-agent")).toBe(-32023);
expect(await notFound(undefined, "ChatGPT")).toBe(-32011);
});
test("sep-3415 answers every caller with SEP-3415's codes", async () => {
expect(await notFound("sep-3415", "ChatGPT")).toBe(-32023);
});
test("sketch answers every caller with the sketch's codes", async () => {
expect(await notFound("sketch", "desk-agent")).toBe(-32011);
});
test("the capability is advertised in both places, whatever the dialect", async () => {
const rpc = serverWith({ compat: "sketch" });
const { capabilities } = (await rpc("server/discover", {}, "desk-agent")).result;
expect(capabilities).toMatchObject({ events: {}, extensions: { "io.modelcontextprotocol/events": {} } });
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Troubleshooting
Event subscription store: the sqlite store keeps webhook signing secrets…
events.store names SQLite or Redis, and no secret is set to encrypt the stored webhook secrets with (EventSubscriptionStoreError, EVENT_SUBSCRIPTION_STORE). Set MCP_EVENTS_SECRET. The server also refuses store with both sqlite and redis, allowNoExpiry without either, and a key the events option doesn't know:
import { test, expect } from "@frontmcp/testing";
import { FrontMcpInstance } from "@frontmcp/sdk";
import { HelpDeskApp } from "./main";
const start = (events: Record<string, unknown>) =>
FrontMcpInstance.createFetchHandler({
info: { name: "help-desk", version: "1.0.0" },
apps: [HelpDeskApp],
auth: { mode: "static", tokens: ["agent-nour-key"] },
events,
});
test("a store that outlives the process needs a secret", async () => {
await expect(start({ store: { sqlite: { path: "./events.sqlite" } } })).rejects.toThrow(
"Event subscription store: the sqlite store keeps webhook signing secrets, so it needs a secret to encrypt them with: set MCP_EVENTS_SECRET (or MCP_SESSION_SECRET / MCP_SERVER_SECRET).",
);
});
test("the store is sqlite or redis, not both", async () => {
await expect(start({ store: { sqlite: { path: "./events.sqlite" }, redis: { host: "localhost" } } })).rejects.toThrow(
"events.store takes redis or sqlite, not both",
);
});
test("a subscription without expiry needs a store that keeps it", async () => {
await expect(start({ subscriptions: { allowNoExpiry: true } })).rejects.toThrow(
"events.subscriptions.allowNoExpiry needs events.store.redis or events.store.sqlite",
);
});
test("a key the events option doesn't know stops startup", async () => {
await expect(start({ subscriptions: { maxPerPrincipl: 2 } })).rejects.toMatchObject({
issues: [{ code: "unrecognized_keys", path: ["events", "subscriptions"], message: 'Unrecognized key: "maxPerPrincipl"' }],
});
});
test("the three lifetimes have to be in order", async () => {
await expect(start({ subscriptions: { maxTtlMs: 30 * 60_000 } })).rejects.toThrow(
"events.subscriptions needs minTtlMs <= defaultTtlMs <= maxTtlMs; set the three together",
);
});
test("the publish endpoint has to know who publishes", async () => {
await expect(start({ publishEndpoint: { enabled: true, secret: "too-short" } })).rejects.toThrow(
"events.publishEndpoint.secret must be at least 32 characters (make one with: openssl rand -hex 32)",
);
const publicServer = FrontMcpInstance.createFetchHandler({
info: { name: "help-desk", version: "1.0.0" },
apps: [HelpDeskApp],
events: { publishEndpoint: { enabled: true } },
});
await expect(publicServer).rejects.toThrow(
"Event publish endpoint: the server runs in public auth mode, so nothing tells who publishes.",
);
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
events.subscriptions needs minTtlMs <= defaultTtlMs <= maxTtlMs; set the three together
One of the three lifetimes was changed and is now out of order with the defaults of the others. Lowering maxTtlMs below one hour puts it under the default defaultTtlMs: set defaultTtlMs as well.
Unrecognized key at path: ["events", …]
A key under events isn't an option, often a misspelling, and the server doesn't start. The issue's path says where the key is, and its message which one: Unrecognized key: "maxPerPrincipl" at ["events", "subscriptions"]. Fix the spelling with the tables above. Changed in 1.12.1: before, the key was dropped and its default applied.
Webhook event delivery is off: the server runs in public auth mode
A warning at startup, not an error: the server polls and streams. Webhook subscriptions need an auth mode that signs callers in, since each one belongs to a caller. A client that sends events/subscribe anyway gets -32601.
Event publish endpoint: the server runs in public auth mode, so nothing tells who publishes
publishEndpoint.enabled without a secret, on a server in public auth mode (EventPublishEndpointError, EVENT_PUBLISH_ENDPOINT). Set events.publishEndpoint.secret, or an auth mode that signs callers in. The same error class names a path the server already uses: the MCP endpoint, a health or metrics path, or a route of your own.
events.publishEndpoint.secret must be at least 32 characters
Make one with openssl rand -hex 32. events.publishEndpoint takes secret or authorities, not both means both were set: a signed request names no caller for a rule to check.
POST /events/publish answers 401
With a secret: the signature must be over <timestamp>.<body> with the body's bytes exactly as sent, the timestamp must be within 5 minutes of the server's clock, and a signature is accepted once, so sign a retry again. Without a secret: the request needs the Authorization: Bearer … header the MCP endpoint takes, from a caller who isn't anonymous.
POST /events/publish answers 404
Read the body. { "error": "Event \"…\" is not registered" } names an event no app declares. Any other 404 means nothing serves that path: publishEndpoint.enabled isn't true, the path differs, or the request isn't a POST.
POST /events/publish answers 409
Another request with the same eventId is publishing right now. Retry: the answer is then the first request's.
Events are disabled (events.enabled: false), so the … event(s) apps declare are not served
A warning at startup. events.enabled is false, so no event is served and publish() throws. Remove the option to serve them.