Telling Clients Something Happened
Checked against FrontMCP 1.12.2 on
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
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:
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 };
}
}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
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.
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:
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() },
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Three things changed:
event()declares it.nameis what clients subscribe to.descriptiontells a model what the event means, as a tool's description does.payloadSchemais the shape of each occurrence'sdata, and clients get it as JSON Schema.events: [ticketEscalated]registers it on the app. That alone turns events on for the server: no server option is needed.this.events.publish(ticketEscalated, data)publishes one occurrence. FrontMCP checksdataagainstpayloadSchemafirst, gives the occurrence aneventIdand atimestamp, and returns the id.
The tests use 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 in its methods. The @Event reference covers both.
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:
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();
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
Event subscriptions and delivery has each request as it goes over the wire, and what a webhook delivery looks like.
Letting a subscriber filter
An agent on call for billing subscribes to ticket.escalated, and is told about every queue's escalations:
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();
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
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:
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;
},
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
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 applies here unchanged.
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:
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();
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
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?
authoritieson the event, the same rule a tool takes in Deciding Who Can Call What. A caller the rule refuses doesn't see the event inevents/list, and can't subscribe by name. - Who is this occurrence for?
audienceonpublish(). It names the subscribers one occurrence goes to, by theirsub, their tenant or their roles.
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 {}Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
-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.
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, takes the server's publisher when it's built. This one checks the queue on a timer it starts once the server is ready:
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),
});Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.
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 | Runs on a schedule and ends, like this check every minute |
| A 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.
Deep diveWhat about Claude Code?Show detailsHide details
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 notification, which arrives in the conversation as a <channel> tag.
An event reaches those sessions too once it has the channel option:
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.
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'seventsturns events on.this.events.publish(event, data)publishes one occurrence, after checkingdataagainst the schema.- A client receives occurrences by
poll,push(a stream) orwebhook, 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 answeredtruncated: true, not an error. inputSchemaandmatch()let each subscriber filter on the server, so a model is given only what it asked to hear.authoritieson the event decides who may subscribe.audienceonpublish()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.
Try some challenges
Each challenge runs hidden checks against your code. Edit the code, then press Check.
Read all challenge instructions
Say when a ticket is closed
This challenge is open below.
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.
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"]) },
});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] };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.
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 {}Challenge 1 of 3
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.
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] };Starting FrontMCP in your browser…
FrontMCP starts when this example comes into view.