# Telling Clients Something Happened

> How a FrontMCP server tells an agent that something happened without being asked. Declaring an event, publishing it from a tool and from background code, how a client receives it, letting subscribers filter, and deciding who hears each occurrence.

Source: https://frontmcp.dev/learn/telling-clients-something-happened

[Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026

Every lesson so far starts with the client: a model calls a tool, and the server answers. But things happen on a server when nobody is asking. A customer opens a ticket at night, or a ticket has waited longer than its SLA allows. A model finds out only if it asks, and it can't know when to ask. **Events** turn this around: the server declares what can happen, a client subscribes once, and the server tells it each time. This lesson declares an event, publishes it, receives it, and then narrows who hears what.

**You will learn**

- Why a tool the model has to keep calling isn't enough
- How to declare an event, and publish it from a tool
- How a client receives it, and what a cursor is for
- How to let a subscriber filter, and how to decide who hears an occurrence
- How to publish when nobody called anything

> **Note**
>
> Events are MCP Events, a draft extension of MCP (SEP-3415). It isn't part of a ratified MCP revision yet, so few clients speak it, and its requests can still change. FrontMCP serves it since 1.12.

<a id="a-model-that-has-to-keep-asking"></a>

## A model that has to keep asking

The help desk escalates a ticket when it needs someone on call. An agent that watches escalations has one way to learn about them, a tool:

Initial call configuration:

```js
{ tool: "list_escalations", arguments: {} }
```

```ts escalations.tools.ts active
import { Tool, ToolContext, z } from "@frontmcp/sdk";

const escalations = [{ ticketId: "T-1", queue: "billing" }];

@Tool({
  name: "escalate_ticket",
  description: "Escalate a ticket to a queue's on-call agent.",
  inputSchema: { ticketId: z.string(), queue: z.string() },
})
export class EscalateTicket extends ToolContext {
  async execute(escalation: { ticketId: string; queue: string }) {
    escalations.push(escalation);
    return escalation;
  }
}

@Tool({
  name: "list_escalations",
  description: "List escalated tickets. Call this regularly to see new ones.",
  inputSchema: {},
  annotations: { readOnlyHint: true },
})
export class ListEscalations extends ToolContext {
  async execute() {
    return { escalations };
  }
}
```

```ts asking.test.ts
import { test, expect } from "@frontmcp/testing";

test("🚩 the client learns of an escalation only when it asks again", async ({ mcp }) => {
  const before = (await mcp.tools.call("list_escalations", {})).json();
  expect(before.escalations).toHaveLength(1);

  // Someone else escalates a ticket. Nothing reaches this client.
  await mcp.tools.call("escalate_ticket", { ticketId: "T-2", queue: "login" });

  const after = (await mcp.tools.call("list_escalations", {})).json();
  expect(after.escalations).toHaveLength(2);
});
```

The tool works, and it isn't enough:

- **The model has to decide to call it.** "Call this regularly" is a wish. A model calls a tool when a user's request makes it relevant, not on a timer.
- **Every look costs a turn**, and most of them find nothing new.
- **When the conversation ends, nobody is asking.** The ticket escalated at 3 a.m. waits for a user to come back and say "anything new?".

The server knows the moment a ticket is escalated. It needs a way to say so.

<a id="declaring-an-event-and-publishing-it"></a>

## Declaring an event and publishing it

An event is a named kind of thing that happens. `event()` declares one, with a description for the client's model and a schema for what each occurrence carries. `this.events.publish()` says that it just happened:

Initial call configuration:

```js
{ tool: "escalate_ticket", arguments: { ticketId: "T-2", queue: "login" } }
```

```ts ticket-escalated.event.ts active
import { event, z } from "@frontmcp/sdk";

export const ticketEscalated = event({
  name: "ticket.escalated",
  description: "A ticket was escalated to a queue's on-call agent. Read the ticket with get_ticket.",
  payloadSchema: { ticketId: z.string(), queue: z.string() },
});
```

```ts main.ts
import { App, Tool, ToolContext, z } from "@frontmcp/sdk";
import { ticketEscalated } from "./ticket-escalated.event";

@Tool({
  name: "escalate_ticket",
  description: "Escalate a ticket to a queue's on-call agent.",
  inputSchema: { ticketId: z.string(), queue: z.string() },
})
class EscalateTicket extends ToolContext {
  async execute(escalation: { ticketId: string; queue: string }) {
    const { eventId } = await this.events.publish(ticketEscalated, escalation);
    return { ...escalation, eventId };
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [EscalateTicket], events: [ticketEscalated] })
export class HelpDeskApp {}

// In your project: @FrontMcp(config) export default class Server {}
export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] };
```

```ts events.test.ts
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

test("the client can see what it may subscribe to", async () => {
  const client = await connect(config);
  const [definition] = await client.events.list();
  expect(definition).toMatchObject({
    name: "ticket.escalated",
    description: "A ticket was escalated to a queue's on-call agent. Read the ticket with get_ticket.",
    payloadSchema: { properties: { ticketId: { type: "string" }, queue: { type: "string" } }, required: ["ticketId", "queue"] },
  });
  await client.close();
});

test("✅ a client that subscribed is told, without asking again", async () => {
  const client = await connect(config);
  const subscription = await client.events.subscribe("ticket.escalated");

  // Someone escalates a ticket...
  await client.callTool("escalate_ticket", { ticketId: "T-2", queue: "login" });

  // ...and the occurrence arrives.
  for await (const occurrence of subscription) {
    expect(occurrence).toMatchObject({
      eventId: expect.stringMatching(/^evt_/),
      name: "ticket.escalated",
      data: { ticketId: "T-2", queue: "login" },
    });
    break;
  }
  await client.close();
});
```

Three things changed:

1. **`event()` declares it.** `name` is what clients subscribe to. `description` tells a model what the event means, as a tool's description does. `payloadSchema` is the shape of each occurrence's `data`, and clients get it as JSON Schema.
2. **`events: [ticketEscalated]` registers it** on the app. That alone turns events on for the server: no server option is needed.
3. **`this.events.publish(ticketEscalated, data)`** publishes one occurrence. FrontMCP checks `data` against `payloadSchema` first, gives the occurrence an `eventId` and a `timestamp`, and returns the id.

The tests use [`connect()`](https://frontmcp.dev/reference/sdk/connect), which runs the server inside the test and gives a client. `client.events.list()` asks what there is to subscribe to, and `client.events.subscribe()` returns a subscription you read with `for await`. Leaving the loop ends it.

There's also a class form, `@Event` on a class that extends `EventContext`. It takes the same options, and it's the one to use when an event needs [providers](https://frontmcp.dev/learn/sharing-state-with-providers) in its methods. The [`@Event` reference](https://frontmcp.dev/reference/sdk/event) covers both.

> **Pitfall: A payload is read by a model**
>
> A client hands an occurrence to its model, so whatever the payload carries lands in a prompt. Keep it small: an id, and the few fields a model needs to decide whether to act. Let it read the rest with a tool, where your authorization rules apply. And treat text that came from a user, like a ticket's title, as you would in a tool result: the model on the other side can't tell it from instructions.

<a id="how-a-client-receives-it"></a>

## How a client receives it

`subscribe()` hid a choice. MCP Events has three delivery modes, and a client uses the one that fits how it runs:

| Mode | What the client does | Fits |
| --- | --- | --- |
| `poll` | Sends `events/poll` every so often, with the cursor of the last answer | A script, or anything that can't hold a connection open |
| `push` | Holds one `events/stream` request open, and reads occurrences as they come | An app or an agent runtime that's connected anyway |
| `webhook` | Sends `events/subscribe` with a URL. The server calls that URL with each occurrence, signed | A hosted assistant that isn't connected when things happen |

The client in the tests is connected in the same process, so it streams. ChatGPT implements the webhook mode. Claude Code sends none of these requests, and gets events another way: see the Deep dive at the end of this lesson.

The client application subscribes, not the model. What it does with an occurrence is up to the client. One built for agents starts a turn and gives its model the payload, which is why the description and the payload are written for a model.

Whatever the mode, a client keeps a **cursor**: its position in the event's history. That's what lets a client that was away pick up where it left off, instead of starting over or missing things:

Initial call configuration:

```js
{ tool: "escalate_ticket", arguments: { ticketId: "T-2", queue: "login" } }
```

```ts cursor.test.ts active
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

test("a new subscription starts from now: what happened before isn't sent", async () => {
  const client = await connect(config);
  await client.callTool("escalate_ticket", { ticketId: "T-2", queue: "login" });

  const subscription = await client.events.subscribe("ticket.escalated");
  await client.callTool("escalate_ticket", { ticketId: "T-3", queue: "billing" });

  for await (const occurrence of subscription) {
    expect(occurrence.data).toEqual({ ticketId: "T-3", queue: "billing" });
    break;
  }
  await client.close();
});

test("a client that kept its cursor gets what happened while it was away", async () => {
  const client = await connect(config);
  const first = await client.events.subscribe("ticket.escalated");
  await client.callTool("escalate_ticket", { ticketId: "T-4", queue: "login" });
  for await (const occurrence of first) {
    expect(occurrence.data).toMatchObject({ ticketId: "T-4" });
    break;
  }
  const whereItStopped = first.cursor;

  // The client is away. A ticket is escalated meanwhile.
  await client.callTool("escalate_ticket", { ticketId: "T-5", queue: "billing" });

  // Back again, it subscribes from where it stopped.
  const second = await client.events.subscribe("ticket.escalated", {}, { cursor: whereItStopped });
  for await (const occurrence of second) {
    expect(occurrence.data).toEqual({ ticketId: "T-5", queue: "billing" });
    break;
  }
  await client.close();
});
```

```ts main.ts
import { App, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketEscalated = event({
  name: "ticket.escalated",
  description: "A ticket was escalated to a queue's on-call agent. Read the ticket with get_ticket.",
  payloadSchema: { ticketId: z.string(), queue: z.string() },
});

@Tool({
  name: "escalate_ticket",
  description: "Escalate a ticket to a queue's on-call agent.",
  inputSchema: { ticketId: z.string(), queue: z.string() },
})
class EscalateTicket extends ToolContext {
  async execute(escalation: { ticketId: string; queue: string }) {
    const { eventId } = await this.events.publish(ticketEscalated, escalation);
    return { ...escalation, eventId };
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [EscalateTicket], events: [ticketEscalated] })
export class HelpDeskApp {}

export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] };
```

> **Pitfall: The history is ten minutes of one process's memory**
>
> FrontMCP keeps what `publish()` published in memory, for ten minutes. A cursor older than that, or one from before a restart, can't be placed. The client isn't refused: it's answered `truncated: true` and a fresh cursor, which means "you missed something". A client that needs the full picture then reads the current state with a tool. When your own database can answer "what changed since position N", an event can read from it instead: see [reading an upstream that can replay](https://frontmcp.dev/reference/sdk/event#reading-an-upstream-that-can-replay).

[Event subscriptions and delivery](https://frontmcp.dev/reference/sdk/event-delivery) has each request as it goes over the wire, and what a webhook delivery looks like.

<a id="letting-a-subscriber-filter"></a>

## Letting a subscriber filter

An agent on call for billing subscribes to `ticket.escalated`, and is told about every queue's escalations:

Initial call configuration:

```js
{ tool: "escalate_ticket", arguments: { ticketId: "T-2", queue: "login" } }
```

```ts noise.test.ts active
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

test("🚩 the billing agent is told about a login ticket", async () => {
  const billingAgent = await connect(config);
  const subscription = await billingAgent.events.subscribe("ticket.escalated");

  await billingAgent.callTool("escalate_ticket", { ticketId: "T-2", queue: "login" });

  for await (const occurrence of subscription) {
    expect(occurrence.data).toEqual({ ticketId: "T-2", queue: "login" });
    break;
  }
  await billingAgent.close();
});
```

```ts main.ts
import { App, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketEscalated = event({
  name: "ticket.escalated",
  description: "A ticket was escalated to a queue's on-call agent. Read the ticket with get_ticket.",
  payloadSchema: { ticketId: z.string(), queue: z.string() },
});

@Tool({
  name: "escalate_ticket",
  description: "Escalate a ticket to a queue's on-call agent.",
  inputSchema: { ticketId: z.string(), queue: z.string() },
})
class EscalateTicket extends ToolContext {
  async execute(escalation: { ticketId: string; queue: string }) {
    const { eventId } = await this.events.publish(ticketEscalated, escalation);
    return { ...escalation, eventId };
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [EscalateTicket], events: [ticketEscalated] })
export class HelpDeskApp {}

export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] };
```

Each occurrence a model is given costs it a turn and some of its context, so an event nobody can narrow gets ignored or unsubscribed. The client could drop what it doesn't want, but it has already been woken up by then. Let the subscriber say what it wants, and filter on the server. `inputSchema` declares a subscription's arguments, and `match()` decides, per subscriber, whether an occurrence is for it:

Initial call configuration:

```js
{ tool: "escalate_ticket", arguments: { ticketId: "T-2", queue: "login" } }
```

```ts ticket-escalated.event.ts active
import { event, z } from "@frontmcp/sdk";

export const ticketEscalated = event({
  name: "ticket.escalated",
  description: "A ticket was escalated to a queue's on-call agent. Read the ticket with get_ticket.",
  inputSchema: { queue: z.string().optional().describe("Only tickets escalated to this queue, like billing") },
  payloadSchema: { ticketId: z.string(), queue: z.string() },
  match(occurrence, args) {
    return args.queue === undefined || args.queue === occurrence.data.queue;
  },
});
```

```ts main.ts
import { App, Tool, ToolContext, z } from "@frontmcp/sdk";
import { ticketEscalated } from "./ticket-escalated.event";

@Tool({
  name: "escalate_ticket",
  description: "Escalate a ticket to a queue's on-call agent.",
  inputSchema: { ticketId: z.string(), queue: z.string() },
})
class EscalateTicket extends ToolContext {
  async execute(escalation: { ticketId: string; queue: string }) {
    const { eventId } = await this.events.publish(ticketEscalated, escalation);
    return { ...escalation, eventId };
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [EscalateTicket], events: [ticketEscalated] })
export class HelpDeskApp {}

export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] };
```

```ts filter.test.ts
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

test("✅ the billing agent hears about billing only", async () => {
  const billingAgent = await connect(config);
  const subscription = await billingAgent.events.subscribe("ticket.escalated", { queue: "billing" });

  await billingAgent.callTool("escalate_ticket", { ticketId: "T-2", queue: "login" });
  await billingAgent.callTool("escalate_ticket", { ticketId: "T-3", queue: "billing" });

  // The first thing it hears is the billing ticket: the login one was never sent.
  for await (const occurrence of subscription) {
    expect(occurrence.data).toEqual({ ticketId: "T-3", queue: "billing" });
    break;
  }
  await billingAgent.close();
});

test("a subscriber with no arguments still gets everything", async () => {
  const supervisor = await connect(config);
  const subscription = await supervisor.events.subscribe("ticket.escalated");
  await supervisor.callTool("escalate_ticket", { ticketId: "T-4", queue: "login" });
  for await (const occurrence of subscription) {
    expect(occurrence.data).toEqual({ ticketId: "T-4", queue: "login" });
    break;
  }
  await supervisor.close();
});

test("the arguments are described to the client's model", async () => {
  const client = await connect(config);
  const [definition] = await client.events.list();
  expect(definition.inputSchema.properties).toEqual({
    queue: { type: "string", description: "Only tickets escalated to this queue, like billing" },
  });
  await client.close();
});
```

Arguments are a contract, like a tool's input. They're validated when a client subscribes, so one that sends `{ queue: 7 }` is refused, and `.describe()` reaches the model that picks them. [Schemas Are Contracts](https://frontmcp.dev/learn/schemas-are-contracts) applies here unchanged.

<a id="deciding-who-hears-it"></a>

## Deciding who hears it

So far anyone who can reach the server can subscribe, and every subscriber hears every occurrence that matches what it asked for. The help desk serves two companies, and its tickets carry a customer's name:

Initial call configuration:

```js
{ tool: "create_ticket", arguments: { tenant: "acme", customer: "Dana Reyes" } }
```

```ts leak.test.ts active
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

test("🚩 another company's agent is told about Acme's ticket, with the customer's name", async () => {
  const globexAgent = await connect(config, { session: { user: { sub: "sam", roles: ["agent"], tenantId: "globex" } } });
  const subscription = await globexAgent.events.subscribe("ticket.created");

  await globexAgent.callTool("create_ticket", { tenant: "acme", customer: "Dana Reyes" });

  for await (const occurrence of subscription) {
    expect(occurrence.data).toEqual({ ticketId: "acme-1", customer: "Dana Reyes" });
    break;
  }
  await globexAgent.close();
});

test("🚩 so is a caller who never signed in", async () => {
  const anonymous = await connect(config);
  expect((await anonymous.events.list()).map((definition) => definition.name)).toEqual(["ticket.created"]);
  const subscription = await anonymous.events.subscribe("ticket.created");

  await anonymous.callTool("create_ticket", { tenant: "acme", customer: "Dana Reyes" });

  for await (const occurrence of subscription) {
    expect(occurrence.data).toEqual({ ticketId: "acme-1", customer: "Dana Reyes" });
    break;
  }
  await anonymous.close();
});
```

```ts main.ts
import { App, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketCreated = event({
  name: "ticket.created",
  description: "A customer opened a support ticket.",
  payloadSchema: { ticketId: z.string(), customer: z.string() },
});

@Tool({ name: "create_ticket", description: "Open a support ticket.", inputSchema: { tenant: z.string(), customer: z.string() } })
class CreateTicket extends ToolContext {
  async execute({ tenant, customer }: { tenant: string; customer: string }) {
    return this.events.publish(ticketCreated, { ticketId: `${tenant}-1`, customer });
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], events: [ticketCreated] })
export class HelpDeskApp {}

export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] };
```

`session.user` names the caller of a `connect()` client, as a token's claims do over HTTP. Two different questions need answering here, and each has its own setting:

- **Who may subscribe at all?** `authorities` on the event, the same rule a tool takes in [Deciding Who Can Call What](https://frontmcp.dev/learn/authorizing-calls). A caller the rule refuses doesn't see the event in `events/list`, and can't subscribe by name.
- **Who is this occurrence for?** `audience` on `publish()`. It names the subscribers one occurrence goes to, by their `sub`, their tenant or their roles.

Initial call configuration:

```js
{ tool: "create_ticket", arguments: { tenant: "acme", customer: "Dana Reyes" } }
```

```ts main.ts active
import { App, FrontMcp, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketCreated = event({
  name: "ticket.created",
  description: "A customer opened a support ticket.",
  payloadSchema: { ticketId: z.string(), customer: z.string() },
  // Who may subscribe: agents only.
  authorities: "agent",
});

@Tool({ name: "create_ticket", description: "Open a support ticket.", inputSchema: { tenant: z.string(), customer: z.string() } })
class CreateTicket extends ToolContext {
  async execute({ tenant, customer }: { tenant: string; customer: string }) {
    return this.events.publish(
      ticketCreated,
      { ticketId: `${tenant}-1`, customer },
      // Who this occurrence is for: the agents of the ticket's own company.
      { audience: { tenantId: tenant } },
    );
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], events: [ticketCreated] })
class HelpDeskApp {}

export const config = {
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDeskApp],
  authorities: {
    // Where a caller's roles and company are: the token's `roles` and `tenantId` claims.
    claimsMapping: { roles: "roles", tenantId: "tenantId" },
    profiles: { agent: { roles: { any: ["agent"] } } },
  },
};

@FrontMcp(config)
export default class Server {}
```

```ts audience.test.ts
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

const acmeAgent = { session: { user: { sub: "nour", roles: ["agent"], tenantId: "acme" } } };
const globexAgent = { session: { user: { sub: "sam", roles: ["agent"], tenantId: "globex" } } };

test("✅ a caller who never signed in doesn't see the event, and can't subscribe by name", async () => {
  const anonymous = await connect(config);
  expect(await anonymous.events.list()).toEqual([]);
  await expect(anonymous.events.subscribe("ticket.created")).rejects.toMatchObject({ rpcCode: -32024 });
  await anonymous.close();
});

test("✅ each company's agent hears about its own tickets only", async () => {
  const nour = await connect(config, acmeAgent);
  const sam = await connect(config, globexAgent);
  const forAcme = await nour.events.subscribe("ticket.created");
  const forGlobex = await sam.events.subscribe("ticket.created");

  await nour.callTool("create_ticket", { tenant: "acme", customer: "Dana Reyes" });
  await nour.callTool("create_ticket", { tenant: "globex", customer: "Omar Haddad" });

  for await (const occurrence of forAcme) {
    expect(occurrence.data).toEqual({ ticketId: "acme-1", customer: "Dana Reyes" });
    break;
  }
  // The first thing Globex's agent hears is Globex's ticket: Acme's was never sent to it.
  for await (const occurrence of forGlobex) {
    expect(occurrence.data).toEqual({ ticketId: "globex-1", customer: "Omar Haddad" });
    break;
  }
  await nour.close();
  await sam.close();
});
```

`-32024` is the events error `Forbidden`. `match()` could have compared tenants too, but it reads what a subscriber asked for, and a subscriber shouldn't be the one to say which company it belongs to. `audience` comes from the publisher, and is compared with who the subscriber is.

> **Pitfall: A webhook subscriber is checked again later, not on every occurrence**
>
> A webhook subscription can live for hours after the caller subscribed. FrontMCP checks its owner against `authorities` again once the last check is older than five minutes, and ends the subscription of an owner who lost access. A caller that polls is checked on every poll. [Access over a subscription's life](https://frontmcp.dev/reference/sdk/event-delivery#access-over-a-subscriptions-life) has the details.

<a id="publishing-when-nobody-called"></a>

## Publishing when nobody called

Every occurrence so far was published by a tool, so somebody still had to call something. The ticket that passes its SLA at 3 a.m. is noticed by nobody. Code that runs by itself has to publish it.

A tool has `this.events`. Code outside a call, like a [provider](https://frontmcp.dev/learn/sharing-state-with-providers), takes the server's publisher when it's built. This one checks the queue on a timer it starts once the server is ready:

```ts queue-monitor.ts active
import { AsyncProvider, EVENT_PUBLISHER, type EventPublisher } from "@frontmcp/sdk";
import { slaBreached } from "./sla-breached.event";

// T-1 may wait 60 ms. A real SLA is hours, and the tickets are in a database.
const tickets = [{ id: "T-1", openedAt: Date.now(), limitMs: 60 }];

class QueueMonitor {
  private timer?: ReturnType<typeof setInterval>;
  private readonly reported = new Set<string>();

  constructor(private readonly events: EventPublisher) {}

  // Runs once the server is ready to serve.
  onReady() {
    this.timer = setInterval(() => void this.reportBreaches(), 20);
  }

  onShutdown() {
    clearInterval(this.timer);
  }

  private async reportBreaches() {
    for (const ticket of tickets) {
      const breached = Date.now() - ticket.openedAt >= ticket.limitMs;
      if (!breached || this.reported.has(ticket.id)) continue;
      this.reported.add(ticket.id);
      await this.events.publish(slaBreached, { ticketId: ticket.id });
    }
  }
}

// Hands the monitor the server's publisher when the server builds it.
export const queueMonitor = AsyncProvider({
  provide: QueueMonitor,
  name: "queue-monitor",
  inject: () => [EVENT_PUBLISHER] as const,
  useFactory: (events) => new QueueMonitor(events),
});
```

```ts sla-breached.event.ts
import { event, z } from "@frontmcp/sdk";

export const slaBreached = event({
  name: "ticket.sla_breached",
  description: "A ticket has waited longer than its SLA allows. Read it with get_ticket, then reply or escalate.",
  payloadSchema: { ticketId: z.string() },
});
```

```ts main.ts
import { App } from "@frontmcp/sdk";
import { queueMonitor } from "./queue-monitor";
import { slaBreached } from "./sla-breached.event";

@App({ id: "help-desk", name: "Help Desk", events: [slaBreached], providers: [queueMonitor] })
export class HelpDeskApp {}

export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] };
```

```ts background.test.ts
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

test("✅ the client is told, and nobody called a tool", async () => {
  const client = await connect(config);
  const subscription = await client.events.subscribe("ticket.sla_breached");
  for await (const occurrence of subscription) {
    expect(occurrence.data).toEqual({ ticketId: "T-1" });
    break;
  }
  await client.close();
});
```

This server has no tools at all. The test subscribes and waits, and the occurrence arrives because time passed.

A timer in a provider is fine for a lesson, and has two problems in production: with several copies of the server, each copy runs it and publishes, and nothing restarts it when it throws. FrontMCP has two decorators for background code that solve both, and each takes the publisher the same way:

| Use | When the work |
| --- | --- |
| A [duty](https://frontmcp.dev/reference/sdk/duty) | Runs on a schedule and ends, like this check every minute |
| A [worker](https://frontmcp.dev/reference/sdk/worker) | Stays connected or keeps watching, like a mail connection or a folder watcher |

A third source needs no code inside the server: another service can publish with one signed HTTP request, to [the publish endpoint](https://frontmcp.dev/reference/sdk/events-options#eventspublishendpoint).

### What about Claude Code?

Claude Code doesn't send `events/list`, `events/poll` or `events/stream`. What a Claude Code session reads from a server while it's open is a [channel](https://frontmcp.dev/reference/sdk/channel) notification, which arrives in the conversation as a `<channel>` tag.

An event reaches those sessions too once it has the `channel` option:

```ts
export const slaBreached = event({
  name: "ticket.sla_breached",
  payloadSchema: { ticketId: z.string() },
  channel: { content: (payload) => `Ticket ${payload.ticketId} is past its SLA` },
});
```

Each time it's published, the sessions connected to that server process are told as well. It isn't a fourth delivery mode: nothing is stored, `events/list` doesn't show it, and a session that isn't open misses it. The event's `authorities` and the publish's `audience` still decide which sessions hear it. See [the `channel` option](https://frontmcp.dev/reference/sdk/event#the-channel-option).

<a id="recap"></a>

## Recap

- A tool answers when it's asked. An event tells a client that something happened, when it happens, and also when no conversation is open.
- `event({ name, description, payloadSchema })` declares an event, and listing it in an app's `events` turns events on. `this.events.publish(event, data)` publishes one occurrence, after checking `data` against the schema.
- A client receives occurrences by `poll`, `push` (a stream) or `webhook`, and keeps a cursor so it can continue where it stopped. Published occurrences are kept ten minutes, in one process's memory. A cursor that can't be placed is answered `truncated: true`, not an error.
- `inputSchema` and `match()` let each subscriber filter on the server, so a model is given only what it asked to hear.
- `authorities` on the event decides who may subscribe. `audience` on `publish()` decides who one occurrence is for.
- Code outside a call takes the publisher when it's built, with `EVENT_PUBLISHER`, and publishes when nobody called anything. Use a duty or a worker for that in production.
- MCP Events is a draft extension of MCP. A payload ends up in a model's prompt: keep it to ids and a few fields.

<a id="try-some-challenges"></a>

## Try some challenges

Each challenge runs hidden checks against your code. Edit the code, then press **Check**.

### Challenge: Say when a ticket is closed

`close_ticket` closes a ticket, and nobody is told. The event `ticket.closed` is already declared and registered. Publish it from the tool, with the ticket's id and the reason it was closed.

Initial call configuration:

```js
{ tool: "close_ticket", arguments: { ticketId: "T-1", reason: "resolved" } }
```

```ts main.ts active
import { App, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketClosed = event({
  name: "ticket.closed",
  description: "A support ticket was closed.",
  payloadSchema: { ticketId: z.string(), reason: z.enum(["resolved", "duplicate"]) },
});

@Tool({
  name: "close_ticket",
  description: "Close a support ticket.",
  inputSchema: { ticketId: z.string(), reason: z.enum(["resolved", "duplicate"]) },
})
class CloseTicket extends ToolContext {
  async execute({ ticketId, reason }: { ticketId: string; reason: "resolved" | "duplicate" }) {
    return { ticketId, closed: true };
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], events: [ticketClosed] })
export class HelpDeskApp {}

export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] };
```

**Solution file (alternative to the starter):**

```ts main.ts solution
import { App, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketClosed = event({
  name: "ticket.closed",
  description: "A support ticket was closed.",
  payloadSchema: { ticketId: z.string(), reason: z.enum(["resolved", "duplicate"]) },
});

@Tool({
  name: "close_ticket",
  description: "Close a support ticket.",
  inputSchema: { ticketId: z.string(), reason: z.enum(["resolved", "duplicate"]) },
})
class CloseTicket extends ToolContext {
  async execute({ ticketId, reason }: { ticketId: string; reason: "resolved" | "duplicate" }) {
    await this.events.publish(ticketClosed, { ticketId, reason });
    return { ticketId, closed: true };
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], events: [ticketClosed] })
export class HelpDeskApp {}

export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] };
```

**Hidden fixture/test file (runs with the example):**

```ts closed.test.ts hidden
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

type Subscription = AsyncIterable<{ data: unknown }> & { cancel(): Promise<void> };

/** The next occurrence's data, or undefined when none arrives in time. */
async function nextOrNothing(subscription: Subscription, waitMs = 300) {
  const iterator = subscription[Symbol.asyncIterator]();
  const next = iterator.next().then((step) => (step.done ? undefined : step.value.data));
  const nothing = new Promise<undefined>((resolve) => setTimeout(() => resolve(undefined), waitMs));
  const data = await Promise.race([next, nothing]);
  await subscription.cancel();
  return data;
}

test("`close_ticket` still closes the ticket", async () => {
  const client = await connect(config);
  const result = await client.callTool("close_ticket", { ticketId: "T-1", reason: "resolved" });
  expect(result.structuredContent).toMatchObject({ ticketId: "T-1", closed: true });
  await client.close();
});

test("a subscriber to `ticket.closed` is told when a ticket is closed", async () => {
  const client = await connect(config);
  const subscription = await client.events.subscribe("ticket.closed");
  await client.callTool("close_ticket", { ticketId: "T-2", reason: "duplicate" });
  expect(await nextOrNothing(subscription)).toBeDefined();
  await client.close();
});

test("the occurrence carries the ticket's id and the reason", async () => {
  const client = await connect(config);
  const subscription = await client.events.subscribe("ticket.closed");
  await client.callTool("close_ticket", { ticketId: "T-3", reason: "duplicate" });
  expect(await nextOrNothing(subscription)).toEqual({ ticketId: "T-3", reason: "duplicate" });
  await client.close();
});
```

**Hint:**

A tool publishes with `this.events.publish()`. Its first argument is the event, its second the data.

**Solution:**

`await this.events.publish(ticketClosed, { ticketId, reason })` is the whole change. Passing `ticketClosed` itself, not the string `"ticket.closed"`, lets TypeScript check the data against `payloadSchema`: leave out `reason` and it doesn't compile. Publish after the ticket is closed, so a subscriber is never told about something that then failed.

### Challenge: Only the priority I asked for

`ticket.created` goes to every subscriber, whatever the ticket's priority. Let a subscriber pass `{ priority: "high" }` or `{ priority: "normal" }` and hear about those tickets only. A subscriber that passes nothing should still get every ticket.

Initial call configuration:

```js
{ tool: "create_ticket", arguments: { priority: "normal" } }
```

```ts ticket-created.event.ts active
import { event, z } from "@frontmcp/sdk";

export const ticketCreated = event({
  name: "ticket.created",
  description: "A customer opened a support ticket.",
  payloadSchema: { ticketId: z.string(), priority: z.enum(["high", "normal"]) },
});
```

**Solution file (alternative to the starter):**

```ts ticket-created.event.ts solution
import { event, z } from "@frontmcp/sdk";

export const ticketCreated = event({
  name: "ticket.created",
  description: "A customer opened a support ticket.",
  inputSchema: { priority: z.enum(["high", "normal"]).optional().describe("Only tickets of this priority") },
  payloadSchema: { ticketId: z.string(), priority: z.enum(["high", "normal"]) },
  match(occurrence, args) {
    return args.priority === undefined || args.priority === occurrence.data.priority;
  },
});
```

```ts main.ts
import { App, Tool, ToolContext, z } from "@frontmcp/sdk";
import { ticketCreated } from "./ticket-created.event";

let nextId = 4;

@Tool({ name: "create_ticket", description: "Open a support ticket.", inputSchema: { priority: z.enum(["high", "normal"]) } })
class CreateTicket extends ToolContext {
  async execute({ priority }: { priority: "high" | "normal" }) {
    return this.events.publish(ticketCreated, { ticketId: `T-${nextId++}`, priority });
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], events: [ticketCreated] })
export class HelpDeskApp {}

export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] };
```

**Hidden fixture/test file (runs with the example):**

```ts priority.test.ts hidden
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

type Occurrence = { data: { priority: string } };
type Subscription = AsyncIterable<Occurrence> & { cancel(): Promise<void> };

/** The priorities of the occurrences that arrive within the wait. */
async function prioritiesHeard(subscription: Subscription, waitMs = 300) {
  const heard: string[] = [];
  const reading = (async () => {
    for await (const occurrence of subscription) heard.push(occurrence.data.priority);
  })();
  await new Promise((resolve) => setTimeout(resolve, waitMs));
  await subscription.cancel();
  await reading.catch(() => undefined);
  return heard;
}

test("a subscriber that asks for `high` hears about high-priority tickets only", async () => {
  const client = await connect(config);
  const subscribing = client.events.subscribe("ticket.created", { priority: "high" });
  await expect(subscribing).resolves.toBeDefined();
  const subscription = await subscribing;
  for (const priority of ["normal", "high", "normal"]) await client.callTool("create_ticket", { priority });
  expect(await prioritiesHeard(subscription)).toEqual(["high"]);
  await client.close();
});

test("a subscriber that passes nothing hears about every ticket", async () => {
  const client = await connect(config);
  const subscription = await client.events.subscribe("ticket.created");
  for (const priority of ["normal", "high"]) await client.callTool("create_ticket", { priority });
  expect(await prioritiesHeard(subscription)).toEqual(["normal", "high"]);
  await client.close();
});

test("`priority` is optional, and is one of `high` and `normal`", async () => {
  const client = await connect(config);
  const [definition] = await client.events.list();
  expect(definition.inputSchema.properties?.priority).toMatchObject({ enum: ["high", "normal"] });
  expect(definition.inputSchema.required ?? []).not.toContain("priority");
  await expect(client.events.subscribe("ticket.created", { priority: "urgent" })).rejects.toMatchObject({ rpcCode: -32602 });
  await client.close();
});
```

**Hint:**

An event needs two things to filter: `inputSchema`, for what a subscriber may pass, and `match(occurrence, args)`, which returns whether this occurrence is for a subscriber with those arguments.

**Solution:**

`inputSchema` declares `priority` as an optional enum, so a subscriber may leave it out, and one that sends `"urgent"` is refused when it subscribes. `match()` returns `true` when the subscriber passed no priority, or passed the occurrence's. Without `match()`, the arguments would be validated and then ignored: every subscriber would still get every ticket.

### Challenge: Keep each company's tickets to itself

The help desk serves two companies, and `ticket.created` reaches the agents of both. Change `create_ticket` so that a ticket is published to the agents of its own company only. A caller's company is the `tenantId` claim of its token, which the server's `claimsMapping` already reads.

Initial call configuration:

```js
{ tool: "create_ticket", arguments: { tenant: "acme", title: "Cannot log in" } }
```

```ts main.ts active
import { App, FrontMcp, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketCreated = event({
  name: "ticket.created",
  description: "A customer opened a support ticket.",
  payloadSchema: { ticketId: z.string(), title: z.string() },
});

@Tool({ name: "create_ticket", description: "Open a support ticket.", inputSchema: { tenant: z.string(), title: z.string() } })
class CreateTicket extends ToolContext {
  async execute({ tenant, title }: { tenant: string; title: string }) {
    return this.events.publish(ticketCreated, { ticketId: `${tenant}-1`, title });
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], events: [ticketCreated] })
class HelpDeskApp {}

export const config = {
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDeskApp],
  authorities: { claimsMapping: { roles: "roles", tenantId: "tenantId" } },
};

@FrontMcp(config)
export default class Server {}
```

**Solution file (alternative to the starter):**

```ts main.ts solution
import { App, FrontMcp, Tool, ToolContext, event, z } from "@frontmcp/sdk";

export const ticketCreated = event({
  name: "ticket.created",
  description: "A customer opened a support ticket.",
  payloadSchema: { ticketId: z.string(), title: z.string() },
});

@Tool({ name: "create_ticket", description: "Open a support ticket.", inputSchema: { tenant: z.string(), title: z.string() } })
class CreateTicket extends ToolContext {
  async execute({ tenant, title }: { tenant: string; title: string }) {
    return this.events.publish(ticketCreated, { ticketId: `${tenant}-1`, title }, { audience: { tenantId: tenant } });
  }
}

@App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], events: [ticketCreated] })
class HelpDeskApp {}

export const config = {
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDeskApp],
  authorities: { claimsMapping: { roles: "roles", tenantId: "tenantId" } },
};

@FrontMcp(config)
export default class Server {}
```

**Hidden fixture/test file (runs with the example):**

```ts tenants.test.ts hidden
import { test, expect } from "@frontmcp/testing";
import { connect } from "@frontmcp/sdk";
import { config } from "./main";

type Subscription = AsyncIterable<{ data: { ticketId: string } }> & { cancel(): Promise<void> };

/** The ids of the tickets a subscriber hears about within the wait. */
async function ticketsHeard(subscription: Subscription, waitMs = 300) {
  const heard: string[] = [];
  const reading = (async () => {
    for await (const occurrence of subscription) heard.push(occurrence.data.ticketId);
  })();
  await new Promise((resolve) => setTimeout(resolve, waitMs));
  await subscription.cancel();
  await reading.catch(() => undefined);
  return heard;
}

const agentOf = (tenantId: string) => ({ session: { user: { sub: `agent-of-${tenantId}`, roles: ["agent"], tenantId } } });

test("an agent of the ticket's company is told about it", async () => {
  const acme = await connect(config, agentOf("acme"));
  const subscription = await acme.events.subscribe("ticket.created");
  await acme.callTool("create_ticket", { tenant: "acme", title: "Cannot log in" });
  expect(await ticketsHeard(subscription)).toEqual(["acme-1"]);
  await acme.close();
});

test("an agent of another company isn't", async () => {
  const globex = await connect(config, agentOf("globex"));
  const subscription = await globex.events.subscribe("ticket.created");
  await globex.callTool("create_ticket", { tenant: "acme", title: "Cannot log in" });
  expect(await ticketsHeard(subscription)).toEqual([]);
  await globex.close();
});

test("each company's agent hears about its own tickets", async () => {
  const globex = await connect(config, agentOf("globex"));
  const subscription = await globex.events.subscribe("ticket.created");
  await globex.callTool("create_ticket", { tenant: "acme", title: "Cannot log in" });
  await globex.callTool("create_ticket", { tenant: "globex", title: "Invoice total is wrong" });
  expect(await ticketsHeard(subscription)).toEqual(["globex-1"]);
  await globex.close();
});
```

**Hint:**

`publish()` takes a third argument. Its `audience` names who an occurrence is for, and one of the things it can name is a tenant.

**Solution:**

`{ audience: { tenantId: tenant } }` sends each occurrence to the subscribers whose `tenantId` is the ticket's company. Nothing changes for the subscriber: both companies' agents subscribe to the same event with the same arguments, and each hears its own. The check happens on the server, against who the subscriber is, so a subscriber can't ask its way into another company's tickets. A `match()` that compared an argument like `{ tenant }` would let it.
