# FrontMCP > FrontMCP is the TypeScript framework for MCP servers: typed tools with Zod, dependency injection, auth, testing, agents and jobs, and builds for Node, Vercel, AWS Lambda and Cloudflare Workers. The full text of the MDX documentation and blog posts on https://frontmcp.dev, as Markdown, in reading order: Learn, Reference, Examples, Compare, then the blog. It documents FrontMCP 1.12.2. The index of pages is at https://frontmcp.dev/llms.txt. This bulk file excludes the homepage and standalone indexes; read /index.md, /versions.md, /releases.md, /blog.md and /playground.md separately. Prefer a page or docs MCP section read when context is limited. Historical articles retain their own scope and are not automatically verified against the snapshot release. --- # Quick Start: build an MCP server in TypeScript > Build an MCP server in TypeScript with FrontMCP. The 80% you'll use every day, with every example running in your browser. Source: https://frontmcp.dev/learn [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Welcome to FrontMCP. This page covers the concepts you'll use most days when building an MCP server. Every example runs the real FrontMCP SDK in your browser: change the code and the server restarts with your edits. **You will learn** - How to define a tool, and what an AI model sees when it looks at one - How schemas check input before your code runs - How to return structured results - How to expose data with resources and reusable prompts - How apps and a server fit together - How to share a service between tools with a provider ## The quick path Six steps take you from an empty folder to an MCP client calling your own tool. You need Node.js 24 or later. The sections after this list teach each piece in the browser first. 1. **Create the project.** Run `npx frontmcp create my-mcp-server`, then `cd my-mcp-server` and `npm install`: `create` writes the files but installs nothing ([Installation](https://frontmcp.dev/learn/installation#creating-a-new-server), [`frontmcp create`](https://frontmcp.dev/reference/cli#frontmcp-create)). 2. **Run it.** `npm run dev` runs `frontmcp dev`, which restarts the server when you save a file. The server answers at `http://localhost:3000/mcp` ([`frontmcp dev`](https://frontmcp.dev/reference/cli#frontmcp-dev)). 3. **Write a tool.** The project starts with one, `add`, in `src/tools/add.tool.ts`: a class with `@Tool` that extends `ToolContext`. Add yours beside it and list it in its app's `tools` ([Creating a tool](https://frontmcp.dev/learn#creating-a-tool), [Your First Tool](https://frontmcp.dev/learn/your-first-tool)). 4. **Inspect and test it.** With the server running, `npm run inspect` opens the MCP Inspector, where you can connect and call your tool. `npm test` runs the project's end-to-end tests with `frontmcp test` ([Running and testing your server](https://frontmcp.dev/learn/installation#running-and-testing-your-server), [Testing Your Server](https://frontmcp.dev/learn/testing-your-server)). 5. **Connect a client.** Add `http://localhost:3000/mcp` to the MCP servers in your client's settings, like Claude Code or Cursor. The field that marks an entry as a URL differs between clients ([Connecting a client](https://frontmcp.dev/learn/installation#connecting-a-client), [Connecting to `frontmcp dev`](https://frontmcp.dev/reference/deployment/mcp-clients#connecting-to-frontmcp-dev)). 6. **Go further.** Learn tools properly in [Describing Capabilities](https://frontmcp.dev/learn/describing-capabilities), then decide who may call them in [Securing a Server](https://frontmcp.dev/learn/securing-a-server) and put the server online in [Deploying Your Server](https://frontmcp.dev/learn/deploying-your-server). ## Creating a tool An MCP server gives AI clients, like Claude or Cursor, a set of **capabilities**. The most common kind is a **tool**: a function the model can decide to call when it needs to act or look something up. In FrontMCP, a tool is a class decorated with `@Tool` that extends `ToolContext` and implements `execute()`: Initial call configuration: ```js { tool: "add", arguments: { a: 2, b: 3 } } ``` ```ts add.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "add", description: "Adds two numbers together", inputSchema: { a: z.number(), b: z.number() }, }) export class AddTool extends ToolContext { async execute(input: { a: number; b: number }) { return input.a + input.b; } } ``` The panel on the right is an MCP client talking to your server: - **Capabilities** shows what `tools/list` returns. That card is everything the model knows about your tool, so the name and description are the model's only documentation. - **Call** sends `tools/call`. The page already sent `{ "a": 2, "b": 3 }`, and the result came back as `{ "value": 5 }`. - **Wire** shows each JSON-RPC request and response exactly as a client would send and receive them. Try changing `description` and watch the Capabilities card change. ## Checking input with schemas `inputSchema` is written with [Zod](https://zod.dev), re-exported from `@frontmcp/sdk` as `z`. FrontMCP turns it into the JSON Schema the model reads, and checks every call against it **before** `execute()` runs. Initial call configuration: ```js { tool: "greet", arguments: { name: "Ada", style: "formal" } } ``` ```ts greet.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "greet", description: "Greets someone by name", inputSchema: { name: z.string().min(1).describe("Who to greet"), style: z.enum(["casual", "formal"]).default("casual"), }, }) export class GreetTool extends ToolContext { async execute({ name, style }: { name: string; style: "casual" | "formal" }) { return style === "formal" ? `Good day, ${name}.` : `Hi ${name}!`; } } ``` Clear the **name** field and call it again. FrontMCP rejects the call with `Invalid tool input` and a list of what's wrong, and your `execute()` never runs. The model gets that message back and can correct itself. `.describe()` text shows up next to the field in the Capabilities tab. Models use it the same way you'd use a parameter comment. ## Returning structured results Whatever `execute()` returns is sent back to the client. Plain values, like the number and string above, arrive wrapped as `{ "value": ... }`. When the result has a shape, declare it with `outputSchema`, so clients know what fields to expect before they call: Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts search-tickets.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ] as const; @Tool({ name: "search_tickets", description: "Search support tickets by words in the title", inputSchema: { query: z.string().min(1) }, outputSchema: z.object({ tickets: z.array(z.object({ id: z.string(), title: z.string(), status: z.enum(["open", "closed"]) })), }), annotations: { readOnlyHint: true }, }) export class SearchTicketsTool extends ToolContext { async execute({ query }: { query: string }) { const q = query.toLowerCase(); return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(q)) }; } } ``` The result arrives as `structuredContent`, and FrontMCP also includes it as text for clients that only read text. The `readOnlyHint` annotation tells clients this tool doesn't change anything. Clients can use hints like this to decide how carefully to confirm a call with the user. ## Exposing data with resources and prompts Tools are for actions the **model** decides to take. MCP has two other kinds of capability: - A **resource** is data the client application can read and attach to a conversation, addressed by a URI. `@ResourceTemplate` covers a whole family of URIs, like `ticket://{id}`. - A **prompt** is a reusable message template the **user** picks, often from a slash menu. Initial call configuration: ```js { resource: "policy://sla" } ``` ```ts help-desk.ts import { Prompt, PromptContext, Resource, ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; @Resource({ name: "sla", uri: "policy://sla", mimeType: "text/plain", description: "How fast we reply" }) export class SlaPolicy extends ResourceContext { async execute(uri: string) { return { contents: [{ uri, mimeType: "text/plain", text: "Reply to every ticket within 4 business hours." }] }; } } @ResourceTemplate({ name: "ticket", uriTemplate: "ticket://{id}", mimeType: "application/json", description: "One ticket by id" }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, params: { id: string }) { const ticket = { id: params.id, title: "Cannot log in", status: "open" }; return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } @Prompt({ name: "triage", description: "Triage a ticket", arguments: [{ name: "id", description: "Ticket id", required: true }], }) export class TriagePrompt extends PromptContext { async execute(args: Record) { return { messages: [{ role: "user" as const, content: { type: "text" as const, text: `Read ticket://${args.id}, then suggest a priority and a next step.` } }], }; } } ``` Use the **Request** menu in the Call tab to read `ticket://{id}` with any id, or to get the `triage` prompt. ## Grouping capabilities into an app and a server So far the Playground has wrapped your exports in a server for you. In a real project you write that wiring yourself, in two layers: - An **app** (`@App`) groups related tools, resources, prompts and providers. Apps can have their own auth and settings. - The **server** (`@FrontMcp`) is the entry point. It lists your apps and holds server-wide settings such as `info` and `http`. Initial call configuration: ```js { tool: "add", arguments: { a: 40, b: 2 } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { CalcApp } from "./calc.app"; @FrontMcp({ info: { name: "Hello MCP", version: "0.1.0" }, apps: [CalcApp], }) export default class Server {} ``` ```ts calc.app.ts import { App } from "@frontmcp/sdk"; import { AddTool } from "./add.tool"; @App({ id: "calc", name: "Calculator", tools: [AddTool] }) export class CalcApp {} ``` ```ts add.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "add", description: "Adds two numbers together", inputSchema: { a: z.number(), b: z.number() }, }) export class AddTool extends ToolContext { async execute(input: { a: number; b: number }) { return input.a + input.b; } } ``` `npx frontmcp create` generates this same structure, with the tool in a `tools/` folder. Open the Wire tab: the `_meta.serverInfo` in each response now reads `Hello MCP`, from `info` in `main.ts`. ## Sharing a service with a provider Tools often need the same thing: a database client, an API wrapper, a cache. Put it in a **provider** (`@Provider`), register it on the app, and get it inside any tool with `this.get()`: Initial call configuration: ```js { tool: "count_open_tickets", arguments: {} } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Tool({ name: "count_open_tickets", description: "How many tickets are still open", inputSchema: {} }) export class CountOpenTickets extends ToolContext { async execute() { return this.get(TicketStore).open().length; } } @Tool({ name: "close_ticket", description: "Close a ticket by id", inputSchema: { id: z.string() }, annotations: { destructiveHint: true, idempotentHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return this.get(TicketStore).close(id); } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; open: boolean }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", open: true }, { id: "T-2", title: "Invoice total is wrong", open: false }, { id: "T-3", title: "Login link expired", open: true }, ]; open() { return this.tickets.filter((t) => t.open); } close(id: string) { const ticket = this.tickets.find((t) => t.id === id); if (ticket) ticket.open = false; return { id, open: false }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, CountOpenTickets } from "./tools"; import { TicketStore } from "./ticket-store"; @App({ id: "help-desk", name: "Help Desk", providers: [TicketStore], tools: [CountOpenTickets, CloseTicket] }) export class HelpDeskApp {} ``` Call `close_ticket` with `T-1`, then call `count_open_tickets` again: the count drops from 2 to 1. Both tools share one `TicketStore`, because `ProviderScope.GLOBAL` creates one instance for the whole server. `ProviderScope.CONTEXT` would create one per request instead. ## Next steps You now know the pieces you'll use most: tools, schemas, structured results, resources, prompts, apps, servers and providers. - To run a server on your own machine and connect a real client, read [Installation](https://frontmcp.dev/learn/installation). - To learn tools properly, start the [Describing Capabilities](https://frontmcp.dev/learn/describing-capabilities) chapter with [Your First Tool](https://frontmcp.dev/learn/your-first-tool). - To look up every `@Tool` option, see the [`@Tool` reference](https://frontmcp.dev/reference/sdk/tool). - To have a server tell a client that something happened, without being asked, read [Telling Clients Something Happened](https://frontmcp.dev/learn/telling-clients-something-happened). - Coming from the official MCP SDK or another framework? See [when FrontMCP is worth it](https://frontmcp.dev/compare/why-frontmcp) and [how it compares](https://frontmcp.dev/compare). --- # Tutorial: Help Desk Server > Build a complete MCP server for a support team one step at a time, with tools, clear errors, annotations, a confirmation, a resource, a prompt, an app and tests. Source: https://frontmcp.dev/learn/tutorial-help-desk [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 In this tutorial you'll build a small MCP server for a help desk with FrontMCP. An AI assistant connected to it can search a support team's tickets, read them, reply to customers and close tickets, and it asks the user before it closes anything. You don't need to know MCP yet. Each idea is introduced when you first need it, and every step runs in your browser. > **Note** > > This tutorial is for people who like to learn by doing. If you'd rather learn each idea on its own, start with [Describing Capabilities](https://frontmcp.dev/learn/describing-capabilities). The two cover the same ground, and each step here links to the lesson that explains its idea in depth. **You will learn** - How to keep data in a provider that every tool shares - How to write tools a model can call, and errors it can act on - How to tell clients which tools change data, and ask the user before an important change - How to offer data as a resource, and a workflow as a prompt - How to wire everything into an app and a server, and test it end to end ## What are you building? Here is the server you'll have at the end. Don't worry about the code yet. Only the two files that tie it together are shown, and you'll write every file yourself. Open the **Capabilities** tab to see what a client sees, then try the **Call** tab: search for `log`, read `T-1`, or call `close_ticket` and answer the question that comes back. ```ts main.ts active import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, }) export default class HelpDeskServer {} ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { DraftReply } from "./draft-reply.prompt"; import { TicketResource } from "./ticket.resource"; import { TicketStore } from "./ticket-store"; import { AddReply, CloseTicket, GetTicket, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", providers: [TicketStore], tools: [SearchTickets, GetTicket, AddReply, CloseTicket], resources: [TicketResource], prompts: [DraftReply], }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts tools.ts hidden import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, annotations: { destructiveHint: false }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } @Tool({ name: "close_ticket", description: "Close a ticket whose problem is solved. The customer is told it's resolved, so the user is asked to confirm first.", inputSchema: { id: ticketId }, annotations: { destructiveHint: true, idempotentHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") return { id, status: "closed", note: `${id} was already closed.` }; const answer = await this.elicit( `Close ${id} "${ticket.title}"? ${ticket.customer} will be told it's resolved.`, z.object({ confirmed: z.boolean().describe("Yes, close this ticket") }), ); if (answer.status !== "accept" || !answer.content?.confirmed) { return { id, status: "open", note: "The user didn't confirm, so the ticket is still open." }; } store.close(id); return { id, status: "closed" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket.resource.ts hidden import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "A support ticket with the customer's message and every reply", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new ResourceNotFoundError(uri); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts draft-reply.prompt.ts hidden import { type GetPromptResult, Prompt, PromptContext, PublicMcpError } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Prompt({ name: "draft_reply", description: "Draft a reply to a ticket, for you to review before it's sent", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "tone", description: "friendly (the default) or formal" }, ], }) export class DraftReply extends PromptContext { async execute({ id, tone = "friendly" }: Record): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND"); return { messages: [ { role: "user", content: { type: "resource", resource: { uri: `tickets://${id}`, mimeType: "application/json", text: JSON.stringify(ticket) } }, }, { role: "user", content: { type: "text", text: `Draft a ${tone} reply to ${ticket.customer} about this ticket. Show me the draft and wait. Only send it with add_reply once I approve it.`, }, }, ], }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` The server offers: - four **tools** the model can call: `search_tickets`, `get_ticket`, `add_reply` and `close_ticket`; - a **resource template**, `tickets://{id}`, so a client app can attach a ticket to the conversation; - a **prompt**, `draft_reply`, that a user picks to start a reply they'll review. By the end you'll also have tests that check all of it. Next, you'll build it from nothing, one step at a time. ## Setup for the tutorial There's nothing to install. Each step has a Playground: FrontMCP running in your browser, with an MCP client attached. Here's how to use one. **The code** is on the left, one tab per file. Press **Edit**, or double-click the code, to change it. The server restarts with your edits a moment after you stop typing, and **Reset** brings back the original. **The client** is on the right: - **Capabilities** shows what the server lists: its tools, resources and prompts. That's everything a model or a client app knows about your server. - **Call** sends a request the way a client would. Pick the request from the menu, fill in the form, and send it. Some Playgrounds send a request as soon as they start, so the result is already there. - **Tests** appears when an example has a test file. The tests run when you open the tab. - **Wire** shows every JSON-RPC message the client and the server exchanged. - **Logs** shows what FrontMCP printed. Each Playground shows the files its step changes. Files that didn't change are still part of the example and still run, but they aren't shown again. And each Playground runs its own server, starting from the same three tickets, so a reply you add in one step isn't there in the next. If you'd rather follow along in your own editor, [Installation](https://frontmcp.dev/learn/installation) sets up a project. The files at the end of step 6 are the ones you'd have. ## Step 1: A ticket store and a search tool A support agent's first question is usually "what's going on with…?", so the assistant needs to find tickets. Before the tool, the tickets need somewhere to live. Put them in a **provider**: a class FrontMCP creates once and hands to any tool that asks for it. `ProviderScope.GLOBAL` means there's a single `TicketStore` for the whole server, so when a tool changes a ticket in step 3, every other tool sees the change. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } } ``` The page searched for `log` and found two tickets. Here's what the two files do: - **`ticket-store.ts`** declares the provider with `@Provider`. The tickets are a plain array. In a real server this class would wrap your database or your help desk's API, and the tools wouldn't change. - **`tools.ts`** declares `search_tickets`. Its `name` is what the model calls, its `description` says what comes back, and its `inputSchema`, written with Zod, becomes the JSON Schema the model reads. `.min(2)` and `.describe()` are part of that schema. - Inside `execute()`, `this.get(TicketStore)` gets the store. - The tool returns an object, `{ tickets: [...] }`, which arrives as `structuredContent`. Each match has only its id, title and status: enough for the model to choose one, and short enough to read quickly. The whole ticket comes from the next tool. You didn't write a server. The Playground found the exported tool and provider and wrapped them in one for you. You'll write that part yourself in step 6. Try searching for `invoice`, and then for `a`. The second call never reaches `execute()`: FrontMCP checks the arguments against the schema first, and `a` is shorter than 2 characters. [Your First Tool](https://frontmcp.dev/learn/your-first-tool) explains what the model sees and what FrontMCP checks. ## Step 2: Read a ticket, and fail clearly Search gives the model ids. Next it needs to read one ticket in full. Add a `get()` method to the store and a `get_ticket` tool. Here's a first version: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-9" } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"), }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return this.get(TicketStore).get(id); } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } } ``` Called with `T-1`, this works. But the page asked for `T-9`, which doesn't exist. `find()` returned `undefined`, and FrontMCP answered with "Flow exited without producing output". That message is about FrontMCP's internals, not about tickets. A model reading it can't tell whether the ticket is missing, the server is broken, or it should try the same call again. When a call can't succeed, fail with a message the model can act on: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-9" } } ``` ```ts tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } } ``` - `this.fail()` ends the call and sends the error as a result with `isError: true`. - `PublicMcpError` marks the message as safe to show, so it reaches the model word for word. It says what's wrong and what to do next, so the model can search instead of guessing. - Its second argument, `"TICKET_NOT_FOUND"`, is a code for programs rather than models. It arrives as `_meta.code`, and the Call tab shows it next to the error. You'll check it in a test in step 6. - `ticketId` and `notFound()` are shared because the next two tools need the same id rule and the same error. There are now two layers of checking. The `.regex()` in the schema turns away anything that isn't shaped like `T-1` before your code runs, and `execute()` only has to handle ids that look right but don't exist. Call `get_ticket` with `T-2` to see a whole ticket, reply included. [Your First Tool](https://frontmcp.dev/learn/your-first-tool#returning-results-and-errors) covers results and errors in more detail. ## Step 3: Add a reply, and say which tools change data Nothing has changed any data so far. `add_reply` will: it adds a reply that the customer will read. The store gets an `addReply()` method, and the tool checks the ticket before writing to it: Initial call configuration: ```js { tool: "add_reply", arguments: { id: "T-1", text: "Could you try the reset link we just sent? It works for an hour." } } ``` ```ts tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, annotations: { destructiveHint: false }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } } ``` - The tool returns the updated ticket, so the model can see that its reply landed. - A reply to a closed ticket fails with its own code, `TICKET_CLOSED`, and a message that says why. Try it with `T-2`. - Now call `get_ticket` with `T-1`. The reply is there, because both tools use the same `TicketStore`. Now open the Capabilities tab. Each tool has **annotations**, hints that tell clients how it behaves: | Tool | Annotation | What it tells clients | | --- | --- | --- | | `search_tickets`, `get_ticket` | `readOnlyHint: true` | It doesn't change anything. The card shows a **read-only** chip. | | `add_reply` | `destructiveHint: false` | It changes data, but only by adding to it. | Without annotations, a client knows nothing about how a tool behaves, and MCP's defaults assume the worst: that any tool may change or delete things. Clients can use hints to decide how carefully to confirm a call with the user. They're only hints, though. FrontMCP sends them in `tools/list` but doesn't enforce them, and a client is free to ignore them. The next step shows how to make sure the user is asked. ## Step 4: Close a ticket once the user confirms Closing a ticket tells the customer their problem is solved. If the model closes the wrong one, a customer who still needs help is told they're done. That's a decision for the person using the assistant, not the model, so `close_ticket` asks them with `this.elicit()`: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, annotations: { destructiveHint: false }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } @Tool({ name: "close_ticket", description: "Close a ticket whose problem is solved. The customer is told it's resolved, so the user is asked to confirm first.", inputSchema: { id: ticketId }, annotations: { destructiveHint: true, idempotentHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") return { id, status: "closed", note: `${id} was already closed.` }; const answer = await this.elicit( `Close ${id} "${ticket.title}"? ${ticket.customer} will be told it's resolved.`, z.object({ confirmed: z.boolean().describe("Yes, close this ticket") }), ); if (answer.status !== "accept" || !answer.content?.confirmed) { return { id, status: "open", note: "The user didn't confirm, so the ticket is still open." }; } store.close(id); return { id, status: "closed" }; } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` The page called `close_ticket` for `T-1`, and instead of a result, the Call tab shows a form: the question the tool is asking the user. Tick **confirmed** and press **Accept**, and the ticket closes. Then call it again with `T-3` and press **Decline**: the ticket stays open, and the result says so. `this.elicit(message, schema)` sends a question with a Zod schema for the answer, and the client turns the schema into a form. It returns an object with a `status`, which is `"accept"`, `"decline"` or `"cancel"`, and, when the user accepted, the answers in `content`. `close_ticket` closes the ticket only if the user accepted and ticked the box. Any other answer is a normal result, not an error: the user said no, so the model should tell them the ticket is still open rather than try again. The checks come before the question. A missing ticket fails, and a closed one returns at once, so the user is never asked about something that can't happen. Try `T-2`. The annotations say what the tool does, too. `destructiveHint: true` because closing overwrites the ticket's status rather than adding to it, and `idempotentHint: true` because closing a ticket twice changes nothing the second time. How does a tool wait for the user? It doesn't. Under MCP 2026-07-28, the first `tools/call` comes back at once with `resultType: "input_required"`, the question, and a `requestState` token. The client shows the form, then sends the same `tools/call` again with the answer in `inputResponses`. FrontMCP runs `execute()` again from the top, and this time `this.elicit()` returns the answer. Open the Wire tab to see both requests. Because `execute()` runs twice, do your reads before `this.elicit()` and your writes after it. [Asking the User](https://frontmcp.dev/learn/asking-the-user) covers elicitation in depth. > **Note** > > The Playground turns elicitation on for you when your code calls `this.elicit()`. On your own server you turn it on in `@FrontMcp`, which is part of step 6. ## Step 5: Attach tickets as resources, and add a prompt Tools are for the model: it decides when to call them. Sometimes, though, the user already knows which ticket they mean and wants their client to attach it to the conversation, the way you'd attach a file. That's a **resource**: data a client app reads by URI. A **resource template** covers a whole family of URIs, here one per ticket: Initial call configuration: ```js { resource: "tickets://T-1" } ``` ```ts ticket.resource.ts active import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "A support ticket with the customer's message and every reply", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new ResourceNotFoundError(uri); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts tools.ts hidden import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, annotations: { destructiveHint: false }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } @Tool({ name: "close_ticket", description: "Close a ticket whose problem is solved. The customer is told it's resolved, so the user is asked to confirm first.", inputSchema: { id: ticketId }, annotations: { destructiveHint: true, idempotentHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") return { id, status: "closed", note: `${id} was already closed.` }; const answer = await this.elicit( `Close ${id} "${ticket.title}"? ${ticket.customer} will be told it's resolved.`, z.object({ confirmed: z.boolean().describe("Yes, close this ticket") }), ); if (answer.status !== "accept" || !answer.content?.confirmed) { return { id, status: "open", note: "The user didn't confirm, so the ticket is still open." }; } store.close(id); return { id, status: "closed" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` - `uriTemplate: "tickets://{id}"` matches any `tickets://` URI, and FrontMCP passes the `id` part to `execute()`. - `execute()` returns `contents`: the URI that was read, its MIME type, and the text. The text is the same JSON that `get_ticket` returns. - Reading a resource has no `isError` result the way a tool call does. For a ticket that doesn't exist, `execute()` throws `ResourceNotFoundError`, and the client gets a JSON-RPC error instead of a result. In the Call tab, pick `resources/read · tickets://{id}` and read `T-9` to see it. Offering a ticket both as a tool and as a resource isn't duplication. `get_ticket` is for when the model decides it needs a ticket, and `tickets://{id}` is for when the user or the app decides. [Exposing Data with Resources](https://frontmcp.dev/learn/exposing-data-with-resources) covers resources in depth. The last piece is for the user too. A good reply draft needs the same instructions every time: read the ticket, match the tone, and don't send anything until the user approves. A **prompt** packages those instructions so the user can pick them, usually from a slash menu in their client, and fill in the blanks: Initial call configuration: ```js { prompt: "draft_reply", arguments: { id: "T-3" } } ``` ```ts draft-reply.prompt.ts active import { type GetPromptResult, Prompt, PromptContext, PublicMcpError } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Prompt({ name: "draft_reply", description: "Draft a reply to a ticket, for you to review before it's sent", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "tone", description: "friendly (the default) or formal" }, ], }) export class DraftReply extends PromptContext { async execute({ id, tone = "friendly" }: Record): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND"); return { messages: [ { role: "user", content: { type: "resource", resource: { uri: `tickets://${id}`, mimeType: "application/json", text: JSON.stringify(ticket) } }, }, { role: "user", content: { type: "text", text: `Draft a ${tone} reply to ${ticket.customer} about this ticket. Show me the draft and wait. Only send it with add_reply once I approve it.`, }, }, ], }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket.resource.ts hidden import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "A support ticket with the customer's message and every reply", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new ResourceNotFoundError(uri); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts tools.ts hidden import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, annotations: { destructiveHint: false }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } @Tool({ name: "close_ticket", description: "Close a ticket whose problem is solved. The customer is told it's resolved, so the user is asked to confirm first.", inputSchema: { id: ticketId }, annotations: { destructiveHint: true, idempotentHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") return { id, status: "closed", note: `${id} was already closed.` }; const answer = await this.elicit( `Close ${id} "${ticket.title}"? ${ticket.customer} will be told it's resolved.`, z.object({ confirmed: z.boolean().describe("Yes, close this ticket") }), ); if (answer.status !== "accept" || !answer.content?.confirmed) { return { id, status: "open", note: "The user didn't confirm, so the ticket is still open." }; } store.close(id); return { id, status: "closed" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` - `arguments` are the blanks the user fills in. `id` is required. `tone` is optional, and `execute()` uses `"friendly"` when it's left out. Prompt arguments are always strings. - `execute()` returns the messages that start the conversation. The first attaches the ticket, just as reading `tickets://T-3` would. The second says what to do with it. - The instructions name `add_reply`. A prompt is a good place to say how your tools fit together. - The return type, `GetPromptResult`, lets TypeScript check the shape of each message. Try `tone` set to `formal`, or an id that doesn't exist. [Reusable Prompts](https://frontmcp.dev/learn/reusable-prompts) covers prompts in depth. ## Step 6: Put it in an app and a server, and test it Until now, the Playground has found your exports and wrapped them in a server. A real project does that wiring in two files: - **`help-desk.app.ts`** declares an `@App`: the provider, tools, resource and prompt that belong together. - **`main.ts`** declares the `@FrontMcp` server: its name and version, and its apps. `import "reflect-metadata"` comes first, because FrontMCP's decorators rely on it. Here's a first try. It lists everything, and the page calls `close_ticket`: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts main.ts active import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class HelpDeskServer {} ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { DraftReply } from "./draft-reply.prompt"; import { TicketResource } from "./ticket.resource"; import { TicketStore } from "./ticket-store"; import { AddReply, CloseTicket, GetTicket, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", providers: [TicketStore], tools: [SearchTickets, GetTicket, AddReply, CloseTicket], resources: [TicketResource], prompts: [DraftReply], }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts tools.ts hidden import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, annotations: { destructiveHint: false }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } @Tool({ name: "close_ticket", description: "Close a ticket whose problem is solved. The customer is told it's resolved, so the user is asked to confirm first.", inputSchema: { id: ticketId }, annotations: { destructiveHint: true, idempotentHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") return { id, status: "closed", note: `${id} was already closed.` }; const answer = await this.elicit( `Close ${id} "${ticket.title}"? ${ticket.customer} will be told it's resolved.`, z.object({ confirmed: z.boolean().describe("Yes, close this ticket") }), ); if (answer.status !== "accept" || !answer.content?.confirmed) { return { id, status: "open", note: "The user didn't confirm, so the ticket is still open." }; } store.close(id); return { id, status: "closed" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket.resource.ts hidden import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "A support ticket with the customer's message and every reply", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new ResourceNotFoundError(uri); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts draft-reply.prompt.ts hidden import { type GetPromptResult, Prompt, PromptContext, PublicMcpError } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Prompt({ name: "draft_reply", description: "Draft a reply to a ticket, for you to review before it's sent", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "tone", description: "friendly (the default) or formal" }, ], }) export class DraftReply extends PromptContext { async execute({ id, tone = "friendly" }: Record): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND"); return { messages: [ { role: "user", content: { type: "resource", resource: { uri: `tickets://${id}`, mimeType: "application/json", text: JSON.stringify(ticket) } }, }, { role: "user", content: { type: "text", text: `Draft a ${tone} reply to ${ticket.customer} about this ticket. Show me the draft and wait. Only send it with add_reply once I approve it.`, }, }, ], }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` The call fails: "Elicitation is disabled in server configuration". Asking the user is off unless the server turns it on, and until now the Playground had been doing that for you. Add `elicitation: { enabled: true }` to `@FrontMcp`, and add a test file: ```ts main.ts import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, }) export default class HelpDeskServer {} ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { DraftReply } from "./draft-reply.prompt"; import { TicketResource } from "./ticket.resource"; import { TicketStore } from "./ticket-store"; import { AddReply, CloseTicket, GetTicket, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", providers: [TicketStore], tools: [SearchTickets, GetTicket, AddReply, CloseTicket], resources: [TicketResource], prompts: [DraftReply], }) export class HelpDeskApp {} ``` ```ts tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns each match's id, title and status.", inputSchema: { query: z.string().min(2).describe('Words to look for in ticket titles, like "login"'), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, annotations: { destructiveHint: false }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } @Tool({ name: "close_ticket", description: "Close a ticket whose problem is solved. The customer is told it's resolved, so the user is asked to confirm first.", inputSchema: { id: ticketId }, annotations: { destructiveHint: true, idempotentHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") return { id, status: "closed", note: `${id} was already closed.` }; const answer = await this.elicit( `Close ${id} "${ticket.title}"? ${ticket.customer} will be told it's resolved.`, z.object({ confirmed: z.boolean().describe("Yes, close this ticket") }), ); if (answer.status !== "accept" || !answer.content?.confirmed) { return { id, status: "open", note: "The user didn't confirm, so the ticket is still open." }; } store.close(id); return { id, status: "closed" }; } } ``` ```ts ticket.resource.ts import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "A support ticket with the customer's message and every reply", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new ResourceNotFoundError(uri); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } ``` ```ts draft-reply.prompt.ts import { type GetPromptResult, Prompt, PromptContext, PublicMcpError } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Prompt({ name: "draft_reply", description: "Draft a reply to a ticket, for you to review before it's sent", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "tone", description: "friendly (the default) or formal" }, ], }) export class DraftReply extends PromptContext { async execute({ id, tone = "friendly" }: Record): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND"); return { messages: [ { role: "user", content: { type: "resource", resource: { uri: `tickets://${id}`, mimeType: "application/json", text: JSON.stringify(ticket) } }, }, { role: "user", content: { type: "text", text: `Draft a ${tone} reply to ${ticket.customer} about this ticket. Show me the draft and wait. Only send it with add_reply once I approve it.`, }, }, ], }; } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string) { const q = query.toLowerCase(); return this.tickets .filter((t) => t.title.toLowerCase().includes(q)) .map(({ id, title, status }) => ({ id, title, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` ```ts helpdesk.test.ts active import { test, expect } from "@frontmcp/testing"; test("search_tickets finds both login tickets", async ({ mcp }) => { const result = await mcp.tools.call("search_tickets", { query: "log" }); expect(result).toBeSuccessful(); expect(result.json().tickets.map((t: { id: string }) => t.id)).toEqual(["T-1", "T-3"]); }); test("get_ticket explains a missing ticket", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-9" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("TICKET_NOT_FOUND"); expect(result).toHaveTextContent("search_tickets"); }); test("a reply shows up on the ticket", async ({ mcp }) => { await mcp.tools.call("add_reply", { id: "T-3", text: "Here's a fresh link. It works for an hour." }); const ticket = (await mcp.tools.call("get_ticket", { id: "T-3" })).json(); expect(ticket.replies).toContain("Here's a fresh link. It works for an hour."); }); test("close_ticket closes the ticket when the user confirms", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirmed: true } })); const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result.json()).toEqual({ id: "T-1", status: "closed" }); }); test("close_ticket leaves the ticket open when the user declines", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "decline" })); const result = await mcp.tools.call("close_ticket", { id: "T-3" }); expect(result.json()).toMatchObject({ id: "T-3", status: "open" }); }); test("tickets://T-2 is the ticket as JSON", async ({ mcp }) => { const content = await mcp.resources.read("tickets://T-2"); expect(content).toHaveMimeType("application/json"); expect(content.json().customer).toBe("Grace"); }); test("draft_reply attaches the ticket and asks for a draft", async ({ mcp }) => { const prompt = await mcp.prompts.get("draft_reply", { id: "T-3" }); expect(prompt).toHaveMessages(2); expect(prompt.messages[0].content.resource.uri).toBe("tickets://T-3"); }); ``` This is the finished server from the top of the page, with every file shown. In the Call tab, `close_ticket` asks the user again. In the Wire tab, each response's `_meta.serverInfo` now says `Help Desk`, from `info` in `main.ts`. Open the **Tests** tab. `helpdesk.test.ts` is written with `@frontmcp/testing`. Each test gets `mcp`, a client connected to this server, calls the server through it, and checks the results with `expect`: - `toBeSuccessful()` and `toBeError()` check whether a tool call worked, and `result.json()` reads the result's data. - `result.raw._meta?.code` is where the `TICKET_NOT_FOUND` code from step 2 arrives. - `mcp.onElicitation()` plays the user: whenever a tool asks a question, the test answers it. One test accepts and one declines. - `mcp.resources.read()` and `mcp.prompts.get()` test the resource and the prompt the same way. All the tests in a file talk to the same running server, so a ticket that one test closes stays closed for the next. That's why the test that closes a ticket uses `T-1`, and the one that declines uses `T-3`. To see a test fail, change `"TICKET_NOT_FOUND"` in `tools.ts` to something else and open the Tests tab again. In a project, you run the same tests with `frontmcp test`, once the file says where your server is. [Testing Your Server](https://frontmcp.dev/learn/testing-your-server) shows the setup. ## Wrapping up Congratulations! You've built an MCP server that: - keeps its data in a provider that every capability shares; - gives the model four tools with clear names, schemas, results and errors; - tells clients which tools change data, and asks the user before a ticket is closed; - lets a client attach tickets as resources, and lets a user start a reply with a prompt; - wires everything into an app and a server, with tests that check each part. Each idea has its own lesson: - Tools, schemas, results and errors: [Your First Tool](https://frontmcp.dev/learn/your-first-tool), [Schemas Are Contracts](https://frontmcp.dev/learn/schemas-are-contracts) and [Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results) - Resources: [Exposing Data with Resources](https://frontmcp.dev/learn/exposing-data-with-resources) - Prompts: [Reusable Prompts](https://frontmcp.dev/learn/reusable-prompts) - Apps, servers and providers: [Grouping Capabilities into Apps](https://frontmcp.dev/learn/grouping-capabilities-into-apps) - Asking the user: [Asking the User](https://frontmcp.dev/learn/asking-the-user) - Tests: [Testing Your Server](https://frontmcp.dev/learn/testing-your-server) - Deciding what to build in the first place: [Thinking in MCP](https://frontmcp.dev/learn/thinking-in-mcp) If you'd like more practice, here are some ideas to try in the last Playground, roughly from easiest to hardest. 1. Let the model narrow a search to open or closed tickets, with an optional `status` argument on `search_tickets`. Look at how the new argument shows up in the Capabilities tab. 2. A user asking about "Ada's login problem" gets nothing if the model searches for `Ada`. Make `search_tickets` match the customer's name as well as the title, and update its description to say so. 3. Add a `reopen_ticket` tool. Decide which annotations it needs, and whether reopening needs the user to confirm. Then add a test for it. 4. Let `close_ticket` ask for a one-line resolution in the same form, and save it as the ticket's last reply. The elicitation schema is a Zod object, so it can hold more than one field. --- # Thinking in MCP > A design process for turning what people need from an AI assistant into tools, resources and prompts, worked through for a help desk. Source: https://frontmcp.dev/learn/thinking-in-mcp [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 When you connect a product to AI, the obvious first move is to take your API and turn each endpoint into a tool. That works, but models often use the result badly, because they don't think in endpoints. They think in the requests people make. This page designs an MCP server the other way round, starting from what people will ask the assistant. The example is a help desk, and you'll end with a working FrontMCP server. **You will learn** - How to start a design from the requests people will make - How to tell whether a job is a tool, a resource or a prompt - How to shape names, inputs and results for a model - How to decide which actions need the user's confirmation - How to group capabilities into apps ## Start with what people will ask Say you make help desk software. It has a web app, a database of tickets, and an API with dozens of endpoints. Support teams want their AI assistant to work with it. Don't start from the API. Start from the requests. Ask a few support agents what they'd want to say to the assistant, or read your team's chat for things people already ask each other. You might collect these: 1. "What's going on with Ada's login problem?" 2. "Are there any open tickets about invoices?" 3. "Tell Linus we've sent him a new sign-in link." 4. "T-1 is fixed. Close it." 5. With a ticket attached to the conversation: "Why did this customer get a refund?" 6. Picked from the client's prompt menu: "Draft a reply to T-3." Then look at the data the requests are about. Here's one ticket: ```json ticket.json { "id": "T-1", "title": "Cannot log in", "customer": "Ada", "status": "open", "message": "I reset my password twice and the login page still says it's wrong.", "replies": [] } ``` These requests are your mockup. Everything that follows is about making each of them easy for a model to carry out. ## Step 1: Break the requests into jobs For each request, write down what the assistant has to do, and what it needs to know to do it: | Request | Jobs | What it needs | | --- | --- | --- | | "What's going on with Ada's login problem?" | find the ticket, read it | a customer's name, then the whole ticket | | "Are there any open tickets about invoices?" | find tickets | a word from the title, a status | | "Tell Linus we've sent him a new sign-in link." | find the ticket, reply | a customer's name, then the id and the reply | | "T-1 is fixed. Close it." | close a ticket | the id | | (ticket attached) "Why did this customer get a refund?" | read a ticket | the whole ticket | | (from the menu) "Draft a reply to T-3." | read a ticket, draft a reply | the whole ticket | Then merge the duplicates. Six requests come down to five jobs: **find tickets**, **read a ticket**, **reply**, **close a ticket** and **draft a reply**. All five work on the same data: tickets. Two things stand out: - **Most requests start by finding a ticket, and people don't know ids.** They say "Ada's login problem" or "Linus". So finding has to work with what people say: words from the title, and the customer's name, with an optional status for request 2. - **The list is short, and it isn't your API.** Your product may have endpoints for tags, assignments, exports and reports. If nobody asks the assistant for them, leave them out for now. Every capability you add is one more thing a model has to read and choose between. ## Step 2: Decide who starts each job MCP has three kinds of capability. What separates them is who decides to use each one: - A **tool** is chosen by the **model**. It reads the tool's name and description, and calls it when the conversation needs it. - A **resource** is read by the **client app**, usually because the user attached it to the conversation, the way you attach a file. It's data with a URI. - A **prompt** is picked by the **user**, usually from a slash menu, to start a workflow with arguments they fill in. So for each job, ask who decides that it should happen: | Job | Who decides | Kind | | --- | --- | --- | | Find tickets | The model, while it answers a question | Tool | | Read a ticket | The model, when it needs the details. The user, when they attach one. | Tool and resource | | Reply | The model, when the user asks for it | Tool | | Close a ticket | The model, when the user asks for it | Tool | | Draft a reply | The user, who wants the same steps every time | Prompt | Reading a ticket is both, which is common for the main thing your product holds: the model needs a way to fetch it, and the user needs a way to hand it over. The two can share the code that loads a ticket. Here's a first sketch with one capability of each kind, all reading the same tickets from a provider. The page read `tickets://T-2`, the ticket attached in request 5. Open the Capabilities tab to see the sketch the way a client does, and use the Call tab's **Request** menu to try the tool and the prompt. Initial call configuration: ```js { resource: "tickets://T-2" } ``` ```ts help-desk.ts active import { type GetPromptResult, Prompt, PromptContext, PublicMcpError, ResourceContext, ResourceNotFoundError, ResourceTemplate, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; // The model decides it needs a ticket: a tool. @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } // The user attaches a ticket: a resource. @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "A support ticket with the customer's message and every reply", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new ResourceNotFoundError(uri); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } // The user picks a workflow: a prompt. @Prompt({ name: "draft_reply", description: "Draft a reply to a ticket, for you to review before it's sent", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class DraftReply extends PromptContext { async execute({ id }: Record): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return { messages: [ { role: "user", content: { type: "resource", resource: { uri: `tickets://${id}`, mimeType: "application/json", text: JSON.stringify(ticket) } }, }, { role: "user", content: { type: "text", text: `Draft a reply to ${ticket.customer} about this ticket. Show me the draft and wait for my approval.` }, }, ], }; } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string, status?: "open" | "closed") { const q = query.toLowerCase(); return this.tickets .filter((t) => [t.title, t.customer].some((s) => s.toLowerCase().includes(q))) .filter((t) => !status || t.status === status) .map(({ id, title, customer, status }) => ({ id, title, customer, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` The three capabilities read the same `TicketStore`, so they can never disagree about a ticket. The store is a provider with `ProviderScope.GLOBAL`: FrontMCP creates one for the whole server and hands it to anything that asks with `this.get()`. Every Playground on this page uses this same store file, so from here on it's hidden. It still runs. ## Step 3: Design names, inputs and results for the model With the jobs and their kinds decided, design each tool for its reader: a model that sees only names, descriptions and schemas. It's tempting to skip this and mirror the API with a single tool that takes an `action` and every field any action might need. Here's that design. The page asked it to reply to `T-3`: Initial call configuration: ```js { tool: "tickets", arguments: { action: "reply", id: "T-3" } } ``` ```ts tickets.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; type Input = { action: "search" | "get" | "reply" | "close"; id?: string; query?: string; text?: string }; @Tool({ name: "tickets", description: "Manage tickets.", inputSchema: { action: z.enum(["search", "get", "reply", "close"]), id: z.string().optional(), query: z.string().optional(), text: z.string().optional(), }, }) export class Tickets extends ToolContext { async execute({ action, id, query, text }: Input) { const store = this.get(TicketStore); if (action === "search") return { tickets: store.search(query ?? "") }; if (!id) this.fail(new PublicMcpError(`"${action}" needs an id.`)); if (action === "get") return store.get(id); if (action === "reply") { if (!text) this.fail(new PublicMcpError(`"reply" needs text.`)); return store.addReply(id, text); } return store.close(id); } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string, status?: "open" | "closed") { const q = query.toLowerCase(); return this.tickets .filter((t) => [t.title, t.customer].some((s) => s.toLowerCase().includes(q))) .filter((t) => !status || t.status === status) .map(({ id, title, customer, status }) => ({ id, title, customer, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` The call failed because it had no `text`, and the model had no way to know it needed one. Open the Capabilities tab and read the card as a model would: 1. **Every field but `action` is optional, and nothing says which fields go with which action.** The schema can't express "`reply` needs `id` and `text`", so the model finds out by failing, as this call just did. 2. **One vague name and description cover four jobs.** When a user says "close it", the model has to guess that `tickets` is the tool, then guess the arguments. 3. **It can't be annotated honestly.** The same tool reads and closes tickets, so it can't be marked read-only, and a careful client has to treat every search like a change. Give each job its own tool instead, and design each one for the moment the model will use it: - **Name the tool after its job**: a verb and a noun in `snake_case`, like `search_tickets`. The name is the first thing a model matches against the user's words. - **Ask only for what the model can know at that point**: the user's words, or an id from an earlier result. `search_tickets` takes words and matches them against titles and customer names, because step 1 showed that's how people ask. `get_ticket` takes the id that search returned. Make inputs required unless there's a sensible default, like the optional `status`, and put every rule in the schema. - **Return what the next step needs.** Search returns each match's id, title, customer and status: enough to pick one and to pass its id on. The whole ticket comes from `get_ticket`. - **Make errors say what to do next.** "There's no ticket T-9. Use search_tickets to find the right id." gives the model a way forward. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "Ada" } } ``` ```ts tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by a word from the title or the customer's name. Returns each match's id, title, customer and status.", inputSchema: { query: z.string().min(2).describe('A word from the title, or a customer name, like "invoice" or "Ada"'), status: z.enum(["open", "closed"]).optional().describe("Only tickets with this status. Leave out for both."), }, }) export class SearchTickets extends ToolContext { async execute({ query, status }: { query: string; status?: "open" | "closed" }) { return { tickets: this.get(TicketStore).search(query, status) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } @Tool({ name: "close_ticket", description: "Close a ticket whose problem is solved. The customer is told it's resolved.", inputSchema: { id: ticketId }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); if (!store.get(id)) this.fail(notFound(id)); store.close(id); return { id, status: "closed" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string, status?: "open" | "closed") { const q = query.toLowerCase(); return this.tickets .filter((t) => [t.title, t.customer].some((s) => s.toLowerCase().includes(q))) .filter((t) => !status || t.status === status) .map(({ id, title, customer, status }) => ({ id, title, customer, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` The page searched for `Ada`, the way request 1 would, and found `T-1`. Now walk the other requests through the Call tab. Request 2 is `search_tickets` with `invoice` and status `open`: there are none, because the invoice ticket is closed. Request 3 is a search for `Linus`, then `add_reply` on the id it returns. Each card in the Capabilities tab now says what its tool does and asks only for what it needs. For more on each of these, see [Your First Tool](https://frontmcp.dev/learn/your-first-tool), [Schemas Are Contracts](https://frontmcp.dev/learn/schemas-are-contracts), [Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results) and [Writing Descriptions Agents Understand](https://frontmcp.dev/learn/writing-descriptions-agents-understand). ## Step 4: Decide what needs the user's confirmation Request 4 now works a little too well. Anything that makes the model call `close_ticket`, whether it misread the user or mixed up two tickets, closes a ticket on the spot. Go through the tools and ask: what happens if the model calls this when the user didn't mean it? | Tool | If it's called by mistake | So | | --- | --- | --- | | `search_tickets`, `get_ticket` | Nothing changes. | `readOnlyHint: true`. No confirmation. | | `add_reply` | A customer gets a reply nobody meant to send. It adds to the ticket and doesn't overwrite anything, and a follow-up can correct it. | `destructiveHint: false`. No confirmation. | | `close_ticket` | A customer who still needs help is told they're done. | `destructiveHint: true`, and ask the user first. | You have two ways to act on the answers, and they do different jobs: - **Annotations** describe a tool's effects to clients, which may use them to decide how carefully to confirm a call. Give every tool annotations. They're hints: FrontMCP sends them but doesn't enforce them. - **`this.elicit()`** asks the user a question from inside your tool, and your code acts on the answer. The check lives in your server, so it holds whatever the client does with hints. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by a word from the title or the customer's name. Returns each match's id, title, customer and status.", inputSchema: { query: z.string().min(2).describe('A word from the title, or a customer name, like "invoice" or "Ada"'), status: z.enum(["open", "closed"]).optional().describe("Only tickets with this status. Leave out for both."), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query, status }: { query: string; status?: "open" | "closed" }) { return { tickets: this.get(TicketStore).search(query, status) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, annotations: { destructiveHint: false }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } @Tool({ name: "close_ticket", description: "Close a ticket whose problem is solved. The customer is told it's resolved, so the user is asked to confirm first.", inputSchema: { id: ticketId }, annotations: { destructiveHint: true, idempotentHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") return { id, status: "closed", note: `${id} was already closed.` }; const answer = await this.elicit( `Close ${id} "${ticket.title}"? ${ticket.customer} will be told it's resolved.`, z.object({ confirmed: z.boolean().describe("Yes, close this ticket") }), ); if (answer.status !== "accept" || !answer.content?.confirmed) { return { id, status: "open", note: "The user didn't confirm, so the ticket is still open." }; } store.close(id); return { id, status: "closed" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string, status?: "open" | "closed") { const q = query.toLowerCase(); return this.tickets .filter((t) => [t.title, t.customer].some((s) => s.toLowerCase().includes(q))) .filter((t) => !status || t.status === status) .map(({ id, title, customer, status }) => ({ id, title, customer, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` The page called `close_ticket` again, and this time the user gets a form instead of a closed ticket. Tick **confirmed** and press **Accept** to close it, or **Decline** to keep it open. The tool checks the ticket before it asks, so nobody is asked to close a ticket that doesn't exist or is already closed, and it writes only after the answer comes back, because `execute()` runs again from the top when the answer arrives. The Capabilities tab now shows the annotations as chips: **read-only** on the two reads, **destructive** and **idempotent** on `close_ticket`. Keep confirmations for the actions that need them. A user asked to confirm every reply soon starts pressing Accept without reading, and then the one question that matters gets the same treatment. Replies are covered another way: the `draft_reply` prompt from step 2 tells the model to wait for the user's approval before it sends anything. [Asking the User](https://frontmcp.dev/learn/asking-the-user) covers elicitation in depth. ## Step 5: Group capabilities into apps An `@App` groups capabilities that belong together: they work on the same data, share the same providers, and would share settings such as authentication. Everything so far is about tickets, so it's one app, and the app owns the `TicketStore`. Then a new request shows up: "Is there a help article about sign-in links I can send Linus?" That's a new job with different data, articles, probably looked after by another team. It becomes a second app, and the `@FrontMcp` server lists both. The resource and the prompt from step 2 get files of their own, and `tools.ts` is hidden because it hasn't changed since step 4: ```ts main.ts active import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; import { KnowledgeBaseApp } from "./knowledge-base.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [HelpDeskApp, KnowledgeBaseApp], elicitation: { enabled: true }, }) export default class HelpDeskServer {} ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { DraftReply } from "./draft-reply.prompt"; import { TicketResource } from "./ticket.resource"; import { TicketStore } from "./ticket-store"; import { AddReply, CloseTicket, GetTicket, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", providers: [TicketStore], tools: [SearchTickets, GetTicket, AddReply, CloseTicket], resources: [TicketResource], prompts: [DraftReply], }) export class HelpDeskApp {} ``` ```ts knowledge-base.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; const articles = [ { id: "KB-1", title: "Resetting your password", url: "https://help.example.com/kb/1" }, { id: "KB-2", title: "Sign-in links and when they expire", url: "https://help.example.com/kb/2" }, { id: "KB-3", title: "Reading your invoice", url: "https://help.example.com/kb/3" }, ]; @Tool({ name: "search_articles", description: "Search help center articles by words in their title. Returns links an agent can send to a customer.", inputSchema: { query: z.string().min(2).describe('Words to look for in article titles, like "password"') }, annotations: { readOnlyHint: true }, }) export class SearchArticles extends ToolContext { async execute({ query }: { query: string }) { const q = query.toLowerCase(); return { articles: articles.filter((a) => a.title.toLowerCase().includes(q)) }; } } @App({ id: "knowledge-base", name: "Knowledge Base", tools: [SearchArticles] }) export class KnowledgeBaseApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts tools.ts hidden import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); function notFound(id: string) { return new PublicMcpError(`There's no ticket ${id}. Use search_tickets to find the right id.`, "TICKET_NOT_FOUND"); } @Tool({ name: "search_tickets", description: "Search support tickets by a word from the title or the customer's name. Returns each match's id, title, customer and status.", inputSchema: { query: z.string().min(2).describe('A word from the title, or a customer name, like "invoice" or "Ada"'), status: z.enum(["open", "closed"]).optional().describe("Only tickets with this status. Leave out for both."), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query, status }: { query: string; status?: "open" | "closed" }) { return { tickets: this.get(TicketStore).search(query, status) }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id: the customer, the status, their message and every reply so far.", inputSchema: { id: ticketId }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(notFound(id)); return ticket; } } @Tool({ name: "add_reply", description: "Add a reply to an open ticket. The customer reads it, so write it to them. Returns the updated ticket.", inputSchema: { id: ticketId, text: z.string().min(1).max(2000).describe("The reply, as the customer will read it"), }, annotations: { destructiveHint: false }, }) export class AddReply extends ToolContext { async execute({ id, text }: { id: string; text: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") { this.fail(new PublicMcpError(`${id} is closed. Replies can only go on open tickets.`, "TICKET_CLOSED")); } return store.addReply(id, text); } } @Tool({ name: "close_ticket", description: "Close a ticket whose problem is solved. The customer is told it's resolved, so the user is asked to confirm first.", inputSchema: { id: ticketId }, annotations: { destructiveHint: true, idempotentHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); const ticket = store.get(id); if (!ticket) this.fail(notFound(id)); if (ticket.status === "closed") return { id, status: "closed", note: `${id} was already closed.` }; const answer = await this.elicit( `Close ${id} "${ticket.title}"? ${ticket.customer} will be told it's resolved.`, z.object({ confirmed: z.boolean().describe("Yes, close this ticket") }), ); if (answer.status !== "accept" || !answer.content?.confirmed) { return { id, status: "open", note: "The user didn't confirm, so the ticket is still open." }; } store.close(id); return { id, status: "closed" }; } } ``` ```ts ticket.resource.ts import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "A support ticket with the customer's message and every reply", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new ResourceNotFoundError(uri); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } ``` ```ts draft-reply.prompt.ts import { type GetPromptResult, Prompt, PromptContext, PublicMcpError } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Prompt({ name: "draft_reply", description: "Draft a reply to a ticket, for you to review before it's sent", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class DraftReply extends PromptContext { async execute({ id }: Record): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return { messages: [ { role: "user", content: { type: "resource", resource: { uri: `tickets://${id}`, mimeType: "application/json", text: JSON.stringify(ticket) } }, }, { role: "user", content: { type: "text", text: `Draft a reply to ${ticket.customer} about this ticket. Show me the draft and wait. Only send it with add_reply once I approve it.`, }, }, ], }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; export type Ticket = { id: string; title: string; customer: string; status: "open" | "closed"; message: string; replies: string[]; }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", customer: "Ada", status: "open", message: "I reset my password twice and the login page still says it's wrong.", replies: [], }, { id: "T-2", title: "Invoice total is wrong", customer: "Grace", status: "closed", message: "My March invoice charges for 12 seats. We only have 10.", replies: ["You're right, sorry! We've refunded the two extra seats."], }, { id: "T-3", title: "Login link expired", customer: "Linus", status: "open", message: "The sign-in link in your email says it has expired, even when I click it right away.", replies: [], }, ]; search(query: string, status?: "open" | "closed") { const q = query.toLowerCase(); return this.tickets .filter((t) => [t.title, t.customer].some((s) => s.toLowerCase().includes(q))) .filter((t) => !status || t.status === status) .map(({ id, title, customer, status }) => ({ id, title, customer, status })); } get(id: string) { return this.tickets.find((t) => t.id === id); } addReply(id: string, text: string) { const ticket = this.get(id); ticket?.replies.push(text); return ticket; } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` ```ts requests.test.ts import { test, expect } from "@frontmcp/testing"; const ids = (result: { json(): any }) => result.json().tickets.map((t: { id: string }) => t.id); test("What's going on with Ada's login problem?", async ({ mcp }) => { expect(ids(await mcp.tools.call("search_tickets", { query: "Ada" }))).toEqual(["T-1"]); const ticket = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(ticket.json().message).toContain("reset my password"); }); test("Are there any open tickets about invoices?", async ({ mcp }) => { expect(ids(await mcp.tools.call("search_tickets", { query: "invoice", status: "open" }))).toEqual([]); }); test("Tell Linus we've sent him a new sign-in link.", async ({ mcp }) => { const [id] = ids(await mcp.tools.call("search_tickets", { query: "Linus" })); const result = await mcp.tools.call("add_reply", { id, text: "We've sent you a new sign-in link." }); expect(result.json().replies).toEqual(["We've sent you a new sign-in link."]); }); test("T-1 is fixed. Close it.", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirmed: true } })); const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result.json()).toEqual({ id: "T-1", status: "closed" }); }); test("(T-2 attached) Why did this customer get a refund?", async ({ mcp }) => { const ticket = await mcp.resources.read("tickets://T-2"); expect(ticket.json().replies[0]).toContain("refunded"); }); test("Draft a reply to T-3.", async ({ mcp }) => { const prompt = await mcp.prompts.get("draft_reply", { id: "T-3" }); expect(prompt).toHaveMessages(2); expect(prompt.messages[0].content.resource.uri).toBe("tickets://T-3"); }); test("Is there a help article about sign-in links?", async ({ mcp }) => { const result = await mcp.tools.call("search_articles", { query: "sign-in link" }); expect(result.json().articles.map((a: { id: string }) => a.id)).toEqual(["KB-2"]); }); ``` Open the Capabilities tab. A client sees one list with the tools from both apps. Apps are for you, not the model: they keep each area's code, data and settings together, and the server combines them. Tool names still have to make sense side by side, which is one more reason for specific names like `search_tickets` and `search_articles` over a plain `search`. Now open the Tests tab. Each test is one of the requests you started with, carried out the way a model would carry it out. Your sample requests make a good first test suite: when they pass, the server does what people will ask of it. [Grouping Capabilities into Apps](https://frontmcp.dev/learn/grouping-capabilities-into-apps) covers apps in depth, and [Testing Your Server](https://frontmcp.dev/learn/testing-your-server) covers tests. ## Recap - Start from the requests people will make, not from your API. They're your mockup. - Break the requests into jobs and the data they need, and leave out what nobody asks for. - Decide who starts each job: the model (a tool), the client app or user attaching data (a resource), or the user picking a workflow (a prompt). One job can be both a tool and a resource. - Give each job its own tool, named after the job, asking only for what the model can know, and returning what the next step needs. - Annotate every tool, and ask the user with `this.elicit()` before the changes that are costly to get wrong. - Group capabilities that share data and settings into an app, and let the server combine apps. ## Where to go from here To build this server one step at a time, with each idea explained as it comes up, follow the [Help Desk tutorial](https://frontmcp.dev/learn/tutorial-help-desk). To learn each kind of capability properly, start the [Describing Capabilities](https://frontmcp.dev/learn/describing-capabilities) chapter. --- # Installation > Create a FrontMCP project with Node.js 24+, run it locally and connect an MCP client. Includes existing-project setup and troubleshooting. Source: https://frontmcp.dev/learn/installation [Covers FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) as of November 14, 2026 The Playground is the quickest way to learn FrontMCP. To build a real server, create a project on your machine. It takes one command. **You will learn** - How to create a new FrontMCP project - How to add FrontMCP to a project you already have - How to run your server and test it with the MCP Inspector - How to fix the most common setup problems ## Before you start You need **Node.js 24 or later** and **npm 10 or later** (pnpm and yarn work too). FrontMCP is developed and tested on Node 24. Check your versions: ```bash node --version npm --version ``` ## Creating a new server ```bash npx frontmcp create my-mcp-server cd my-mcp-server npm install npm run dev ``` `create` asks a few questions: - **Deployment target**: Node.js (Docker), Vercel, AWS Lambda or Cloudflare Workers - **Redis**: Docker Compose, an existing Redis, or none (Docker target only) - **GitHub Actions**: whether to add CI/CD workflows Pass `--yes` to accept the defaults, or answer up front with flags such as `--target cloudflare` or `--pm pnpm`. `create` doesn't install anything, so run `npm install` (or your package manager) before `npm run dev`. Your server is now running at `http://localhost:3000/mcp`, and `http://localhost:3000/health` answers `{"status":"ok", …}`. The project looks like this (Docker target): *[Illustration: The new project in a file explorer: my-mcp-server with ci/ (Dockerfile, docker-compose.yml), src/ with main.ts marked @FrontMcp, calc.app.ts marked @App, and tools/add.tool.ts marked @Tool, then package.json and tsconfig.json. Beside it, the same three files as nested boxes: the @FrontMcp server in main.ts contains the @App in calc.app.ts, which contains the @Tool add in add.tool.ts.]* That's the same server you built at the end of the [Quick Start](https://frontmcp.dev/learn#grouping-capabilities-into-an-app-and-a-server). ## Adding FrontMCP to an existing project ```bash npm install @frontmcp/sdk reflect-metadata npm install -D frontmcp @types/node@^24 npx frontmcp init ``` `init` updates `tsconfig.json` with the decorator settings FrontMCP needs: ```json tsconfig.json { "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true } } ``` Then import `reflect-metadata` once, at the very top of your entry file, before anything from FrontMCP: ```ts src/main.ts import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; ``` ## Running and testing your server Your project comes with these scripts: | Command | What it does | | --- | --- | | `npm run dev` | Starts the server with hot reload and type checking | | `npm run build` | Compiles a production build to `./dist` | | `npm run inspect` | Opens the MCP Inspector | | `npm run doctor` | Checks your Node and npm versions and your config | To have Claude Code call your server while it reloads, connect it through `frontmcp dev --stdio --serve`: see [Build an MCP Server With Claude Code Connected to It](https://frontmcp.dev/blog/claude-code-hot-reload). To test the server the way a client sees it, keep `npm run dev` running and start the Inspector in a second terminal: ```bash npm run inspect ``` It opens at `http://localhost:6274`. Enter `http://localhost:3000/mcp` as the server URL, click **Connect**, pick the `add` tool, and call it with `{ "a": 2, "b": 3 }`. You'll get `5` back, just as in the Playground. ## Connecting a client FrontMCP speaks MCP's Streamable HTTP transport, so any MCP client that supports it can connect to `http://localhost:3000/mcp`. That includes Claude Desktop, Claude Code and Cursor. ## Starting a monorepo For several servers that share code, scaffold an Nx workspace: ```bash npx frontmcp create my-platform --nx --pm pnpm ``` It creates `apps/`, `libs/` and `servers/` folders, plus generators for new apps, tools and servers. To add the plugin to a workspace you already have, run `nx add @frontmcp/nx`: it installs FrontMCP and makes the `build` and `test` targets cacheable. The [Nx plugin](https://frontmcp.dev/reference/nx#installing-it) reference has the details. ## Troubleshooting ### The server won't start Check that you're on Node 24 or later, that nothing else is using port 3000, and that the console shows no TypeScript errors. Then run `npm run doctor`. ### My tools don't appear 1. Make sure the tool is listed in its app's `tools` array, and the app is listed in `@FrontMcp({ apps })`. 2. Make sure `tsconfig.json` has `experimentalDecorators` and `emitDecoratorMetadata` set to `true`. 3. Make sure `import "reflect-metadata"` is the first line of `main.ts`. ### "skill storage needs the optional peer dependency 'vectoriadb'" You're on FrontMCP 1.8, which lists `vectoriadb` as an optional peer dependency but loads it at startup, so an install without dev dependencies, like a production Docker image, can't start. Since 1.9.1, `@frontmcp/sdk` depends on `vectoriadb` (and `vectoriadb` on `tslib`), and a production install starts. Upgrade, or on 1.8 add both to your dependencies: ```bash npm install vectoriadb tslib ``` ### The Inspector can't connect Check that `http://localhost:3000/health` responds, and that you entered `http://`, not `https://`. --- # Docs for Your Agent > Give your coding agent FrontMCP's docs for the release your project uses, through FrontMCP's own MCP server at mcp.frontmcp.dev. Source: https://frontmcp.dev/learn/docs-for-your-agent [Covers FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) as of November 14, 2026 A coding agent knows FrontMCP from whatever release it was trained on, if any. FrontMCP's docs server gives it these docs instead, over MCP, for the release your project uses: it searches them, reads pages and sections, looks up an API by name, returns runnable examples, and says what changed between two releases. **You will learn** - How to connect your agent to the docs server - How to pin it to the FrontMCP release your project uses - What each of its tools does ## Connecting your agent The server is at `https://mcp.frontmcp.dev`, and in the [MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=dev.frontmcp.mcp%2Ffrontmcp) as `dev.frontmcp.mcp/frontmcp`. It needs no key and no sign-in, and it only reads. With Claude Code: ```bash claude mcp add --transport http frontmcp-docs https://mcp.frontmcp.dev ``` Clients that keep their servers in a JSON file take an entry with the URL: ```json { "mcpServers": { "frontmcp-docs": { "url": "https://mcp.frontmcp.dev" } } } ``` The field that marks an entry as a URL differs between clients (`type`, `transport`, or none), so check your client's documentation for it. The server speaks MCP from 2024-11-05 to 2026-07-28 over Streamable HTTP, as any FrontMCP server does. ## Pinning a release `https://mcp.frontmcp.dev` serves the docs of the latest release. To pin one, add it to the URL: | URL | Docs for | | --- | --- | | `https://mcp.frontmcp.dev` | The latest release | | `https://mcp.frontmcp.dev/1.9.4` | That release | | `https://mcp.frontmcp.dev/1.9` | The newest patch of 1.9 | The server's earlier URL, `https://frontmcp.dev/mcp`, still works, with the same pins after it: `https://frontmcp.dev/mcp/1.9.4`. The server documents each release from 1.9.2 on, and `get_versions` lists them; the [versions page](https://frontmcp.dev/versions) has every release's notes. Without a pin, your agent can find the release itself: the server tells it to call `resolve_version` with your project's `package.json` or lockfile first, and to pass the release it gets to the other tools. ## Choosing a workspace A lockfile can contain several SDK releases. `resolve_version` refuses an ambiguous result instead of selecting the first record. For npm or pnpm, pass `workspace: "."` for the root or a path such as `packages/api`. For Yarn resolutions or a project you can inspect directly, pass `installedVersion` read from that project\'s resolved `@frontmcp/sdk/package.json`. A conflicting manifest/installation is an error to investigate. Search results identify their snapshot, content kind and article dates. Maintained docs are preferred for current instructions; a blog in a release snapshot is still a dated article unless its own scope says otherwise. ## What it offers | Tool | What it does | | --- | --- | | `resolve_version` | Which documented release a project should read, from its lockfile (npm, Yarn or pnpm), its `package.json` or a version range, and the URL that pins it | | `get_versions` | The documented releases, newest first, with their release notes | | `search_docs` | Full-text search over the docs, by section: the page, the heading, the path with its `#anchor`, and the start of its text | | `get_page` | A page as Markdown, or one section of it. It takes a path, a frontmcp.dev URL, or a link to the old docs on docs.agentfront.dev, which it maps to its page here | | `list_pages` | The docs as the sidebar has them: Learn, Reference, Examples and Compare | | `lookup_api` | An API by name: a decorator (`@Tool`), a function (`createFetchHandler`), an option, an error code (`TOOL_NOT_FOUND`) or a CLI flag, with what the Reference says and where | | `get_example` | A page's Playgrounds, or one's files and tests, with how to run them in your project | | `whats_changed` | Between two releases: their release notes, every "Changed in" note in the docs with its page, and the pages that changed | | `get_skill` | FrontMCP's skills catalog: instructions for building with FrontMCP, and their reference files | It also has three prompts. `upgrade_frontmcp` asks your agent to move a project from one release to another, change by change. `migrate_from_fastmcp` and `migrate_from_typescript_sdk` ask it to move a server to FrontMCP from FastMCP for TypeScript or the official SDK, by [Migrating from FastMCP](https://frontmcp.dev/learn/migrating-from-fastmcp#migrate-with-a-coding-agent) and [Migrating from the TypeScript SDK](https://frontmcp.dev/learn/migrating-from-the-typescript-sdk#migrate-with-a-coding-agent). ### How the server is built It's a FrontMCP server on a Cloudflare Worker: [`createFetchHandler()`](https://frontmcp.dev/reference/sdk/create-fetch-handler) behind a Worker entry, as [Cloudflare Workers](https://frontmcp.dev/reference/deployment/cloudflare-workers) describes. Each release's docs come from this site's history: when a release moves the site to the next one, the outgoing release's pages are kept, and the server reads them as Markdown, with a search index and an index of the Reference's APIs, from the Worker's static assets. ## Troubleshooting ### `Too many requests: at most 120 a minute from one address.` The server answers each address 120 requests a minute, then `429` with `Retry-After: 60`. Wait a minute, or have your agent search before it reads pages one by one. ### `FrontMCP 1.8.7 isn't documented here.` The server documents releases from 1.9.2 on. Pin the nearest one, or ask `whats_changed` with `from` set to your release to see what changed since, which also covers releases the server doesn't document. --- # Migrating from the TypeScript SDK > Preserve an MCP server's tools, resources, errors and access rules while moving shared services into FrontMCP. Includes a reproducible contract comparison. Source: https://frontmcp.dev/learn/migrating-from-the-typescript-sdk [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Migrate one client contract at a time. Before you move any code, record what clients rely on: tool names, input schemas, results, resource URIs and refused requests. FrontMCP adds structure around the protocol. It does not make every SDK middleware, transport or schema choice a drop-in match. For a small, stable server, staying with the SDK may be the simpler choice. **You will learn** - How to compare an SDK server and a FrontMCP server with the same contract check - Which FrontMCP API replaces each official SDK construct - How one tool looks before and after the move - What to check for auth and for the endpoint before clients switch ## Compare two implementations [Download the contract fixtures](https://frontmcp.dev/downloads/crm-evaluation.tgz). Their README includes the SDK migration check. The check runs an official TypeScript SDK server and a FrontMCP server against the same synthetic records. Both servers expose two tools, a resource and the same result shape. The check compares the tool schemas, successful calls, a missing record, an unauthorized operation and resource content. Extract it and, with Node.js 24 or later, run in its folder: ```bash npm ci npm run test:migration ``` The output names the package versions that are actually installed. The [dated record](https://frontmcp.dev/evidence/migration.json) keeps one run: official SDK 1.32.1 and FrontMCP 1.10.10, on 2026-10-22. The official SDK server runs over an in-memory transport. FrontMCP runs through its in-process entry. So the check compares the application contract a client sees. HTTP routing, OAuth and deployment need the endpoint checks [below](https://frontmcp.dev/learn/migrating-from-the-typescript-sdk#verify-the-endpoint-before-switching-clients). ## Migrate with a coding agent A coding agent can do this migration in your project. Connect it to [FrontMCP's docs server](https://frontmcp.dev/learn/docs-for-your-agent) first, so it reads this page and the APIs it needs for the release it installs, rather than writing FrontMCP code from what it was trained on. Then paste this prompt into it, in your SDK project: ```text title="Prompt for your coding agent" Migrate this project's MCP server from the official MCP TypeScript SDK (`@modelcontextprotocol/sdk`) to FrontMCP 1.12.2, without changing what its MCP clients see: tool names, input schemas, results, error messages, resource URIs and the requests it refuses. Follow the guide at https://frontmcp.dev/learn/migrating-from-the-typescript-sdk, one section at a time. If FrontMCP's docs MCP server (https://mcp.frontmcp.dev) is connected, read the guide with its get_page tool and look up every FrontMCP API you use with lookup_api and get_example, passing version "1.12.2". Otherwise fetch https://frontmcp.dev/learn/migrating-from-the-typescript-sdk.md and the pages it links to. Don't write FrontMCP code from memory. 1. List what the server has: every registerTool (or tool), registerResource (with or without a ResourceTemplate) and registerPrompt; how it connects (stdio, or Streamable HTTP inside its own HTTP server); its auth; shared services such as API clients and stores; and how its tools fail (isError results or thrown errors). Show me the list before you change code. 2. Record what clients see now: drive the SDK server in-process with an InMemoryTransport linked pair and the SDK's Client, and save tools/list, a successful call and a refused call for each tool, and each resource read. 3. Add FrontMCP next to the SDK server as https://frontmcp.dev/learn/installation#adding-frontmcp-to-an-existing-project shows, with @frontmcp/sdk and frontmcp pinned to 1.12.2. Keep the SDK server working until I switch clients. 4. Move one contract at a time, by the guide's mapping table: McpServer becomes an @FrontMcp server with an @App; each tool a @Tool class with the same Zod input shape; resources, templates and prompts their decorated classes (a @Prompt's arguments are a list, not a Zod shape); a failure this.fail(new PublicMcpError(message, code)). Move shared services into a provider that tools read with this.get(). After each part, write @frontmcp/testing tests that check the recorded answers, run them, and don't start the next part until they pass. 5. Where FrontMCP answers differently, keep its behaviour and list the difference for me instead of hiding it: a failure gets _meta.code and an errorId, and in production only a PublicMcpError keeps its message. 6. A FrontMCP endpoint is public by default. Ask me which auth mode to use before you move anything protected, and keep the negative cases: call restricted tools directly by name, not only through discovery. 7. Ask me before you rename anything a client sees, change the endpoint path, or delete SDK code. When you finish, report what you moved, the test results, every difference a client will see, anything with no FrontMCP counterpart, and the guide's checks before switching clients: the exact endpoint path and protocol revision, missing, expired and wrong-audience tokens, two callers with different access, a build for the real target, and a way to roll back. ``` With the docs server connected, the same prompt is also its `migrate_from_typescript_sdk` MCP prompt, so a client that lists MCP prompts can start it without copying. Review the agent's work as you would anyone's: the recorded answers and the tests that check them are what show the clients see no difference. ## Map SDK constructs to FrontMCP The left column is v1 of the official SDK, `@modelcontextprotocol/sdk`. It's the line the migration check runs, and the one FrontMCP builds on. The last column links the FrontMCP reference for each row. | Official SDK v1 | FrontMCP | Reference | | --- | --- | --- | | `new McpServer({ name, version })` | A class decorated with `@FrontMcp({ info: { name, version }, apps })`. Each app is an `@App` that lists its tools, resources and prompts. | [`@FrontMcp`](https://frontmcp.dev/reference/sdk/frontmcp), [`@App`](https://frontmcp.dev/reference/sdk/app) | | `server.registerTool(name, { description, inputSchema }, handler)`, or the deprecated `server.tool()` | A `@Tool({ name, description, inputSchema })` class. `inputSchema` is the same Zod shape, like `{ id: z.string() }`. `execute()` receives the validated input. The `tool()` function is the form without a decorator. | [`@Tool`](https://frontmcp.dev/reference/sdk/tool) | | `server.registerResource(name, uri, metadata, read)` | A `@Resource({ name, uri, mimeType })` class whose `execute()` returns the content | [`@Resource`](https://frontmcp.dev/reference/sdk/resource) | | `server.registerResource(name, new ResourceTemplate(pattern, { list }), metadata, read)` | A `@ResourceTemplate({ name, uriTemplate })` class. `execute(uri, params)` receives the matched parameters. | [`@ResourceTemplate`](https://frontmcp.dev/reference/sdk/resource-template) | | `server.registerPrompt(name, { argsSchema }, handler)` | A `@Prompt({ name, arguments })` class. `arguments` is a list of `{ name, description, required }` entries, not a Zod shape. | [`@Prompt`](https://frontmcp.dev/reference/sdk/prompt) | | `server.connect(new StdioServerTransport())` | `FrontMcpInstance.runStdio(config)` | [`runStdio()`](https://frontmcp.dev/reference/sdk/frontmcp-instance#frontmcpinstancerunstdioconfigorclass) | | `StreamableHTTPServerTransport` inside your own HTTP server | In Node, importing the `@FrontMcp` class starts an HTTP server. `FrontMcpInstance.createHandler()` and `createFetchHandler()` return a handler for a host you choose. | [`FrontMcpInstance`](https://frontmcp.dev/reference/sdk/frontmcp-instance), [`createFetchHandler()`](https://frontmcp.dev/reference/sdk/create-fetch-handler) | | `InMemoryTransport.createLinkedPair()` with a `Client` | `connect()` gives you an MCP client in memory. `create()` calls tools directly, with no client. | [`connect()`](https://frontmcp.dev/reference/sdk/connect), [`create()`](https://frontmcp.dev/reference/sdk/create) | | A handler that returns `{ isError: true, content }`, or throws | `this.fail(new PublicMcpError(message, code))` | [`this.fail`](https://frontmcp.dev/reference/sdk/fail), [Error classes](https://frontmcp.dev/reference/sdk/error-classes) | > **Note: Two methods named registerTool()** > > FrontMCP also has a `server.registerTool()`. It belongs to the server that `create()` or `createDirect()` returns, and adds a tool to a server that is already running. It takes a JSON Schema, not a Zod shape. A migrated tool belongs in a `@Tool` class instead. See [`server.registerTool()`](https://frontmcp.dev/reference/sdk/register-tool). ## Move one tool This is `get_report` from the migration check. It reads one record by id, and it fails when the record is missing. ### Before: the official SDK Here is the SDK version, for `@modelcontextprotocol/sdk` 1.32.1 and `zod` 4. It's the SDK server from `scripts/check-migration.mjs`, cut down to this one tool and served over stdio instead of in memory. The handler closes over a store object at module scope. This file can't run in a Playground, which only loads FrontMCP packages: ```ts server.ts import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; const reports = [{ id: "R-1", total: 42 }]; class ReportStore { get(id: string) { return reports.find((report) => report.id === id); } } const store = new ReportStore(); const server = new McpServer({ name: "reports", version: "1.0.0" }); server.registerTool( "get_report", { description: "Read one fixture report", inputSchema: { id: z.string() } }, async ({ id }) => { const report = store.get(id); if (!report) return { isError: true, content: [{ type: "text", text: "Report not found" }] }; return { content: [{ type: "text", text: JSON.stringify(report) }], structuredContent: report }; }, ); await server.connect(new StdioServerTransport()); ``` On SDK v2, `@modelcontextprotocol/server`, the [comparison's example](https://frontmcp.dev/compare/official-typescript-sdk#with-the-official-sdk) passes `inputSchema` as `z.object(...)` instead. ### After: FrontMCP The same tool in FrontMCP. The store becomes a provider, and the tool reads it with `this.get()`. The Playground wraps the exported tool and provider in a one-app server and calls `get_report`. The **Tests** tab checks the contract: Initial call configuration: ```js { tool: "get_report", arguments: { id: "R-1" } } ``` ```ts get-report.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ReportStore } from "./report-store"; @Tool({ name: "get_report", description: "Read one fixture report", inputSchema: { id: z.string() }, }) export class GetReport extends ToolContext { async execute({ id }: { id: string }) { const report = this.get(ReportStore).get(id); if (!report) this.fail(new PublicMcpError("Report not found", "NOT_FOUND")); return report; } } ``` ```ts report-store.ts import { Provider } from "@frontmcp/sdk"; const reports = [{ id: "R-1", total: 42 }]; @Provider({ name: "ReportStore" }) export class ReportStore { get(id: string) { return reports.find((report) => report.id === id); } } ``` ```ts get-report.test.ts import { test, expect } from "@frontmcp/testing"; test("`id` is a required string, as in the SDK version", async ({ mcp }) => { const tools = await mcp.tools.list(); const getReport = tools.find((tool) => tool.name === "get_report"); expect(getReport?.inputSchema.properties).toEqual({ id: { type: "string" } }); expect(getReport?.inputSchema.required).toEqual(["id"]); }); test("the record arrives as structured content with a JSON text copy", async ({ mcp }) => { const result = await mcp.tools.call("get_report", { id: "R-1" }); expect(result).toBeSuccessful(); expect(result.raw.structuredContent).toEqual({ id: "R-1", total: 42 }); expect(result.json()).toEqual({ id: "R-1", total: 42 }); }); test("a missing record keeps the SDK's error text and adds a code", async ({ mcp }) => { const result = await mcp.tools.call("get_report", { id: "missing" }); expect(result).toBeError("NOT_FOUND"); expect(result.text()).toBe("Report not found"); expect(result.raw._meta?.errorId).toMatch(/^err_/); }); ``` What stays the same for clients: - The tool name, `get_report`, and its input: `id`, a required string. - A found record arrives as `structuredContent`, with the same JSON as text. - A missing record is an `isError` result with the text `Report not found`. What changes: - The store is a provider. Tools ask for it with `this.get(ReportStore)`, so they can share one instance. - The failure goes through `this.fail()`. FrontMCP adds `_meta.code` (`NOT_FOUND` here) and an `errorId` to the result. - Only a `PublicMcpError` keeps its message in production. FrontMCP replaces the message of any other error with an error ID ([Error classes](https://frontmcp.dev/reference/sdk/error-classes#in-production)). - Your code doesn't build the server. In a project, list the tool and the provider in an `@App`, and the app in `@FrontMcp`. The check's other refusal, a caller who may not read the report, depends on who is calling. That needs an auth mode, so this example leaves it out. See [Choose auth explicitly](https://frontmcp.dev/learn/migrating-from-the-typescript-sdk#choose-auth-explicitly). ## Move shared services into a provider Keep your API client independent of the transport. Register it as a provider, as `ReportStore` is above. Tools then get it with `this.get()`, instead of reading a module global or wiring it up per request. Move the tools into an app, and register the app on the server. Keep the public names and resource URIs your clients already use. Don't expose new class names to existing clients. [The tool reference](https://frontmcp.dev/reference/sdk/tool), [providers](https://frontmcp.dev/reference/sdk/provider), [resources](https://frontmcp.dev/reference/sdk/resource) and [testing](https://frontmcp.dev/reference/testing) cover each step. The [reporting download](https://frontmcp.dev/downloads/tenant-reporting.tgz) shows a complete local registration, with its tests adapted. ## Choose auth explicitly A FrontMCP endpoint is public by default. Choose [an auth mode](https://frontmcp.dev/reference/auth/modes) before you migrate protected data. Check how the server handles issuer, audience, expiry and scopes. Take tenant claims from a trusted identity, and enforce record access in your API. Static test keys don't replace a real identity-provider flow. Keep your negative cases. A tool missing from discovery is not the same as a server that refuses the call, so also call restricted tools directly by name. For destructive operations, keep authorization separate from [user approval](https://frontmcp.dev/learn/asking-for-approval). ## Verify the endpoint before switching clients 1. Keep the existing endpoint running while the new one runs in preview. 2. Test the exact endpoint path and the protocol revision you chose. Test initialize and session behavior where they apply, the tool schemas and resource reads. 3. Send missing, expired and wrong-audience tokens. Test two callers with different access. 4. Compare typical success and error results. Include any widget or resource metadata the client reads. 5. Build for the real target, and configure secrets and state. Then send the same requests to the preview. 6. Move a small group of clients first, and watch for failures. Keep the previous deployment ready for rollback. The [deployment guide](https://frontmcp.dev/reference/deployment) covers each target's constraints. Passing the in-memory contract check does not show that a hosted deployment works, or that OAuth behaves the same. Keep unsupported middleware or client features on the original path until a replacement has been checked. --- # Migrating from FastMCP for TypeScript > Move a FastMCP for TypeScript server to FrontMCP one client contract at a time: tools, errors, logs, resources, prompts, auth and transports. Source: https://frontmcp.dev/learn/migrating-from-fastmcp [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 This guide moves a server written with FastMCP for TypeScript, punkpeye's `fastmcp` package, to FrontMCP without changing what its clients see: tool names, input schemas, result text, error messages, resource URIs and prompt messages. Most FastMCP calls have a FrontMCP counterpart. A few FrontMCP defaults differ in ways a client notices, and some FastMCP features have no counterpart. Move one contract at a time, and compare it with what FastMCP sent before you move the next. Prefect's `@prefecthq/fastmcp-ts` is a different library; [FrontMCP vs Prefect's FastMCP TypeScript](https://frontmcp.dev/compare/fastmcp-ts) covers it. **You will learn** - Which FrontMCP construct replaces each FastMCP one, and which have no counterpart - How to port a tool and keep the result its clients already read - Where FrontMCP answers differently: invalid input, log messages and session state - An order to migrate in, and what to check before each next step ## Before you start FastMCP 4.23.4's README says it implements the handshake-based MCP revisions, 2025-11-25 and earlier, and doesn't support 2026-07-28 ([README](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md?plain=1#L5-L7)). When this site checked it on 2026-10-20, its server answered 2026-07-28 requests with `400` over HTTP and `-32601` over stdio ([How this was checked](https://frontmcp.dev/compare/fastmcp-typescript#how-this-was-checked)). FrontMCP serves every revision from 2024-11-05 to 2026-07-28 over Streamable HTTP and stdio, except 2026-07-28 on [stdio servers with Claude Code channels](https://frontmcp.dev/reference/server/protocol-versions#a-stdio-server-with-channels-declines-2026-07-28) ([Protocol versions](https://frontmcp.dev/reference/server/protocol-versions#revisions-over-stdio)), so clients that start with `initialize` keep working after the move. Moving isn't the only option. If your clients speak 2025-11-25 or earlier and you don't need what FrontMCP adds, [FrontMCP vs FastMCP for TypeScript](https://frontmcp.dev/compare/fastmcp-typescript#when-to-choose-fastmcp) lists reasons to stay. For 2026-07-28 with FastMCP's API, its README points to ViteMCP, by the same author ([FrontMCP vs ViteMCP](https://frontmcp.dev/compare/vitemcp)). A FrontMCP project needs Node 24 or later and TypeScript's decorator settings; `frontmcp init` adds them to an existing project ([Installation](https://frontmcp.dev/learn/installation#adding-frontmcp-to-an-existing-project)). The FastMCP code on this page ran on 2026-10-25 with `fastmcp` 4.23.4, `zod` 4.6.7, the official SDK 1.32.2 that `fastmcp` installs, and `tsx`. The Playgrounds run only FrontMCP, with a client on MCP 2026-07-28. The sections follow the order to migrate in, and each ends with what to check before the next: 1. [Record what clients see now](https://frontmcp.dev/learn/migrating-from-fastmcp#record-what-clients-see-now) 2. [Port the tools](https://frontmcp.dev/learn/migrating-from-fastmcp#port-the-tools) 3. [Port errors, logs and progress](https://frontmcp.dev/learn/migrating-from-fastmcp#port-errors-logs-and-progress) 4. [Port resources, templates and prompts](https://frontmcp.dev/learn/migrating-from-fastmcp#port-resources-templates-and-prompts) 5. [Move state out of the session](https://frontmcp.dev/learn/migrating-from-fastmcp#move-state-out-of-the-session) 6. [Choose auth](https://frontmcp.dev/learn/migrating-from-fastmcp#choose-auth) 7. [Serve the same endpoint, then switch clients](https://frontmcp.dev/learn/migrating-from-fastmcp#serve-the-same-endpoint-then-switch-clients) ## Migrate with a coding agent A coding agent can do these steps in your project. Connect it to [FrontMCP's docs server](https://frontmcp.dev/learn/docs-for-your-agent) first, so it reads this page and the APIs it needs for the release it installs, rather than writing FrontMCP code from what it was trained on. Then paste this prompt into it, in your FastMCP project: ```text title="Prompt for your coding agent" Migrate this project's FastMCP for TypeScript server (the `fastmcp` npm package) to FrontMCP 1.12.2, without changing what its MCP clients see: tool names, input schemas, result text, error messages, resource URIs and prompt messages. Follow the guide at https://frontmcp.dev/learn/migrating-from-fastmcp, one section at a time. If FrontMCP's docs MCP server (https://mcp.frontmcp.dev) is connected, read the guide with its get_page tool and look up every FrontMCP API you use with lookup_api and get_example, passing version "1.12.2". Otherwise fetch https://frontmcp.dev/learn/migrating-from-fastmcp.md and the pages it links to. Don't write FrontMCP code from memory. 1. Check the library first. If the project uses `@prefecthq/fastmcp-ts` instead of `fastmcp`, stop and tell me: that is a different library, and this guide doesn't cover it. 2. List what the server has: every addTool, addResource, addResourceTemplate and addPrompt; authenticate; the transport, its endpoint and port; what tools use from their context (log, reportProgress, elicit, session, sessionId); UserError; and any state kept per session. Show me the list before you change code. 3. Record what clients see now, as the guide's "Record what clients see now" section does: drive the FastMCP server in-process with the official MCP SDK's in-memory client, and save its answers, including a call with invalid input. 4. Add FrontMCP next to FastMCP as https://frontmcp.dev/learn/installation#adding-frontmcp-to-an-existing-project shows, with @frontmcp/sdk and frontmcp pinned to 1.12.2. Keep the FastMCP server working until I switch clients. 5. Port one part at a time, in the guide's order: tools; errors, logs and progress; resources, templates and prompts; state kept per session; auth; transports. After each part, write @frontmcp/testing tests that check the recorded answers, run them, and don't start the next part until they pass. 6. Where FrontMCP answers differently by design, keep FrontMCP's behaviour and list the difference for me instead of working around it: invalid input is an INVALID_INPUT tool result, not a -32602 error; input schemas name JSON Schema draft 2020-12 without additionalProperties; log messages are opt-in. A tool that returned a string returns { content: [{ type: "text", text }] } to keep its text. State keyed by the session starts over for MCP 2026-07-28 clients: key it by a handle or the signed-in user, as the guide shows. 7. Ask me before you rename anything a client sees, choose an auth mode, or delete FastMCP code. When you finish, report what you ported, the test results, every difference a client will see, anything with no FrontMCP counterpart, and what to change in each client before switching it: the URL path, the stdio command, the health check and the address the server listens on. ``` With the docs server connected, the same prompt is also its `migrate_from_fastmcp` MCP prompt, so a client that lists MCP prompts can start it without copying. Review the agent's work as you would anyone's: the recorded answers and the tests that check them are what show the clients see no difference. ## What maps to what | FastMCP 4.23.4 | FrontMCP | Watch for | | --- | --- | --- | | `new FastMCP({ name, version })` ([Quickstart](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#quickstart)) | `@FrontMcp({ info: { name, version }, apps })`, with an [`@App`](https://frontmcp.dev/reference/sdk/app) that lists the tools, resources and prompts ([`@FrontMcp`](https://frontmcp.dev/reference/sdk/frontmcp)) | | | `server.addTool({ name, description, parameters, execute })` ([Tools](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#tools)) | A [`@Tool`](https://frontmcp.dev/reference/sdk/tool) class. `inputSchema` takes the `z.object()`'s `.shape`; `execute()` gets the arguments | Zod 4 only: ArkType, Valibot and `jsonSchemaAdapter()` schemas have to be rewritten in Zod | | `execute` returns a string ([Returning a string](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#returning-a-string)) | Return `{ content: [{ type: "text", text }] }` | A returned string arrives as `{"value": …}` ([Port the tools](https://frontmcp.dev/learn/migrating-from-fastmcp#port-the-tools)) | | `outputSchema` ([Structured Tool Output](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#structured-tool-output)) | `outputSchema` ([Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results#declaring-the-shape-with-outputschema)) | | | `throw new UserError(message)` ([Errors](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#errors)) | `this.fail(new PublicMcpError(message))`, or `throw` it ([`this.fail`](https://frontmcp.dev/reference/sdk/fail)) | A `UserError`'s `extras`, which FastMCP sends as `structuredContent` ([`FastMCP.ts`](https://github.com/punkpeye/fastmcp/blob/v4.23.4/src/FastMCP.ts#L3050-L3056)), have no counterpart on this site | | `log.info(message, data)` and `debug`, `warn`, `error` ([Logging](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#logging)) | `this.notify({ message, context: data }, level)` ([`this.notify`](https://frontmcp.dev/reference/sdk/notify)) | FrontMCP sends nothing until the client asks for log messages | | `reportProgress({ progress, total, message })` ([Progress](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#progress)) | `this.progress(progress, total, message)` ([`this.progress`](https://frontmcp.dev/reference/sdk/progress)) | | | `streamContent()` ([Streaming Output](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#streaming-output)) | None | FastMCP's own extension; it isn't part of MCP | | `timeoutMs` on a tool ([Tools](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#tools)) | `timeout: { executeMs }` on the `@Tool` ([Guard options](https://frontmcp.dev/reference/sdk/guard)) | The result's text is `Execution of "add" timed out after 2000ms`, with `_meta.code` `EXECUTION_TIMEOUT`, where FastMCP's said `Tool 'add' timed out after 2000ms` and suggested raising `timeoutMs` | | `server.embedded(uri)` in a tool's result ([Embedded Resources](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#embedded-resources)) | None on this site. Keep the content in a module that the resource and the tool both import | The tool's `resource` block can stay the same | | `elicit({ message, requestedSchema })` ([Elicitation](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#elicitation)) | `this.elicit(message, zodSchema)`, with `elicitation: { enabled: true }` on the server ([`this.elicit`](https://frontmcp.dev/reference/sdk/elicit)) | The answer's `status` is FastMCP's `action`. Under 2026-07-28 the tool runs again from the top when the answer arrives ([side effects](https://frontmcp.dev/reference/sdk/elicit#keeping-side-effects-after-the-question)) | | `session`: what `authenticate` returned ([Custom Authentication](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#custom-authentication)) | [`this.auth`](https://frontmcp.dev/reference/sdk/auth): `user.sub`, `scopes`, `roles`, `claims` | [Choose auth](https://frontmcp.dev/learn/migrating-from-fastmcp#choose-auth) | | `sessionId` ([Session ID and Request ID Tracking](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#session-id-and-request-id-tracking)) | `this.context.sessionId` ([`this.context`](https://frontmcp.dev/reference/sdk/context)) | A new id on every 2026-07-28 request ([Move state out of the session](https://frontmcp.dev/learn/migrating-from-fastmcp#move-state-out-of-the-session)) | | `requestId`, from the client's request ([Session ID and Request ID Tracking](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#session-id-and-request-id-tracking)) | None. `this.context.requestId` is an id FrontMCP makes, not the JSON-RPC `id` ([`this.context`](https://frontmcp.dev/reference/sdk/context#properties)) | | | `signal` ([Cancelling Long Tool Calls](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#cancelling-long-tool-calls-contextsignal)) | [`this.signal`](https://frontmcp.dev/reference/sdk/contexts#thissignal) | | | `server.addResource({ uri, name, mimeType, load })` ([Resources](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#resources)) | A [`@Resource`](https://frontmcp.dev/reference/sdk/resource) class with `execute()` | `load()`'s `{ text }` or `{ blob }` works unchanged | | `server.addResourceTemplate({ uriTemplate, arguments, load })` ([Resource templates](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#resource-templates)) | A [`@ResourceTemplate`](https://frontmcp.dev/reference/sdk/resource-template) class | Parameters come from the URI's placeholders; there's no `arguments` list | | `complete` on a template argument ([auto-completion](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#resource-template-argument-auto-completion)) | A [completer](https://frontmcp.dev/reference/sdk/resource-template#completing-parameters) | | | `server.addPrompt({ name, arguments, load })` ([Prompts](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#prompts)) | A [`@Prompt`](https://frontmcp.dev/reference/sdk/prompt) class with `execute(args)` | | | `complete` or `enum` on a prompt argument ([auto-completion](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#prompt-argument-auto-completion)) | None on this site | | | `authenticate(request)` checking an API key ([Custom Authentication](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#custom-authentication)) | `auth: { mode: "static" }` ([Static keys](https://frontmcp.dev/reference/auth/tokens#static-keys)) | Your code gets an id per key, not an object you return | | `auth: new GoogleProvider(…)`, `GitHubProvider`, `AzureProvider` ([OAuth with Pre-configured Providers](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#oauth-with-pre-configured-providers)) | `auth: { mode: "remote" }` with an OpenID Connect provider you configure ([Remote and proxied auth](https://frontmcp.dev/reference/auth/remote)) | GitHub [can't be used](https://frontmcp.dev/reference/auth/remote#pointing-frontmcp-at-your-providers-endpoints) | | `canAccess`, `requireScopes()`, `requireRole()` ([Tool Authorization](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#tool-authorization)) | `authorities` on the tool ([Authorities](https://frontmcp.dev/reference/auth/authorities#authorities-on-an-entry)), or `this.auth.hasScope()` in `execute()` | | | `server.start({ transportType: "httpStream", httpStream: { port } })` ([HTTP Streaming](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#http-streaming)) | `http: { port, entryPath: "/mcp" }` on `@FrontMcp` ([`http`](https://frontmcp.dev/reference/sdk/frontmcp#http)) | FrontMCP serves the root path unless you set `entryPath` | | `httpStream: { stateless: true }` ([Stateless Mode](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#stateless-mode)) | `transport: { protocol: "stateless-api" }` ([`transport`](https://frontmcp.dev/reference/sdk/frontmcp#transport)) | Only clients before 2026-07-28 have sessions to turn off | | `server.start({ transportType: "stdio" })` ([Quickstart](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#quickstart)) | `FRONTMCP_STDIO=1` ([Starting the server](https://frontmcp.dev/reference/sdk/frontmcp#starting-the-server)) | | | `server.connect()` with `InMemoryTransport`, in tests ([Unit testing](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#unit-testing-with-an-in-memory-transport)) | `@frontmcp/testing` ([Testing](https://frontmcp.dev/reference/testing)) | | | `fastmcp dev`, `fastmcp inspect` ([Running Your Server](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#running-your-server)) | `frontmcp dev`, `frontmcp inspector` ([CLI](https://frontmcp.dev/reference/cli)) | | | `EdgeFastMCP` ([Edge Runtime Support](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#edge-runtime-support)) | [`createFetchHandler()`](https://frontmcp.dev/reference/sdk/create-fetch-handler), or a [Cloudflare Workers build](https://frontmcp.dev/reference/deployment/cloudflare-workers) | | ## Record what clients see now Save what the FastMCP server answers before you change any code: the FrontMCP tests below check these answers. FastMCP's `server.connect()` attaches the server to a transport you create, so a script can drive it in-process with the official SDK's client ([Unit testing with an in-memory transport](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#unit-testing-with-an-in-memory-transport)). Export the `FastMCP` instance from a module that doesn't call `start()`, then run this with `npx tsx record-contract.ts`: ```ts record-contract.ts import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { server } from "./server.js"; const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "contract-recorder", version: "1.0.0" }); await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); const contract = { tools: await client.listTools(), add: await client.callTool({ name: "add", arguments: { a: 2, b: 3 } }), addWithAString: await client.callTool({ name: "add", arguments: { a: "2", b: 3 } }).catch((error) => ({ code: error.code, message: error.message })), }; console.log(JSON.stringify(contract, null, 2)); await client.close(); ``` For FastMCP's Quickstart server, with its one tool, `add`, it printed this (the error message is shortened): ```json { "tools": { "tools": [ { "name": "add", "description": "Add two numbers", "inputSchema": { "type": "object", "properties": { "a": { "type": "number" }, "b": { "type": "number" } }, "required": ["a", "b"], "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false } } ] }, "add": { "content": [{ "type": "text", "text": "5" }] }, "addWithAString": { "code": -32602, "message": "MCP error -32602: … Tool 'add' parameter validation failed: a: Invalid input: expected number, received string. …" } } ``` Add a call for every tool, resource and prompt your clients use, with `listResources()`, `listResourceTemplates()`, `readResource()`, `listPrompts()` and `getPrompt()`, and a failing call for each tool. **Before you move on:** the recording has every name and URI your clients use, and a successful and a failing answer for each tool. ## Port the tools FastMCP's [Quickstart](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#quickstart), which answered over stdio as recorded above (the recording drove the same server, exported instead of started): ```ts server.ts import { FastMCP } from "fastmcp"; import { z } from "zod"; const server = new FastMCP({ name: "My Server", version: "1.0.0", }); server.addTool({ name: "add", description: "Add two numbers", parameters: z.object({ a: z.number(), b: z.number(), }), execute: async (args) => { return String(args.a + args.b); }, }); server.start({ transportType: "stdio", }); ``` In FrontMCP the same server is three declarations: the tool, an app that lists it, and the server that lists the app. FastMCP sends a returned string as one text block ([Returning a string](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#returning-a-string)), so `execute()` returns that block, and the client gets the same answer. The **Tests** tab checks it against the recording. Initial call configuration: ```js { tool: "add", arguments: { a: 2, b: 3 } } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "add", description: "Add two numbers", inputSchema: { a: z.number(), b: z.number() }, }) export class Add extends ToolContext { async execute({ a, b }: { a: number; b: number }) { return { content: [{ type: "text", text: String(a + b) }] }; } } @App({ id: "calc", name: "Calculator", tools: [Add] }) export class CalcApp {} @FrontMcp({ info: { name: "My Server", version: "1.0.0" }, apps: [CalcApp] }) export default class Server {} ``` ```ts add.test.ts import { test, expect } from "@frontmcp/testing"; test("2 + 3 is the text 5, with no structuredContent, as in the recording", async ({ mcp }) => { const result = await mcp.tools.call("add", { a: 2, b: 3 }); expect(result.raw.content).toEqual([{ type: "text", text: "5" }]); expect(result.raw.structuredContent).toBeUndefined(); }); test("tools/list has the same name, description and inputs", async ({ mcp }) => { const add = (await mcp.tools.list()).find((tool) => tool.name === "add"); expect(add?.description).toBe("Add two numbers"); expect(add?.inputSchema).toEqual({ type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"], $schema: "https://json-schema.org/draft/2020-12/schema", }); }); test("a string where a number belongs is an INVALID_INPUT result, not a -32602 error", async ({ mcp }) => { const result = await mcp.tools.call("add", { a: "2", b: 3 }); expect(result.error).toBeUndefined(); expect(result).toBeError("INVALID_INPUT"); }); test("the server still says it is My Server 1.0.0", async ({ mcp }) => { const result = await mcp.tools.call("add", { a: 2, b: 3 }); expect(result.raw._meta?.["io.modelcontextprotocol/serverInfo"]).toEqual({ name: "My Server", version: "1.0.0" }); }); ``` A 2026-07-28 result also carries `resultType` and the server's name in `_meta`, which the last test reads. Two answers differ from the recording, and the tests show both: - **The input schema's keywords.** FrontMCP names JSON Schema draft 2020-12 and leaves out `additionalProperties`. FastMCP named draft-07 and added `additionalProperties: false`, whatever the schema said ([Tools](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md?plain=1#L634-L640)). The properties and `required` are the same. - **Invalid input.** FrontMCP answers with a tool result, `isError: true` and `_meta.code` `INVALID_INPUT`, which the model reads and can correct ([Your First Tool](https://frontmcp.dev/learn/your-first-tool#what-happens-when-a-tool-is-called)). FastMCP answered with a JSON-RPC error, `-32602` ([`FastMCP.ts`](https://github.com/punkpeye/fastmcp/blob/v4.23.4/src/FastMCP.ts#L2810-L2817)). Check any client code or test that looks for `-32602`. - **An unknown tool.** FrontMCP answers with a tool result too, `isError: true` and `_meta.code` `TOOL_NOT_FOUND`, with the text `Tool "multiply" not found`. FastMCP answered with the JSON-RPC error `-32602` and `Unknown tool: multiply`. - **The order of `tools/list`.** FrontMCP lists tools by name; FastMCP listed them in the order they were added. A client that relies on the order needs changing. FastMCP's `parameters` was a `z.object()`; FrontMCP's `inputSchema` takes its fields. Keep the object and pass its `.shape`, as the next section does. Schemas in ArkType, Valibot or plain JSON Schema have to be rewritten in Zod 4, which is the only schema library FrontMCP takes ([Schemas Are Contracts](https://frontmcp.dev/learn/schemas-are-contracts)). > **Pitfall: A returned string isn't sent as it is** > > `return String(a + b)` runs in FrontMCP too, but the client gets `{"value":"5"}` as the text, and the same object as `structuredContent` ([Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results#what-comes-back-from-toolscall)). Return the content block to keep the text. When the clients can take a change, return an object, like `{ sum: 5 }`, which arrives as `structuredContent` with a JSON copy as text ([FrontMCP vs FastMCP](https://frontmcp.dev/compare/fastmcp-typescript#in-frontmcp)); make that change as a step of its own, after the move. **Before you move on:** for each tool, the `tools/list` entry and the recorded calls give the same answers, apart from the differences above. ## Port errors, logs and progress FastMCP's README shows a `download` tool three times: to log, to fail with a `UserError`, and to report progress. In one tool, as it ran with `fastmcp` 4.23.4: ```ts download.ts import { UserError } from "fastmcp"; import { z } from "zod"; import { server } from "./server.js"; server.addTool({ name: "download", description: "Download a file", parameters: z.object({ url: z.string(), }), execute: async (args, { log, reportProgress }) => { log.info("Downloading file...", { url: args.url }); await reportProgress({ progress: 0, total: 100 }); if (args.url.startsWith("https://example.com")) { throw new UserError("This URL is not allowed"); } await reportProgress({ progress: 100, total: 100 }); return "done"; }, }); ``` The helpers FastMCP passes in the second argument are methods of `this` in FrontMCP. The Call tab streams the log message and the progress above the result. Initial call configuration: ```js { tool: "download", arguments: { url: "https://files.example.org/report.pdf" } } ``` ```ts download.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const downloadParameters = z.object({ url: z.string() }); @Tool({ name: "download", description: "Download a file", inputSchema: downloadParameters.shape }) export class Download extends ToolContext { async execute({ url }: z.infer) { await this.notify({ message: "Downloading file...", context: { url } }); await this.progress(0, 100); if (url.startsWith("https://example.com")) { this.fail(new PublicMcpError("This URL is not allowed")); } await this.progress(100, 100); return { content: [{ type: "text", text: "done" }] }; } } ``` ```ts download.test.ts import { test, expect } from "@frontmcp/testing"; test("a blocked URL fails with the UserError's message, word for word", async ({ mcp }) => { const result = await mcp.tools.call("download", { url: "https://example.com/report.pdf" }); expect(result).toBeError("PUBLIC_ERROR"); expect(result.raw.content).toEqual([{ type: "text", text: "This URL is not allowed" }]); }); test("the log message carries FastMCP's data", async ({ mcp }) => { await mcp.tools.call("download", { url: "https://files.example.org/report.pdf" }); const logs = mcp.notifications.collect().received.filter((n) => n.method === "notifications/message"); expect(logs.map((n) => n.params)).toEqual([ { level: "info", logger: "download", data: { message: "Downloading file...", context: { url: "https://files.example.org/report.pdf" } } }, ]); }); test("progress goes from 0 to 100", async ({ mcp }) => { await mcp.tools.call("download", { url: "https://files.example.org/report.pdf" }); const updates = mcp.notifications.collectProgress().all; expect(updates.map((update) => [update.progress, update.total])).toEqual([[0, 100], [100, 100]]); }); test("an allowed URL answers done", async ({ mcp }) => { const result = await mcp.tools.call("download", { url: "https://files.example.org/report.pdf" }); expect(result.text()).toBe("done"); }); ``` - **`UserError` becomes `PublicMcpError`.** Its message is the whole text of an `isError` result in both, and FrontMCP adds a code in `_meta.code`. An error that isn't public is different: FastMCP sent `Tool 'download' execution failed:` and the message ([`FastMCP.ts`](https://github.com/punkpeye/fastmcp/blob/v4.23.4/src/FastMCP.ts#L3058-L3067)); FrontMCP sends `Tool "download" execution failed:`, the message and the stack in development, and hides all of it in production ([Failing vs throwing](https://frontmcp.dev/reference/sdk/fail#failing-vs-throwing)). - **`log` becomes `this.notify()`.** FastMCP sent `{ message, context }` as the log message's `data` ([`FastMCP.ts`](https://github.com/punkpeye/fastmcp/blob/v4.23.4/src/FastMCP.ts#L2035-L2058)); `this.notify()` sends the object you pass, so the same object keeps the shape, and FrontMCP adds the tool's name as `logger`. FastMCP's `log.warn` sent the level `"warning"` ([`FastMCP.ts`](https://github.com/punkpeye/fastmcp/blob/v4.23.4/src/FastMCP.ts#L1929-L1931)), which is the name `this.notify()` takes. - **FrontMCP's log messages are opt-in.** FastMCP sent every level until the client set one with `logging/setLevel` ([Logging](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md?plain=1#L1283-L1286)). FrontMCP sends nothing until the client asks: with `logging/setLevel` before 2026-07-28, and with a level in each request's `_meta` under 2026-07-28 ([Asking for log messages](https://frontmcp.dev/reference/sdk/notify#asking-for-log-messages)). The Playground's test client asks for `debug` on every call, which is why the test sees the message. Anything the model needs belongs in the result. - **Progress is the same.** Both send it only for a request with a `progressToken` ([FastMCP](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md?plain=1#L1351), [`this.progress`](https://frontmcp.dev/reference/sdk/progress)). **Before you move on:** the recorded failures have the same text, and the clients that show logs or progress still get them. ## Port resources, templates and prompts FastMCP's README examples for a resource, a resource template and a prompt, as they ran with `fastmcp` 4.23.4 (the log's text is ours): ```ts logs.ts import { server } from "./server.js"; server.addResource({ uri: "file:///logs/app.log", name: "Application Logs", mimeType: "text/plain", async load() { return { text: "Started on port 8080" }; }, }); server.addResourceTemplate({ uriTemplate: "file:///logs/{name}.log", name: "Application Logs", mimeType: "text/plain", arguments: [{ name: "name", description: "Name of the log", required: true }], async load({ name }) { return { text: `Example log content for ${name}` }; }, }); server.addPrompt({ name: "git-commit", description: "Generate a Git commit message", arguments: [{ name: "changes", description: "Git diff or description of changes", required: true }], load: async (args) => { return `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}`; }, }); ``` In FrontMCP each is a class, and `load()`'s body moves into `execute()` as it is. The tests compare the lists and the reads with what FastMCP answered. Initial call configuration: ```js { resource: "file:///logs/server.log" } ``` ```ts logs.resource.ts active import { Resource, ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; @Resource({ uri: "file:///logs/app.log", name: "Application Logs", mimeType: "text/plain" }) export class AppLog extends ResourceContext { async execute() { return { text: "Started on port 8080" }; } } @ResourceTemplate({ uriTemplate: "file:///logs/{name}.log", name: "Application Logs", mimeType: "text/plain" }) export class NamedLog extends ResourceContext<{ name: string }> { async execute(uri: string, { name }: { name: string }) { return { text: `Example log content for ${name}` }; } } ``` ```ts git-commit.prompt.ts import { Prompt, PromptContext } from "@frontmcp/sdk"; @Prompt({ name: "git-commit", description: "Generate a Git commit message", arguments: [{ name: "changes", description: "Git diff or description of changes", required: true }], }) export class GitCommit extends PromptContext { async execute(args: Record) { return `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}`; } } ``` ```ts logs.test.ts import { test, expect } from "@frontmcp/testing"; test("resources/list and resources/templates/list match the recording", async ({ mcp }) => { expect(await mcp.resources.list()).toEqual([{ name: "Application Logs", uri: "file:///logs/app.log", mimeType: "text/plain" }]); expect(await mcp.resources.listTemplates()).toEqual([{ name: "Application Logs", uriTemplate: "file:///logs/{name}.log", mimeType: "text/plain" }]); }); test("both reads give the recorded contents", async ({ mcp }) => { expect((await mcp.resources.read("file:///logs/app.log")).raw.contents).toEqual([ { uri: "file:///logs/app.log", mimeType: "text/plain", text: "Started on port 8080" }, ]); expect((await mcp.resources.read("file:///logs/server.log")).raw.contents).toEqual([ { uri: "file:///logs/server.log", mimeType: "text/plain", text: "Example log content for server" }, ]); }); test("the prompt lists the same argument and gives the same message", async ({ mcp }) => { const gitCommit = (await mcp.prompts.list()).find((prompt) => prompt.name === "git-commit"); expect(gitCommit?.arguments).toEqual([{ name: "changes", description: "Git diff or description of changes", required: true }]); const result = await mcp.prompts.get("git-commit", { changes: "Fix a typo in the README" }); expect(result.messages).toEqual([ { role: "user", content: { type: "text", text: "Generate a concise but descriptive commit message for these changes:\n\nFix a typo in the README" } }, ]); }); ``` A template has no `arguments` list in FrontMCP: its parameters are the placeholders in `uriTemplate`, and `execute()` gets them as its second argument. FastMCP didn't send the list in `resources/templates/list` either. In both, `{name}` matches within one path segment, so `file:///logs/2026/10/app.log` doesn't match this template ([FastMCP](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md?plain=1#L1656), [FrontMCP](https://frontmcp.dev/reference/sdk/resource-template#matching-paths-with-slashes)). The last challenge ports a template that matches across segments. **Before you move on:** the resource and prompt lists, and a read of every URI and template your clients use, match the recording. ## Move state out of the session FastMCP's README keeps per-session state in a `Map` keyed by `context.sessionId`, which comes from the `Mcp-Session-Id` header ([Session ID and Request ID Tracking](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#session-id-and-request-id-tracking)). Ported as it is, it works for clients on 2025-11-25 and earlier over HTTP, which still get a session from FrontMCP. A client on 2026-07-28 has none: `this.context.sessionId` is a new `anon:` id on every request ([`this.context`](https://frontmcp.dev/reference/sdk/context#thiscontextsessionid-is-different-on-every-call)), so the count starts again on every call: Initial call configuration: ```js { tool: "increment_counter", arguments: {} } ``` ```ts counter.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; const sessionCounters = new Map(); // 🚩 Keyed by a session that 2026-07-28 clients don't have @Tool({ name: "increment_counter", description: "Increment a per-session counter", inputSchema: {} }) export class IncrementCounter extends ToolContext { async execute() { const sessionId = this.context.sessionId; const counter = (sessionCounters.get(sessionId) ?? 0) + 1; sessionCounters.set(sessionId, counter); return { content: [{ type: "text", text: `Counter for session ${sessionId}: ${counter}` }] }; } } ``` ```ts counter.test.ts import { test, expect } from "@frontmcp/testing"; test("each call is a new session, so the count never passes 1", async ({ mcp }) => { const first = await mcp.tools.call("increment_counter", {}); const second = await mcp.tools.call("increment_counter", {}); expect(first.text()).toMatch(/^Counter for session anon:.+: 1$/); expect(second.text()).toMatch(/: 1$/); expect(second.text()).not.toBe(first.text()); }); ``` Give the state a handle of its own that the model passes back, as the 2026-07-28 changelog suggests ([MCP Went Stateless](https://frontmcp.dev/blog/mcp-went-stateless#what-it-means-for-a-server)). One tool starts a counter and returns its id; the other takes the id: Initial call configuration: ```js { tool: "start_counter", arguments: {} } ``` ```ts counter.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const counters = new Map(); // ✅ Keyed by an id the model passes to the next call @Tool({ name: "start_counter", description: "Start a counter. Pass its counterId to increment_counter.", inputSchema: {} }) export class StartCounter extends ToolContext { async execute() { const counterId = crypto.randomUUID(); counters.set(counterId, 0); return { counterId }; } } @Tool({ name: "increment_counter", description: "Increment a counter that start_counter returned", inputSchema: { counterId: z.string().describe("The counterId from start_counter") }, }) export class IncrementCounter extends ToolContext { async execute({ counterId }: { counterId: string }) { const counter = counters.get(counterId); if (counter === undefined) this.fail(new PublicMcpError(`There's no counter ${counterId}. Start one with start_counter.`)); counters.set(counterId, counter + 1); return { counterId, counter: counter + 1 }; } } ``` ```ts counter.test.ts import { test, expect } from "@frontmcp/testing"; test("the count goes on across calls, without a session", async ({ mcp }) => { const { counterId } = (await mcp.tools.call("start_counter", {})).json() as { counterId: string }; await mcp.tools.call("increment_counter", { counterId }); const second = await mcp.tools.call("increment_counter", { counterId }); expect(second.json()).toEqual({ counterId, counter: 2 }); }); test("an unknown counterId is refused with a message the model can act on", async ({ mcp }) => { const result = await mcp.tools.call("increment_counter", { counterId: "c-404" }); expect(result).toBeError("PUBLIC_ERROR"); expect(result.text()).toBe("There's no counter c-404. Start one with start_counter."); }); ``` The `Map` lives in one process. With several instances, keep the state where every instance can read it ([Running Several Instances](https://frontmcp.dev/learn/running-several-instances)). State that belongs to a signed-in user can be keyed by `this.auth.user.sub` instead, once an [auth mode](https://frontmcp.dev/learn/migrating-from-fastmcp#choose-auth) identifies users. **Before you move on:** call each tool that keeps state twice, as a 2026-07-28 client, and check that the second call sees the first. ## Choose auth A FrontMCP server is `public` by default: every request gets in. Choose a mode before you move a protected server ([Auth modes](https://frontmcp.dev/reference/auth/modes)). - **An API key.** FastMCP's README checks an `x-api-key` header in `authenticate()` ([Custom Authentication](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#custom-authentication)). FrontMCP's `static` mode checks the same header, without code, with `header: "x-api-key"` and `scheme: ""` ([Static keys in a header of your own](https://frontmcp.dev/reference/auth/tokens#static-keys-in-a-header-of-your-own)). What tools see changes: FastMCP passed whatever `authenticate()` returned as `session`; in `static` mode, `this.auth.user.sub` is `static:` and 12 hex characters for each key, and every key gets the mode's `scopes` ([What each auth mode fills in](https://frontmcp.dev/reference/sdk/auth#what-each-auth-mode-fills-in)). - **Roles and scopes per user.** Accept JWTs from your identity provider in `transparent` mode ([Tokens](https://frontmcp.dev/reference/auth/tokens#verifying-jwts-from-your-identity-provider)), and replace `canAccess` with `authorities` on the tool ([Authorities](https://frontmcp.dev/reference/auth/authorities#authorities-on-an-entry)). - **Sign-in with a provider.** FastMCP's OAuth proxy has presets for Google, GitHub and Azure. FrontMCP's `remote` mode takes an OpenID Connect provider you configure; GitHub, whose users have no `sub`, [can't be used](https://frontmcp.dev/reference/auth/remote#pointing-frontmcp-at-your-providers-endpoints). `local` mode makes FrontMCP the sign-in page, and you check the user in `authenticate` ([Local auth](https://frontmcp.dev/reference/auth/local#checking-users-yourself)). The Playground's client can't send credentials, so none of this runs on this page; each linked reference page runs its mode. **Before you move on:** against a running server, a request without a key and one with a wrong key are refused, a request with a key gets through, and a tool a caller may not use is refused when called by name, not only left out of `tools/list` ([Hiding versus refusing](https://frontmcp.dev/reference/auth/authorities#hiding-versus-refusing)). ## Serve the same endpoint, then switch clients Clients reach the server at a URL, or start it with a command. Keep the URL, and update the command: - **The HTTP path.** FastMCP serves `/mcp` unless you set `httpStream.endpoint` ([HTTP Streaming](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md?plain=1#L141-L143)). FrontMCP serves the root path unless you set `http.entryPath`, so set `entryPath: "/mcp"` and the same `port` ([`http`](https://frontmcp.dev/reference/sdk/frontmcp#http)). - **SSE.** FastMCP also starts an SSE endpoint at `/sse` ([HTTP Streaming](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md?plain=1#L147)). FrontMCP's Node server serves the older HTTP+SSE transport by default ([`transport`](https://frontmcp.dev/reference/sdk/frontmcp#transport)) at `/sse`. Point an SSE client there and post to the message URL the stream names, including its `sessionId`. The message endpoint accepts any `Accept` value, or none. Changed in 1.10.11: before, `initialize` posts with `*/*` or `application/*` got `404`; see [client troubleshooting](https://frontmcp.dev/reference/deployment/mcp-clients#cannot-post-mcpmessage). Try the client before you switch it. - **stdio.** A client that starts the server as a command needs the new command. FrontMCP connects over stdio when `FRONTMCP_STDIO=1` is set ([Starting the server](https://frontmcp.dev/reference/sdk/frontmcp#starting-the-server), [Over stdio](https://frontmcp.dev/reference/deployment/mcp-clients#over-stdio)). - **Health checks.** FastMCP 4.23.4 answers `/health` with the text `✓ Ok`, although its [Health-check Endpoint](https://github.com/punkpeye/fastmcp/blob/v4.23.4/README.md#health-check-endpoint) section says `ok`. FrontMCP answers `/health` and `/healthz` with JSON ([Health and metrics](https://frontmcp.dev/reference/deployment/health-and-metrics)), so a probe that reads the body needs changing. - **The address it listens on.** FrontMCP listens on `127.0.0.1` by default, which a published container port can't reach; set `FRONTMCP_BIND_ADDRESS=all` there ([Node](https://frontmcp.dev/reference/deployment/node)). - **Readiness.** FastMCP answers `/ready`. FrontMCP answers `/readyz`, and `/ready` is `404` ([Health and metrics](https://frontmcp.dev/reference/deployment/health-and-metrics)). - **Browser clients.** FastMCP answers a browser's preflight to `/mcp` from any origin. FrontMCP sends no CORS headers until you set `http.cors` or `FRONTMCP_CORS_ORIGINS` ([`http`](https://frontmcp.dev/reference/sdk/frontmcp#http), [config files](https://frontmcp.dev/reference/server/config-files)). - **Production mode.** Run FrontMCP with `NODE_ENV=production`. Without it, error results such as `INVALID_INPUT` and `TOOL_NOT_FOUND` carry the stack, with the server's file paths, in `_meta.stack`. Then switch clients the way [Migrating from the TypeScript SDK](https://frontmcp.dev/learn/migrating-from-the-typescript-sdk#verify-the-endpoint-before-switching-clients) describes: keep FastMCP serving while FrontMCP runs in preview, call the exact endpoint as a client that starts with `initialize` and as one on 2026-07-28, move a small group of clients first, and keep the FastMCP deployment until you no longer need to roll back. **Before you move on:** every client reaches the server at its old URL or with its new command, and the recorded calls give the same answers there as in the tests. ## Recap - Record what FastMCP answers first, with `server.connect()` and the SDK's in-memory client, and turn each answer into a `@frontmcp/testing` test. - `addTool`, `addResource`, `addResourceTemplate` and `addPrompt` become `@Tool`, `@Resource`, `@ResourceTemplate` and `@Prompt` classes, listed in an `@App` on a `@FrontMcp` server. - A tool that returned a string returns `{ content: [{ type: "text", text }] }` to keep its text. - `UserError` becomes `PublicMcpError`; `log`, `reportProgress` and `elicit` become `this.notify()`, `this.progress()` and `this.elicit()`. Log messages are opt-in in FrontMCP. - Invalid input is an `INVALID_INPUT` tool result in FrontMCP, not a `-32602` error. - State keyed by the session starts over for 2026-07-28 clients: key it by a handle or the signed-in user. - Choose an auth mode, set `entryPath: "/mcp"`, and keep FastMCP serving until clients have moved. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Keep a tool's text This FastMCP tool returned `` `Hello, ${name}!` `` as a string, and was ported as it was. Clients read the text, so make `greet` send `Hello, Ada!` as the whole text, with no `structuredContent`, as FastMCP did. Initial call configuration: ```js { tool: "greet", arguments: { name: "Ada" } } ``` ```ts greet.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "greet", description: "Greet someone by name", inputSchema: { name: z.string() } }) export class Greet extends ToolContext { async execute({ name }: { name: string }) { return `Hello, ${name}!`; } } ``` **Solution file (alternative to the starter):** ```ts greet.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "greet", description: "Greet someone by name", inputSchema: { name: z.string() } }) export class Greet extends ToolContext { async execute({ name }: { name: string }) { return { content: [{ type: "text", text: `Hello, ${name}!` }] }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts greet.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the text is `Hello, Ada!` and nothing else", async ({ mcp }) => { const result = await mcp.tools.call("greet", { name: "Ada" }); expect(result.raw.content).toEqual([{ type: "text", text: "Hello, Ada!" }]); }); test("there's no `structuredContent`", async ({ mcp }) => { const result = await mcp.tools.call("greet", { name: "Ada" }); expect(result.raw.structuredContent).toBeUndefined(); }); ``` **Hint:** Return the content block FastMCP built from the string. **Solution:** A string is wrapped as `{ "value": … }`; a result with a `content` array is sent as it is, so the text is the greeting and there's no `structuredContent`. ### Challenge: Port a UserError FastMCP had `UserError`, and this port throws a plain `Error` in its place. Make a blocked URL fail with `This URL is not allowed` as the whole text, the way `UserError` did, in development and in production. Initial call configuration: ```js { tool: "download", arguments: { url: "https://example.com/report.pdf" } } ``` ```ts download.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "download", description: "Download a file", inputSchema: { url: z.string() } }) export class Download extends ToolContext { async execute({ url }: { url: string }) { if (url.startsWith("https://example.com")) { throw new Error("This URL is not allowed"); } return { content: [{ type: "text", text: "done" }] }; } } ``` **Solution file (alternative to the starter):** ```ts download.tool.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "download", description: "Download a file", inputSchema: { url: z.string() } }) export class Download extends ToolContext { async execute({ url }: { url: string }) { if (url.startsWith("https://example.com")) { this.fail(new PublicMcpError("This URL is not allowed")); } return { content: [{ type: "text", text: "done" }] }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts download.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("a blocked URL fails with `This URL is not allowed` as the whole text", async ({ mcp }) => { const result = await mcp.tools.call("download", { url: "https://example.com/report.pdf" }); expect(result).toBeError(); expect(result.raw.content).toEqual([{ type: "text", text: "This URL is not allowed" }]); }); test("the error is public, so production keeps its message", async ({ mcp }) => { const result = await mcp.tools.call("download", { url: "https://example.com/report.pdf" }); expect(result).toBeError("PUBLIC_ERROR"); }); test("another URL still answers `done`", async ({ mcp }) => { const result = await mcp.tools.call("download", { url: "https://files.example.org/report.pdf" }); expect(result.text()).toBe("done"); }); ``` **Hint:** FrontMCP's public error class is exported from `@frontmcp/sdk`. **Solution:** A plain `Error` is a server failure: in development its text starts with `Tool "download" execution failed:` and includes the stack, and production hides it. `PublicMcpError` is meant for the model, so its message is the whole text everywhere, with `PUBLIC_ERROR` in `_meta.code`. ### Challenge: Read logs in subfolders The logs moved into dated folders, like `file:///logs/2026/10/app.log`, and the template should read them with `name` as `2026/10/app`. FastMCP's README uses `{+name}` for a value that spans segments; do the same here, without breaking `file:///logs/server.log`. Initial call configuration: ```js { resource: "file:///logs/server.log" } ``` ```ts logs.resource.ts import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; @ResourceTemplate({ uriTemplate: "file:///logs/{name}.log", name: "Application Logs", mimeType: "text/plain" }) export class NamedLog extends ResourceContext<{ name: string }> { async execute(uri: string, { name }: { name: string }) { return { text: `Example log content for ${name}` }; } } ``` **Solution file (alternative to the starter):** ```ts logs.resource.ts solution import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; @ResourceTemplate({ uriTemplate: "file:///logs/{+name}.log", name: "Application Logs", mimeType: "text/plain" }) export class NamedLog extends ResourceContext<{ name: string }> { async execute(uri: string, { name }: { name: string }) { return { text: `Example log content for ${name}` }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts logs.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`file:///logs/2026/10/app.log` reads the log named `2026/10/app`", async ({ mcp }) => { const result = await mcp.resources.read("file:///logs/2026/10/app.log"); expect(result.text()).toBe("Example log content for 2026/10/app"); }); test("`file:///logs/server.log` still reads the log named `server`", async ({ mcp }) => { const result = await mcp.resources.read("file:///logs/server.log"); expect(result.text()).toBe("Example log content for server"); }); ``` **Hint:** Only the placeholder in `uriTemplate` changes. **Solution:** `{name}` stops at the first `/`, in FrontMCP as in FastMCP. `{+name}` takes the rest of the path up to `.log`, slashes included. --- # Evaluating CodeCall > Compare the same CRM task through direct tool calls and CodeCall. Measure bytes and calls, separate discovery overhead, and record model evaluation independently. Source: https://frontmcp.dev/learn/evaluating-codecall [Covers FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) as of November 14, 2026 Measure the workload you need to support before you add FrontMCP's CodeCall plugin to a server. This evaluation uses the published 47-tool CRM and its synthetic data. It runs the same scripted, read-only task two ways: through direct tool calls, and through one server-side script. It checks that both paths return the same answer. It does not measure model tokens, hosted latency, cost, or whether a model can write the script. **You will learn** - How to run the fixture that compares direct calls with CodeCall - What each output field measures, and what it can't tell you - What the recorded run on 2026-10-22 found - What a model evaluation needs on top of this fixture ## Run the fixture [Download the evaluation project](https://frontmcp.dev/downloads/crm-evaluation.tgz), extract it, and follow its README. It pins the dependencies and the fixture. With Node.js 24 or later, in the extracted folder, run: ```bash npm ci npm run evaluate -- --runs=5 ``` For the direct baseline, the harness removes only the plugin's registration. Both servers use the same tool implementations. A scripted client stands in for the model: it makes the same tool choices a model would have to make. A small-catalog control makes a single direct lookup, because not every task gains from running a script. ## Read the output | Field | What it measures | What it cannot establish | | --- | --- | --- | | catalog bytes | UTF-8 bytes of JSON tool definitions | Model tokenizer counts or billing | | direct response bytes | Sum of result envelopes from the underlying calls | Which content a particular client includes in its prompt | | discovery response bytes | Search and schema response envelopes | Free or zero-overhead discovery | | CodeCall response bytes | The execution result envelope | Total context use without discovery and request sizes | | direct calls / execution calls | Requests made by the scripted fixture | Number of model reasoning steps | | directMs / scriptMs | In-process time after server startup | Cold deployment or hosted-model latency | Runs happen one after another, after the servers start. The first call and later calls can differ because of cache state. So the output keeps every run, rather than one number that hides the spread. Compare the runs before you combine them. A failed assertion makes the harness exit with an error. Don't leave wrong results out of an evaluation. ## Recorded results The [JSON record](https://frontmcp.dev/evidence/codecall.json) holds one capture of five runs. The tables below report it as written. Times are rounded to 0.01 ms; the JSON keeps full precision. | Recorded | Value | | --- | --- | | Observed on | 2026-10-22 | | `@frontmcp/sdk` | 1.10.10 | | `@frontmcp/plugin-codecall` | 1.10.10 | | Node.js | v24.18.1 | | Platform | `darwin`, `arm64` | | Workload | 47-tool CRM; identical scripted read-only task; catalog and parsed result JSON UTF-8 bytes | | Runs | 5 | | Failures | None recorded. The harness writes no record if any assertion fails. | The record's `sourceHash` is the SHA-256 of `scripts/evaluate-codecall.mjs` when it was captured. Compare it with the script you run to see whether the harness has changed since. | Catalog from `tools/list` | Tools | Bytes | | --- | --- | --- | | Direct, without the plugin | 47 | 43,251 | | With CodeCall | 6 | 15,999 | Every run made the same calls and returned the same number of bytes: | Step, in each of the 5 runs | Calls | Response bytes | | --- | --- | --- | | Direct tool calls | 8 | 4,194 | | CodeCall discovery: `codecall:search` and `codecall:describe` | 2 | 16,467 | | CodeCall execution: `codecall:execute` | 1 | 522 | | Small-catalog control: one direct `get_agent` call | 1 | Not recorded | Times, in milliseconds. `directMs` times the scripted task through its eight direct calls. `scriptMs` times only the `codecall:execute` call, without discovery. | Run | `directMs` | `scriptMs` | | --- | --- | --- | | 1 | 9.20 | 21.22 | | 2 | 3.75 | 6.69 | | 3 | 3.11 | 6.24 | | 4 | 2.67 | 5.50 | | 5 | 3.02 | 5.43 | What the record shows: - Both paths returned the same answer in every run. - The CodeCall catalog was 15,999 bytes for 6 tools. Without the plugin, it was 43,251 bytes for 47 tools. - CodeCall's two discovery calls returned 16,467 bytes. That is more than the 4,194 bytes of all eight direct responses. The execution result was 522 bytes. - `scriptMs` was higher than `directMs` in every run. Run 1 was the slowest on both paths. > **Note: Limits of this record** > > The runs were sequential and in-process, after server startup. A first execution may include lazy initialization. The record measures no model, tokens, cost, hosted network or answer quality. It counts discovery separately from execution. The same script stands in for a model making direct calls. Bytes are UTF-8 bytes of JSON, not tokens. ## Add a model evaluation deliberately Record the exact prompt, the model and its version, the settings, the catalog, how the client behaves, the execution limits and a fixed set of tasks. Include simple lookups, joins, ambiguous requests and refused operations. Measure real input and output tokens, tool requests, whether the answers are correct, and wall time. Repeat the runs cold and warm. Keep any API price math dated, and separate from those measurements. Publish failures and limits next to the results. Don't turn a fixture's byte reduction into a percentage token saving, a security certification or a universal speedup. Tool authorization still applies on both paths. Read [CodeCall's limits](https://frontmcp.dev/reference/plugins/codecall) before you turn on scripts. ## Next step Look through [the complete CRM](https://frontmcp.dev/examples/crm-with-codecall). Then replace its synthetic data with a read-only workload of your own. If direct calls already give a small answer, keep that simpler path. --- # Upgrading a server > Identify an installed FrontMCP version, read matching changes, compare a pinned fixture before and after upgrade, and keep a rollback path. Source: https://frontmcp.dev/learn/upgrading-a-server [Covers FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) as of November 14, 2026 Upgrade the FrontMCP packages together, then compare the client contract you depend on. The SDK release, the MCP protocol revision and the client version are three separate values. Documentation hashes show which pages changed. ## Identify the installed release Read the resolved SDK package in your project, or use the docs server's `resolve_version`. In a monorepo with several installations, pass the npm/pnpm workspace path or an exact `installedVersion`. When a lockfile is ambiguous, the resolver returns an error. It doesn't pick the first package record. A manifest range lists the versions allowed, not the one installed. ```json { "workspace": "packages/api", "packageJson": "", "lockfile": "" } ``` Keep lockfiles local, unless you choose to share the parts that matter. The resolver needs no credentials, and not your whole repository. ## Read the changes and establish a baseline Pin a docs endpoint to the installed version. Call `whats_changed` with the old and the target release. Then read the reference pages for the APIs that changed. Check companion plugins and adapters too. Before you change dependencies, run your existing contract, access and deployment checks. Save their output with secrets and private data removed, along with the versions and the date. How often releases ship doesn't tell you whether an API changed. So for each change that affects your server, record four things: the old behavior, the new behavior, whether application or client code must change, and the migration check that covers it. Keep additions, fixes and intended breaking changes apart. The [production evaluation](https://frontmcp.dev/compare/production-readiness#assess-maintenance-and-adoption) explains what release and adoption signals can and can't tell you. ## Reproduce a bounded upgrade The repository's upgrade check uses the reporting download as its fixture. It installs FrontMCP 1.9.2, runs the fixture's tests and captures its tool contracts. Then it installs the documented release and runs the same checks again. It keeps the output from before and after, and reports any differences. ```bash node scripts/check-upgrade.mjs ``` The check installs dependencies in a temporary project. It needs network access to npm, and Node.js 24 or later. Its README and script are in the [evaluation download](https://frontmcp.dev/downloads/crm-evaluation.tgz). ## Inspect the recorded contract The [before/after record](https://frontmcp.dev/evidence/upgrade.json) names both releases. It lists the actual schemas, a successful result and an expected refusal. It also records whether the selected contract changed. The same fixture code is installed separately with each set of dependencies. > **Note: What these checks don't cover** > > - Documentation hashes don't test your server's behavior. > - The upgrade check covers one fixture, and its record is one local observation. It reports differences. It doesn't show that every application is safe to upgrade, and it isn't a support guarantee. > - It doesn't deploy or change your application, and it doesn't test a production database migration. > - A passing documentation test doesn't replace your application's own checks. ## Upgrade and roll back deliberately Update the SDK, CLI, testing and companion packages to releases that work together. Regenerate the lockfile, run the contract and auth checks, and build for your target. In preview, try real client connections and widget behavior. Keep the previous build artifact, configuration and lockfile at hand. Database migrations need their own plan to roll back or recover forward. If you change a contract on purpose, record the result before and after, and update the affected clients yourself. See [Versions](https://frontmcp.dev/versions) and [release notes](https://frontmcp.dev/releases). --- # Describing Capabilities > How to describe what your MCP server can do, so AI models use it well. Tools, schemas, results, resources, prompts and apps. Source: https://frontmcp.dev/learn/describing-capabilities [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 An MCP server is only as useful as a model's understanding of it. Models can't read your code; they read the names, descriptions and schemas you give them. This chapter is about describing a FrontMCP server's capabilities so that models call the right one, with the right arguments, and understand the answer. **In this chapter** - [How to write a tool a model can use](https://frontmcp.dev/learn/your-first-tool) - [How schemas act as the contract between the model and your code](https://frontmcp.dev/learn/schemas-are-contracts) - [How to shape tool results so clients can use them](https://frontmcp.dev/learn/shaping-tool-results) - [How to expose data with resources](https://frontmcp.dev/learn/exposing-data-with-resources) - [How to write prompts users can reuse](https://frontmcp.dev/learn/reusable-prompts) - [How to group capabilities into apps](https://frontmcp.dev/learn/grouping-capabilities-into-apps) - [How to write descriptions agents understand](https://frontmcp.dev/learn/writing-descriptions-agents-understand) ## Your first tool A tool is a function the model can choose to call. Its name, description and input schema are all the model knows about it, so a tool with a vague name and no description is nearly invisible, however good the code is. ### [Your First Tool](https://frontmcp.dev/learn/your-first-tool) Learn the four parts of a `@Tool`, what FrontMCP checks before your code runs, and how to return errors the model can act on. ## Schemas are contracts Every argument you declare with Zod becomes part of the JSON Schema the model reads, and every call is checked against it before `execute()` runs. Constraints belong in the schema, not in `if` statements, because the model can see a schema and can't see your code. Initial call configuration: ```js { tool: "schedule_callback", arguments: { phone: "+971 4 555 0100", when: "tomorrow_morning" } } ``` ```ts schedule.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "schedule_callback", description: "Schedule a phone call back to a customer", inputSchema: { phone: z.string().min(7).describe("Phone number with country code"), when: z.enum(["today", "tomorrow_morning", "tomorrow_afternoon"]), note: z.string().max(200).optional(), }, }) export class ScheduleCallback extends ToolContext { async execute(input: { phone: string; when: "today" | "tomorrow_morning" | "tomorrow_afternoon"; note?: string }) { return { scheduled: true, ...input }; } } ``` ### [Schemas Are Contracts](https://frontmcp.dev/learn/schemas-are-contracts) Learn what the model reads from a Zod schema, why rules belong in the schema instead of `if` statements, and how optional fields and defaults appear in `tools/list`. ## Shaping tool results A tool can return plain values or objects. Declaring `outputSchema` tells clients the shape of the result before they call, and the result arrives as `structuredContent` that programs can use directly. The [Quick Start](https://frontmcp.dev/learn#returning-structured-results) shows an example. ### [Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results) Learn what `content` and `structuredContent` carry, when to declare `outputSchema`, how to return only what the model needs, and how to fail in a way the model can act on. ## Exposing data with resources Not everything should be a tool. Data that an application attaches to a conversation, like a document, a record or a policy, is a **resource**: addressed by a URI and read with `resources/read`. `@ResourceTemplate` covers a family of URIs such as `ticket://{id}`. Initial call configuration: ```js { resource: "docs://refund-policy" } ``` ```ts policy.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "refund-policy", uri: "docs://refund-policy", mimeType: "text/markdown", description: "When customers can get a refund", }) export class RefundPolicy extends ResourceContext { async execute(uri: string) { return { contents: [{ uri, mimeType: "text/markdown", text: "# Refunds\n\nFull refund within 30 days of purchase." }], }; } } ``` ### [Exposing Data with Resources](https://frontmcp.dev/learn/exposing-data-with-resources) Learn when data should be a resource instead of a tool, how fixed resources and URI templates work, and what clients see in `resources/list` and `resources/read`. ## Reusable prompts A **prompt** is a message template that a user picks, often from a slash menu in their client, with arguments they fill in. Prompts are how you package the instructions that work best with your tools. ### [Reusable Prompts](https://frontmcp.dev/learn/reusable-prompts) Learn how to declare a prompt and its arguments, return several messages, and bring ticket data into the conversation. ## Grouping capabilities into apps An `@App` bundles related tools, resources, prompts and providers, and a `@FrontMcp` server can host several apps on one endpoint. The [Quick Start](https://frontmcp.dev/learn#grouping-capabilities-into-an-app-and-a-server) shows the three files involved. ### [Grouping Capabilities into Apps](https://frontmcp.dev/learn/grouping-capabilities-into-apps) Learn how apps group capabilities, how a server composes several apps, what happens when two apps use the same name, and how apps share a provider. ## Writing descriptions agents understand Descriptions are prompts. They decide whether a model picks your tool, which of two similar tools it picks, and how it fills in arguments. ### [Writing Descriptions Agents Understand](https://frontmcp.dev/learn/writing-descriptions-agents-understand) Learn what to put in a tool's description and its arguments' descriptions, how to say when *not* to use a tool, and how to test descriptions in `tools/list`. ## What's next? Start the chapter with [Your First Tool](https://frontmcp.dev/learn/your-first-tool). After it, [Talking to Clients](https://frontmcp.dev/learn/talking-to-clients) covers what happens during a call: asking the user for input and reporting progress. --- # Your First Tool > Build a typed MCP tool with FrontMCP, validate input with Zod and return results and errors a client can use. Source: https://frontmcp.dev/learn/your-first-tool [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A **tool** is a function an AI model can choose to call. The model never sees your code. It sees the tool's name, its description and its input schema, and decides from those alone whether to call it and with what. In FrontMCP they're three fields of `@Tool`, and most of writing a good tool is writing them well. **You will learn** - What a tool is, and who decides to call it - The four parts of a `@Tool` - What FrontMCP does between `tools/call` and your `execute()` - How to return results, and errors the model can act on ## A tool the model can't use This tool works. Given a ticket id, it returns the ticket. But open the **Capabilities** tab and look at it the way a model does: ```ts lookup.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "lookup", inputSchema: { q: z.string() } }) export class Lookup extends ToolContext { async execute({ q }: { q: string }) { return tickets.find((t) => t.id === q) ?? "not found"; } } ``` A user asks, "What's the status of ticket T-2?" All the model has to go on is: 1. **A name that doesn't say what it looks up.** Tickets? Users? Orders? 2. **No description.** Nothing says what the tool returns or when to use it. 3. **An input called `q`.** Nothing says it expects an id like `T-2`, rather than a title or a search phrase. The model might skip the tool, or call it with `"ticket T-2"` and get `"not found"`. The code isn't the problem. The description of it is. ## Declaring a tool Here is the same tool, written for the model: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-2" } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id. Returns the ticket's title and status.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"), }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return tickets.find((t) => t.id === id) ?? "not found"; } } ``` Every tool has four parts: 1. **`name`** is what the model calls. Use a verb and a noun in `snake_case`, like `get_ticket`, and keep it unique within your server. 2. **`description`** tells the model what the tool does, what it returns, and when to use it. Write it for a reader who has never seen your code, because that's exactly who reads it. 3. **`inputSchema`** declares each argument with Zod. Constraints like `.regex()` become part of the schema the model sees, and `.describe()` adds a note to the field. 4. **The class** extends `ToolContext` and implements `execute()`. It receives the validated arguments, and `ToolContext` gives it helpers like `this.get()` for [providers](https://frontmcp.dev/learn#sharing-a-service-with-a-provider). > **Note** > > `@Tool` also checks your types when TypeScript compiles. Type `execute()`'s parameter as `{ id: number }` against `z.string()`, or leave out `extends ToolContext`, and the decorator line gets an error that starts `Unable to resolve signature of class decorator`. The rest of the message names the problem, like `Parameter type does not match the input schema.` The Playground runs your code without type-checking, so you'll see these errors in your editor, not here. > **Note** > > For small tools that don't need providers or other context, FrontMCP also has a function form: `tool({ name, description, inputSchema })(async (input) => ...)`. This course uses classes, because most real tools grow into needing context. ## What happens when a tool is called When the model decides to use your tool, FrontMCP stands between the call and your code: *[Illustration: Seven steps across three lanes. The client sends tools/call with the tool's name and the model's arguments. FrontMCP finds the tool by name, then checks the arguments against inputSchema and drops unknown fields; if they don't match, the client gets an isError result, INVALID_INPUT, listing each problem, and execute never runs. Your code's execute runs with the validated arguments. FrontMCP checks the result against outputSchema if the tool has one; a mismatch returns INVALID_OUTPUT. FrontMCP wraps the result as structuredContent plus a text block, and the client hands it to the model.]* The important step is the third one: **if the arguments don't match `inputSchema`, `execute()` never runs.** This call sent `"ticket two"` as the id, which doesn't match the pattern: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "ticket two" } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id. Returns the ticket's title and status.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"), }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return tickets.find((t) => t.id === id) ?? "not found"; } } ``` The error comes back as a normal result, not a protocol failure, so the model can read it and try again with `T-2`. Change the id in the form and call it yourself. ### What does the model actually receive? FrontMCP converts your Zod schema to JSON Schema for `tools/list`. Open the Wire tab above and expand `tools/list` to see it. For `get_ticket` it's: ```json { "name": "get_ticket", "description": "Get one support ticket by its id. Returns the ticket's title and status.", "inputSchema": { "type": "object", "properties": { "id": { "type": "string", "pattern": "^T-\\d+$", "description": "Ticket id, like T-1" } }, "required": ["id"] } } ``` (The real response also carries a `$schema` field.) That JSON is the whole contract. If a client sends fields that aren't in it, FrontMCP drops them before `execute()` runs, so your code only ever sees the fields you declared. ## Returning results and errors Whatever `execute()` returns becomes the result. Objects arrive as `structuredContent`. Plain values, like strings and numbers, are wrapped as `{ "value": ... }`. FrontMCP also sends the same data as text, for clients that only read text. Returning `"not found"` works, but the model can't tell it apart from a real answer. When a call can't succeed, fail with a message the model should read: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-9" } } ``` ```ts get-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id. Returns the ticket's title and status.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"), }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}. Search by title with search_tickets.`)); return ticket; } } ``` `this.fail()` stops `execute()` and sends the error as a result with `isError: true`. `PublicMcpError` marks the message as safe to show, so it reaches the model word for word. > **Pitfall: Raw errors are hidden in production** > > If `execute()` throws a plain `Error`, what the client sees depends on the environment. In development, FrontMCP includes the message and stack trace to help you debug, which is what the Playground shows. In production (`NODE_ENV=production`) it replaces them with "Internal FrontMCP error. Please contact support with error ID: …", so database errors and secrets don't leak to the model. Use `PublicMcpError` for anything the model should read. ## Recap - A tool is a function the model can choose to call. The model sees only its name, description and input schema. - A `@Tool` has a `name`, a `description`, an `inputSchema`, and a class that extends `ToolContext` with an `execute()` method. - FrontMCP validates arguments before `execute()` runs. Invalid calls come back as `isError` results that list what was wrong. - Return objects or plain values; they arrive as `structuredContent`. - Use `this.fail(new PublicMcpError(...))` for errors the model should read. Raw errors are hidden in production. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. The checks are ordinary `@frontmcp/testing` tests, run against a fresh copy of your server. ### Challenge: Rename a vague tool This tool searches tickets, but its name and input don't say so. Rename it to `search_tickets`, add a description, and rename `x` to `query` with a `.describe()` note. Check the Capabilities tab when you're done. ```ts search.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; @Tool({ name: "find", inputSchema: { x: z.string() } }) export class Find extends ToolContext { async execute({ x }: { x: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(x.toLowerCase())) }; } } ``` **Solution file (alternative to the starter):** ```ts search.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns matching tickets with their status.", inputSchema: { query: z.string().describe("Words to look for in ticket titles") }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts search.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the tool is called search_tickets", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("search_tickets"); }); test("it has a description", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "search_tickets"); expect(tool?.description?.length ?? 0).toBeGreaterThan(20); }); test("its input is a described `query`", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "search_tickets"); expect(tool?.inputSchema.required).toEqual(["query"]); expect(tool?.inputSchema.properties?.query).toHaveProperty("description"); }); test("searching for \"log\" finds both login tickets", async ({ mcp }) => { const result = await mcp.tools.call("search_tickets", { query: "log" }); expect(result).toBeSuccessful(); expect(result.json().tickets.map((t: { id: string }) => t.id)).toEqual(["T-1", "T-3"]); }); ``` **Hint:** Remember to rename the field in both places: `inputSchema` and the `execute()` parameter. **Solution:** The name says what it does, the description says what comes back, and `query` explains itself in the schema the model reads. The Playground above now shows the solution; press **Check** to see it pass. ### Challenge: Add an optional filter Let the model narrow results to open or closed tickets. Add a `status` argument that can be `"open"` or `"closed"`, and leave it optional so the model can omit it. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts search.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "closed" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string() }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } ``` **Solution file (alternative to the starter):** ```ts search.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "closed" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Optionally only open or only closed tickets.", inputSchema: { query: z.string(), status: z.enum(["open", "closed"]).optional().describe("Leave out to include both"), }, }) export class SearchTickets extends ToolContext { async execute({ query, status }: { query: string; status?: "open" | "closed" }) { const q = query.toLowerCase(); return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(q) && (!status || t.status === status)) }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts search.test.ts hidden import { test, expect } from "@frontmcp/testing"; const ids = (result: { json(): any }) => result.json().tickets.map((t: { id: string }) => t.id); test("`status` is in the schema, as \"open\" or \"closed\"", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "search_tickets"); expect(tool?.inputSchema.properties?.status?.enum).toEqual(["open", "closed"]); }); test("`status` is optional", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "search_tickets"); expect(tool?.inputSchema.required ?? []).not.toContain("status"); expect(ids(await mcp.tools.call("search_tickets", { query: "log" }))).toEqual(["T-1", "T-3"]); }); test("status \"open\" leaves out closed tickets", async ({ mcp }) => { expect(ids(await mcp.tools.call("search_tickets", { query: "log", status: "open" }))).toEqual(["T-1"]); }); test("status \"closed\" leaves out open tickets", async ({ mcp }) => { expect(ids(await mcp.tools.call("search_tickets", { query: "log", status: "closed" }))).toEqual(["T-3"]); }); ``` **Hint:** `z.enum(["open", "closed"]).optional()` makes a field the model may leave out. Its type in `execute()` is `"open" | "closed" | undefined`. **Solution:** `z.enum()` puts the allowed values in the JSON Schema, so the model knows exactly what it may send, and `.optional()` keeps `status` out of `required`. In `execute()`, a missing `status` means "don't filter". ### Challenge: Reject queries that are too short A one-letter query matches almost everything. Make FrontMCP reject any `query` shorter than 3 characters, without adding a check inside `execute()`. Then call the tool with `"a"` to see the error. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "a" } } ``` ```ts search.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string() }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } ``` **Solution file (alternative to the starter):** ```ts search.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string().min(3).describe("At least 3 characters") }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts search.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("a 1-letter query is rejected", async ({ mcp }) => { const result = await mcp.tools.call("search_tickets", { query: "a" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); test("the rule is in the schema the model reads", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "search_tickets"); expect(tool?.inputSchema.properties?.query?.minLength).toBe(3); }); test("a 3-letter query still works", async ({ mcp }) => { const result = await mcp.tools.call("search_tickets", { query: "log" }); expect(result).toBeSuccessful(); expect(result.json().tickets).toHaveLength(1); }); ``` **Solution:** Put the rule in the schema with `.min(3)`. FrontMCP rejects the call with `INVALID_INPUT` before `execute()` runs, and because the rule is in `tools/list` as `minLength`, a model can follow it before it ever calls the tool. A check inside `execute()` would only tell it afterwards. ### Challenge: Tell clients the tool is read-only Searching never changes anything. Add the annotation that tells clients so, and find where it shows up in the Capabilities tab. ```ts search.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string().min(3) }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [] as { id: string; title: string }[], query }; } } ``` **Solution file (alternative to the starter):** ```ts search.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string().min(3) }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [] as { id: string; title: string }[], query }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts search.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("tools/list marks search_tickets read-only", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "search_tickets"); expect(tool?.annotations).toMatchObject({ readOnlyHint: true }); }); test("it doesn't claim to be destructive", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "search_tickets"); expect(tool?.annotations?.destructiveHint).not.toBe(true); }); ``` **Hint:** Annotations go in `@Tool({ annotations: { ... } })`. MCP defines `readOnlyHint`, `destructiveHint`, `idempotentHint` and `openWorldHint`. **Solution:** `annotations: { readOnlyHint: true }` goes out with the tool in `tools/list`, and the card now shows a **read-only** chip. Hints are hints: clients may use them to decide how carefully to confirm a call, but they don't enforce anything. --- # Schemas Are Contracts > How a tool's Zod input schema becomes the JSON Schema a model reads, what FrontMCP checks before execute() runs, and how to write schemas models fill in correctly. Source: https://frontmcp.dev/learn/schemas-are-contracts [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A tool's `inputSchema` is a contract. The model promises to send arguments that match it, FrontMCP checks that promise before your code runs, and `execute()` gets exactly the fields you declared. The model can only keep promises it can see, so every rule and every hint about what a field means belongs in the schema, where the model reads it, not in your code, where it can't. **You will learn** - How a Zod schema becomes the JSON Schema a model reads - Why limits belong in the schema instead of in `if` statements - What FrontMCP checks, drops and passes on before `execute()` runs - What the model sees for optional fields and defaults - How to declare nested objects and lists ## What the model reads This tool opens a support ticket, and it works. Open the **Capabilities** tab to see what a model gets to work with: ```ts create-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket for a customer.", inputSchema: { title: z.string(), customer: z.string(), priority: z.string(), }, }) export class CreateTicket extends ToolContext { async execute(input: { title: string; customer: string; priority: string }) { return { id: "T-4", status: "open", ...input }; } } ``` A user writes: "Dana from Acme can't log in, and it's urgent." The model has to fill in three strings. Is `customer` a name (`"Dana"`), a company (`"Acme"`), or an email address? Is `priority` `"urgent"`, `"high"` or `"P1"`? Nothing says, so the model guesses, and your code stores whatever it guessed. `.describe()` attaches a note to a field. Say what the value is, in what format, with an example: Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Cannot log in", customer: "dana@acme.com", priority: "high" } } ``` ```ts create-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket for a customer.", inputSchema: { title: z.string().describe("One-line summary of the problem"), customer: z.string().describe("The customer's email address, like dana@acme.com"), priority: z.string().describe("low, normal or high. Use high only when the customer can't work at all."), }, }) export class CreateTicket extends ToolContext { async execute(input: { title: string; customer: string; priority: string }) { return { id: "T-4", status: "open", ...input }; } } ``` FrontMCP converts `inputSchema` to [JSON Schema](https://json-schema.org) and sends it in `tools/list`. Open the **Wire** tab and expand `tools/list` to see it. This is the part the model reads: ```json { "name": "create_ticket", "description": "Open a new support ticket for a customer.", "inputSchema": { "type": "object", "properties": { "title": { "type": "string", "description": "One-line summary of the problem" }, "customer": { "type": "string", "description": "The customer's email address, like dana@acme.com" }, "priority": { "type": "string", "description": "low, normal or high. Use high only when ..." } }, "required": ["title", "customer", "priority"] } } ``` That JSON is the whole contract. The model never sees your Zod code, your types or your `execute()`. Every field is in `required` because none of them is marked optional. A good `.describe()` note says what the name can't: the format (`an email address`), an example (`like dana@acme.com`), the unit, or where the value comes from. Don't repeat the name back: `title: "The title"` tells the model nothing it didn't already know. ### Why import z from @frontmcp/sdk and not from zod? The `z` in `@frontmcp/sdk` is Zod 4 with one difference you rarely notice: `z.object()`, `z.union()` and the other factories for compound schemas put off building the schema until it's first used. A server with many tools starts without building their input schemas; FrontMCP builds them when a client first lists the tools or calls one. Everything else works as in Zod: `.describe()`, `.optional()`, parsing, `instanceof`, `z.infer`. A project made with `frontmcp create` has `zod` 4 installed too, and schemas from `import { z } from "zod"` work in `inputSchema` the same way. Zod 3 schemas don't: the tool is listed with no properties, and every call fails with `INVALID_INPUT`. The one place the difference shows is Zod's own `z.toJSONSchema()`, which throws for a `z` schema with an optional object in it, like `customer: z.object({ email: z.string() }).optional()`. Use `toJSONSchema` from `@frontmcp/sdk` instead, or build that schema with `eagerZ`, which is Zod's own `z`. See [`z`, `eagerZ` and `lazyZ`](https://frontmcp.dev/reference/sdk#z-eagerz-and-lazyz). ## Put rules in the schema, not in `if` statements The `priority` note says "low, normal or high", but nothing enforces it. The obvious fix is a check in `execute()`: Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Help", customer: "dana", priority: "urgent" } } ``` ```ts create-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket for a customer.", inputSchema: { title: z.string().describe("One-line summary of the problem"), customer: z.string().describe("The customer's email address, like dana@acme.com"), priority: z.string().describe("low, normal or high. Use high only when the customer can't work at all."), }, }) export class CreateTicket extends ToolContext { async execute(input: { title: string; customer: string; priority: string }) { if (!["low", "normal", "high"].includes(input.priority)) { this.fail(new PublicMcpError(`priority must be low, normal or high, not "${input.priority}"`)); } if (input.title.length < 5) this.fail(new PublicMcpError("title is too short")); if (!input.customer.includes("@")) this.fail(new PublicMcpError("customer must be an email address")); return { id: "T-4", status: "open", ...input }; } } ``` This call has three problems, and the model hears about one of them. It will fix `priority`, call again, find out about `title`, call a third time, and find out about `customer`. The Capabilities tab still says `priority: string`, so the next conversation starts from the same guess. Here are the same rules as Zod constraints: Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Help", customer: "dana", priority: "urgent" } } ``` ```ts create-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket for a customer.", inputSchema: { title: z.string().min(5).max(120).describe("One-line summary of the problem"), customer: z.string().email().describe("The customer's email address, like dana@acme.com"), priority: z.enum(["low", "normal", "high"]).describe("Use high only when the customer can't work at all."), }, }) export class CreateTicket extends ToolContext { async execute(input: { title: string; customer: string; priority: "low" | "normal" | "high" }) { return { id: "T-4", status: "open", ...input }; } } ``` Three things changed: 1. **The model sees the rules before it calls.** The Capabilities card now shows `"low" | "normal" | "high"` instead of `string`, and `tools/list` carries `minLength`, `maxLength`, `format` and `enum`, so a model can get the arguments right the first time. 2. **All the problems come back at once.** FrontMCP checks every field and returns one `INVALID_INPUT` error that lists each problem with its `path`, so a model can fix everything in one retry. 3. **`execute()` got simpler.** The checks are gone, and `priority` has the narrow type `"low" | "normal" | "high"`. The `priority` note changed too: `z.enum()` already lists the values, so the note only says when to pick `high`. Here is what each common Zod constraint becomes in the JSON Schema the model reads: | Zod | JSON Schema in `tools/list` | | --- | --- | | `z.string().min(5).max(120)` | `"minLength": 5, "maxLength": 120` | | `z.string().regex(/^T-\d+$/)` | `"pattern": "^T-\\d+$"` | | `z.string().email()` | `"format": "email"`, plus a `pattern` | | `z.enum(["low", "normal", "high"])` | `"enum": ["low", "normal", "high"]` | | `z.number().int().min(1).max(50)` | `"type": "integer", "minimum": 1, "maximum": 50` | | `z.array(z.string()).min(1).max(10)` | `"type": "array", "minItems": 1, "maxItems": 10` | | `.describe("...")` | `"description": "..."` | | `.optional()` | the field is left out of `required` | `z.enum()` is worth reaching for whenever a field has a fixed set of values. A model picks from a list far more reliably than it guesses a spelling. ## What reaches `execute()` FrontMCP runs every `tools/call` through your schema before `execute()` runs. If the arguments don't match, `execute()` never runs and the model gets the list of problems you saw above. If they do match, `execute()` gets the parsed result, which is not always exactly what the client sent. This call sends an `assignee` field that isn't in the schema: Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Cannot log in", customer: "dana@acme.com", priority: "high", assignee: "Nour" } } ``` ```ts create-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket for a customer.", inputSchema: { title: z.string().min(5).max(120).describe("One-line summary of the problem"), customer: z.string().email().describe("The customer's email address, like dana@acme.com"), priority: z.enum(["low", "normal", "high"]).describe("Use high only when the customer can't work at all."), }, }) export class CreateTicket extends ToolContext { async execute(input: { title: string; customer: string; priority: "low" | "normal" | "high" }) { // Echo back exactly what execute() received. return { id: "T-4", status: "open", ...input }; } } ``` ```ts create-ticket.test.ts import { test, expect } from "@frontmcp/testing"; const ticket = { title: "Cannot log in", customer: "dana@acme.com", priority: "high" }; test("fields that aren't in the schema are dropped", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { ...ticket, assignee: "Nour" }); expect(result).toBeSuccessful(); expect(result.json()).not.toHaveProperty("assignee"); }); test("every problem is reported in one error", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { title: "Help", customer: "dana", priority: "urgent" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); expect(result.text()).toContain('"title"'); expect(result.text()).toContain('"customer"'); expect(result.text()).toContain('"priority"'); }); test("values aren't converted to the right type", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { ...ticket, priority: ["high"] }); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); ``` The result has no `assignee`: FrontMCP dropped it before `execute()` ran, without an error. The **Tests** tab checks three rules: - **Unknown fields are dropped, not rejected.** Your code only ever sees the fields you declared, so a client can't slip extra data past your schema. - **Every problem is reported at once.** The error text is `Invalid tool input`, then one entry per problem with the field's `path` and a `message`. - **Nothing is converted.** A value of the wrong type is an error, not something FrontMCP tries to fix: `["high"]` is not `"high"`, and `"5"` is not a number. > **Pitfall: A renamed field disappears without an error** > > Because unknown fields are dropped, renaming a field doesn't produce an "unknown field" error for callers that still use the old name. If you rename `customer` to `customer_email`, a client that sends `customer` gets `customer_email` reported as missing, which is a confusing message. If the new field is optional, the value just vanishes. Treat field names like the tool's name: once models and prompts use them, change them carefully. > **Pitfall: Refinements are invisible to the model** > > `.refine()` runs your own function during validation, but JSON Schema has no way to describe a function, so the model never sees the rule: > > Initial call configuration: > > ```js > { tool: "reply_to_ticket", arguments: { id: "T-1", body: "Can you send me your password so I can check?" } } > ``` > > ```ts reply.tool.ts > import { Tool, ToolContext, z } from "@frontmcp/sdk"; > > @Tool({ > name: "reply_to_ticket", > description: "Send a reply to the customer on a ticket.", > inputSchema: { > id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"), > body: z > .string() > .min(1) > .refine((text) => !/password/i.test(text), "Never ask a customer for their password") > .describe("The reply, in plain text"), > }, > }) > export class ReplyToTicket extends ToolContext { > async execute({ id, body }: { id: string; body: string }) { > return { id, sent: true, length: body.length }; > } > } > ``` > > The call fails with your message, but the Capabilities card only says `body: string`. Keep the refinement, and also say the rule in `.describe()` (`"The reply, in plain text. Never ask for a password."`), so the model can follow it before it calls. Your schema can also clean up values on the way in. `.trim()`, `.toLowerCase()` and `.toUpperCase()` change a string while it's parsed, and `.transform()` runs any function you give it. `tools/list` describes what a client should send, and `execute()` gets the value after the clean-up: Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Cannot log in", customer: "Dana@Acme.com" } } ``` ```ts create-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket for a customer.", inputSchema: { title: z.string().min(5).max(120).describe("One-line summary of the problem"), customer: z .string() .email() .transform((email) => email.toLowerCase()) .describe("The customer's email address, like dana@acme.com"), }, }) export class CreateTicket extends ToolContext { async execute(input: { title: string; customer: string }) { return { id: "T-4", status: "open", ...input }; } } ``` ```ts create-ticket.test.ts import { test, expect } from "@frontmcp/testing"; test("the model sees `customer` as an email address", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool.inputSchema.properties?.customer).toMatchObject({ type: "string", format: "email" }); expect(tool.inputSchema.required).toEqual(["title", "customer"]); }); test("execute() gets it in lowercase", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { title: "Cannot log in", customer: "Dana@Acme.com" }); expect(result.json().customer).toBe("dana@acme.com"); }); ``` The model doesn't need to know about the lowercasing, and the schema doesn't tell it: JSON Schema can't describe a function, so a `.transform()` is as invisible as a `.refine()`. Here `.toLowerCase()` would do the same job in fewer characters; keep `.transform()` for clean-ups the built-in methods don't cover. ## Optional fields and defaults Most tools have arguments the model can leave out. Zod gives you two ways to say so. Look at `status` and `limit` in the Capabilities tab and the **Tests** tab: Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts search.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string().min(3).describe("Words to look for in ticket titles"), status: z.enum(["open", "closed"]).optional().describe("Leave out to search both"), limit: z.number().int().min(1).max(50).default(10).describe("The most tickets to return"), }, }) export class SearchTickets extends ToolContext { async execute({ query, status, limit }: { query: string; status?: "open" | "closed"; limit: number }) { const q = query.toLowerCase(); const matches = tickets.filter((t) => t.title.toLowerCase().includes(q) && (!status || t.status === status)); return { tickets: matches.slice(0, limit), total: matches.length }; } } ``` ```ts tickets.ts export const tickets = Array.from({ length: 30 }, (_, i) => ({ id: `T-${i + 1}`, title: i % 2 ? "Login link expired" : "Cannot log in", status: i % 3 ? "open" : "closed", })); ``` ```ts search.test.ts import { test, expect } from "@frontmcp/testing"; async function schema(mcp: any) { const tool = (await mcp.tools.list()).find((t: any) => t.name === "search_tickets"); return tool.inputSchema; } test("`status` is optional", async ({ mcp }) => { expect((await schema(mcp)).required).not.toContain("status"); }); test("`limit` is optional, and the schema shows its default", async ({ mcp }) => { const s = await schema(mcp); expect(s.required).not.toContain("limit"); expect(s.properties.limit.default).toBe(10); }); test("leaving `limit` out: execute() gets 10", async ({ mcp }) => { const result = await mcp.tools.call("search_tickets", { query: "log" }); expect(result).toBeSuccessful(); expect(result.json().tickets).toHaveLength(10); }); test("`limit` must be a number, not a string", async ({ mcp }) => { const result = await mcp.tools.call("search_tickets", { query: "log", limit: "5" }); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); ``` - **`.optional()`** leaves the field out of `required`. When the model leaves it out, `execute()` gets `undefined`, so your code decides what "no value" means. Here it means "search both". - **`.default(10)`** also leaves the field out of `required`, and adds `"default": 10` to it, so the model knows what happens if it says nothing. When the field is missing, FrontMCP fills in 10 before `execute()` runs. The Capabilities card shows **optional** and **default 10**. Use `.default()` when one value is right most of the time, and `.optional()` when leaving a field out means something of its own, like "search both". With a default, `execute()` always gets a value, so type the parameter as `limit: number`, not `limit?: number`. ### Why is limit optional in the schema but not in execute()? A schema can describe a value before it's parsed (what a client may send) or after (what your code receives). `tools/list` uses the "before" view: a client may leave `limit` out, so it isn't required. `execute()` gets the "after" view: by then `limit` always has a value. `@Tool` checks `execute()`'s parameter against the "after" view when TypeScript compiles. `limit?: number` fails that check, because it allows `undefined`, which `execute()` never gets. ## Objects and lists When several values belong together, like a customer's email and name, group them in a `z.object()`. When the model should send several values of one kind, use `z.array()` with rules for the items. An object shows up in the JSON Schema with its own `properties` and `required` list, and a list with an `items` schema, so the model sees the rules at every level: Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Invoice total is wrong", customer: { email: "dana@acme", name: "Dana Levi" }, tags: ["billing", "urgent"] } } ``` ```ts create-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket for a customer.", inputSchema: { title: z.string().min(5).max(120).describe("One-line summary of the problem"), customer: z .object({ email: z.string().email().describe("Like dana@acme.com"), name: z.string().optional().describe("Full name, if the customer gave it"), }) .describe("Who reported the problem"), tags: z .array(z.enum(["billing", "login", "bug", "feature"])) .max(3) .optional() .describe("Up to 3 labels"), }, }) export class CreateTicket extends ToolContext { async execute(input: { title: string; customer: { email: string; name?: string }; tags?: ("billing" | "login" | "bug" | "feature")[]; }) { return { id: "T-4", status: "open", ...input }; } } ``` ```ts create-ticket.test.ts import { test, expect } from "@frontmcp/testing"; test("each problem's path points into the structure", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { title: "Invoice total is wrong", customer: { email: "dana@acme" }, tags: ["billing", "urgent"], }); const problems = JSON.parse(result.text().split("Details: ")[1]); expect(problems.map((p: { path: unknown[] }) => p.path)).toEqual([["customer", "email"], ["tags", 1]]); }); test("unknown fields inside `customer` are dropped", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { title: "Invoice total is wrong", customer: { email: "dana@acme.com", vip: true }, }); expect(result.json().customer).toEqual({ email: "dana@acme.com" }); }); ``` The error lists two problems, and each `path` points into the structure: `["customer", "email"]` for the email, and `["tags", 1]` for the second tag, `"urgent"`, which isn't one of the four labels. Fix both in the form and call again. The rules you've seen apply at every level. Nested fields can have `.describe()` notes, nested objects get their own `required` list, and unknown fields inside `customer` are dropped just like unknown fields at the top. Prefer a list over a string the model has to format. `tags: z.array(...)` says exactly what to send. A `tags: z.string().describe("Comma-separated labels")` leaves the model to guess about spaces, quotes and brackets, and leaves your code to parse whatever it chose. ## Recap - FrontMCP converts `inputSchema` to JSON Schema in `tools/list`. That JSON is all the model knows about a tool's arguments. - Use `.describe()` on any field whose name doesn't say its format, unit, or where its value comes from. - Put rules in the schema with constraints like `.min()`, `.regex()`, `.email()` and `z.enum()`. The model sees them before it calls, and FrontMCP enforces them before `execute()` runs, reporting every problem at once. - Unknown fields are dropped, and values of the wrong type are rejected, not converted. - `.refine()` rules aren't visible to the model; repeat them in `.describe()`. `.trim()`, `.toLowerCase()` and `.transform()` clean up values before `execute()` gets them. - `.optional()` and `.default()` both leave a field out of `required`. With `.default()`, `tools/list` shows the value, and FrontMCP fills it in before `execute()` runs. - Use `z.object()` and `z.array()` for structured values instead of strings the model has to format. ## Try some challenges ### Challenge: Move the checks into the schema This tool checks `priority` and `title` with `if` statements, so the model can't see the rules until it breaks them. Move both rules into `inputSchema` and delete the checks from `execute()`. Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Cannot log in", priority: "urgent" } } ``` ```ts create-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket.", inputSchema: { title: z.string().describe("One-line summary of the problem"), priority: z.string().describe("low, normal or high"), }, }) export class CreateTicket extends ToolContext { async execute({ title, priority }: { title: string; priority: string }) { if (title.length < 5 || title.length > 120) { this.fail(new PublicMcpError("title must be 5 to 120 characters")); } if (!["low", "normal", "high"].includes(priority)) { this.fail(new PublicMcpError("priority must be low, normal or high")); } return { id: "T-4", title, priority }; } } ``` **Solution file (alternative to the starter):** ```ts create-ticket.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket.", inputSchema: { title: z.string().min(5).max(120).describe("One-line summary of the problem"), priority: z.enum(["low", "normal", "high"]), }, }) export class CreateTicket extends ToolContext { async execute({ title, priority }: { title: string; priority: "low" | "normal" | "high" }) { return { id: "T-4", title, priority }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts create-ticket.test.ts hidden import { test, expect } from "@frontmcp/testing"; async function schema(mcp: any) { const tool = (await mcp.tools.list()).find((t: any) => t.name === "create_ticket"); return tool.inputSchema; } test("`priority` lists its allowed values in the schema", async ({ mcp }) => { expect((await schema(mcp)).properties.priority.enum).toEqual(["low", "normal", "high"]); }); test("`title` is 5 to 120 characters, in the schema", async ({ mcp }) => { const title = (await schema(mcp)).properties.title; expect(title.minLength).toBe(5); expect(title.maxLength).toBe(120); }); test("a bad priority is rejected before `execute()` runs", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { title: "Cannot log in", priority: "urgent" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); test("a valid ticket is still created", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { title: "Cannot log in", priority: "high" }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ id: "T-4", title: "Cannot log in", priority: "high" }); }); ``` **Hint:** `z.enum([...])` replaces the list check, and `.min()` and `.max()` on the string replace the length check. Change the type of `priority` in `execute()` to match. **Solution:** The rules now appear in `tools/list` as `enum`, `minLength` and `maxLength`, so a model can follow them before it calls. A call that breaks them fails with `INVALID_INPUT` instead of your own `PUBLIC_ERROR`, and it lists every problem at once. The `.describe()` note on `priority` became redundant, because the enum lists the values. ### Challenge: Show the model the default priority Most tickets are `normal`, and `create_ticket` already treats a missing `priority` as `normal`. But that rule is a `??` inside `execute()`, where the model can't see it. Move the default into the schema, so `tools/list` shows it, and keep `priority` optional. Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Cannot log in" } } ``` ```ts create-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket.", inputSchema: { title: z.string().min(5).max(120).describe("One-line summary of the problem"), priority: z .enum(["low", "normal", "high"]) .optional() .describe("Use high only when the customer can't work at all"), }, }) export class CreateTicket extends ToolContext { async execute({ title, priority }: { title: string; priority?: "low" | "normal" | "high" }) { return { id: "T-4", title, priority: priority ?? "normal" }; } } ``` **Solution file (alternative to the starter):** ```ts create-ticket.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket.", inputSchema: { title: z.string().min(5).max(120).describe("One-line summary of the problem"), priority: z .enum(["low", "normal", "high"]) .default("normal") .describe("Use high only when the customer can't work at all"), }, }) export class CreateTicket extends ToolContext { async execute({ title, priority }: { title: string; priority: "low" | "normal" | "high" }) { return { id: "T-4", title, priority }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts create-ticket.test.ts hidden import { test, expect } from "@frontmcp/testing"; async function schema(mcp: any) { const tool = (await mcp.tools.list()).find((t: any) => t.name === "create_ticket"); return tool.inputSchema; } test("`priority` isn't required", async ({ mcp }) => { expect((await schema(mcp)).required ?? []).not.toContain("priority"); }); test("the schema shows the default, \"normal\"", async ({ mcp }) => { expect((await schema(mcp)).properties.priority.default).toBe("normal"); }); test("a ticket without a priority is \"normal\"", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { title: "Cannot log in" }); expect(result).toBeSuccessful(); expect(result.json().priority).toBe("normal"); }); test("a ticket can still be \"high\"", async ({ mcp }) => { const result = await mcp.tools.call("create_ticket", { title: "Cannot log in", priority: "high" }); expect(result.json().priority).toBe("high"); }); ``` **Hint:** `.default()` takes the place of `.optional()`, and of the `??`. Change the type of `priority` in `execute()` to match. **Solution:** `.default("normal")` keeps `priority` out of `required`, puts `"default": "normal"` in `tools/list` so the model knows what happens if it says nothing, and fills in `"normal"` before `execute()` runs. The `??` is gone, and `priority` is never `undefined` in `execute()`, so its type loses the `?`. ### Challenge: Take a list, not a comma-separated string `close_tickets` asks the model for a comma-separated string of ids, and then parses it. Change `ids` to a list of ticket ids, where each id looks like `T-123`, and the list has 1 to 10 items. ```ts close-tickets.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", status: "open" }, { id: "T-2", status: "closed" }, { id: "T-3", status: "open" }, ]; @Tool({ name: "close_tickets", description: "Close one or more support tickets.", inputSchema: { ids: z.string().describe("Comma-separated ticket ids, like T-1, T-3"), }, }) export class CloseTickets extends ToolContext { async execute({ ids }: { ids: string }) { const list = ids.split(",").map((id) => id.trim()); for (const t of tickets) if (list.includes(t.id)) t.status = "closed"; return { closed: list }; } } ``` **Solution file (alternative to the starter):** ```ts close-tickets.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", status: "open" }, { id: "T-2", status: "closed" }, { id: "T-3", status: "open" }, ]; @Tool({ name: "close_tickets", description: "Close one or more support tickets.", inputSchema: { ids: z .array(z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1")) .min(1) .max(10) .describe("The tickets to close"), }, }) export class CloseTickets extends ToolContext { async execute({ ids }: { ids: string[] }) { for (const t of tickets) if (ids.includes(t.id)) t.status = "closed"; return { closed: ids }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts close-tickets.test.ts hidden import { test, expect } from "@frontmcp/testing"; async function ids(mcp: any) { const tool = (await mcp.tools.list()).find((t: any) => t.name === "close_tickets"); return tool.inputSchema.properties.ids; } test("`ids` is a list in the schema", async ({ mcp }) => { expect((await ids(mcp)).type).toBe("array"); }); test("the list holds 1 to 10 ids", async ({ mcp }) => { const s = await ids(mcp); expect(s.minItems).toBe(1); expect(s.maxItems).toBe(10); }); test("an id that doesn't look like T-123 is rejected", async ({ mcp }) => { const result = await mcp.tools.call("close_tickets", { ids: ["T-1", "ticket 3"] }); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); test("closing [\"T-1\", \"T-3\"] closes both", async ({ mcp }) => { const result = await mcp.tools.call("close_tickets", { ids: ["T-1", "T-3"] }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ closed: ["T-1", "T-3"] }); }); ``` **Hint:** `z.array(item)` takes the schema for one item. Put the id's `.regex()` on the item, and `.min()` and `.max()` on the array. **Solution:** `z.array(z.string().regex(/^T-\d+$/)).min(1).max(10)` becomes `"type": "array"` with `minItems`, `maxItems` and an `items` schema that has the `pattern`. The model now knows exactly what to send, a bad id is rejected with its position in the list, and `execute()` no longer parses anything. --- # Shaping Tool Results > What a tool call sends back, how FrontMCP turns your return value into content and structuredContent, and how to return results and errors a model can act on. Source: https://frontmcp.dev/learn/shaping-tool-results [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 When a tool finishes, FrontMCP turns what it returned into the call's result, and the result goes into the model's context. The model reads it to decide what to tell the user and what to call next. So a result is as much a part of a tool's interface as its input schema. It should hold the data the model needs, in a shape programs can rely on, with ids that lead to the next step. And when a call fails, the result should say what to do about it. **You will learn** - What a `tools/call` result contains, and what FrontMCP does with your return value - How to declare a result's shape with `outputSchema`, and what FrontMCP checks against it - How to return what the model needs, with ids it can pass to the next tool - How to fail in a way the model can recover from - How to return images ## What comes back from `tools/call` Here is a tool that returns an object. Open the **Wire** tab and expand the `tools/call` exchange: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open", assignee: undefined, updated: new Date("2026-09-20T09:30:00Z") }; } } ``` The result has two parts that carry the same data: ```json { "content": [ { "type": "text", "text": "{\"id\":\"T-1\",\"title\":\"Cannot log in\",\"status\":\"open\",\"updated\":\"2026-09-20T09:30:00.000Z\"}" } ], "structuredContent": { "id": "T-1", "title": "Cannot log in", "status": "open", "updated": "2026-09-20T09:30:00.000Z" } } ``` - **`content`** is a list of blocks: text, images and other media. Most clients put these in front of the model. FrontMCP writes your object into one text block, as JSON. - **`structuredContent`** is the same data as a JSON object, for clients and programs that read structured results directly instead of parsing text. FrontMCP makes the value JSON-safe on the way: the `Date` arrived as an ISO string, and `assignee`, which was `undefined`, was left out. That works well for objects. Plain values are less clear. Switch between these tabs and look at each result: ### What FrontMCP does with a plain value ### Example: A number Initial call configuration: ```js { tool: "count_open_tickets", arguments: {} } ``` ```ts count.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "count_open_tickets", description: "Count open support tickets.", inputSchema: {} }) export class CountOpenTickets extends ToolContext { async execute() { return 2; } } ``` ### Example: A string Initial call configuration: ```js { tool: "ticket_status", arguments: { id: "T-1" } } ``` ```ts status.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "ticket_status", description: "Get the status of a support ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/) }, }) export class TicketStatus extends ToolContext { async execute({ id }: { id: string }) { return `Ticket ${id} is open`; } } ``` ### Example: A list Initial call configuration: ```js { tool: "list_open_tickets", arguments: {} } ``` ```ts list.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "list_open_tickets", description: "List open support tickets.", inputSchema: {} }) export class ListOpenTickets extends ToolContext { async execute() { return [ { id: "T-1", title: "Cannot log in" }, { id: "T-3", title: "Login link expired" }, ]; } } ``` `structuredContent` has to be an object, so FrontMCP wraps anything else in one: `2` becomes `{ "value": 2 }`, the sentence becomes `{ "value": "Ticket T-1 is open" }`, and the list becomes `{ "value": [...] }`. The text block holds the same wrapper, so even the text isn't the plain sentence you returned. `{ "value": 2 }` is correct, but it doesn't say what the 2 counts. Return objects with named fields instead: `{ open: 2 }`, `{ id, status }`, `{ tickets: [...] }`. The field names tell the model what each value means, and the object leaves room to add a field later without changing the result's shape. | `execute()` returns | `structuredContent` | Text block in `content` | | --- | --- | --- | | An object | the object | the object as JSON | | A string, number or boolean | `{ "value": ... }` | `{"value": ...}` as JSON | | An array | `{ "value": [...] }` | `{"value": [...]}` as JSON | | An object with a `content` array of blocks | none | your blocks, as they are ([see images](https://frontmcp.dev/learn/shaping-tool-results#returning-images)) | > **Pitfall: NaN fails the whole call** > > JSON has no `NaN` or `Infinity`, so FrontMCP refuses to send them. Averages over an empty list are the usual way to get one: > > Initial call configuration: > > ```js > { tool: "ticket_stats", arguments: {} } > ``` > > ```ts stats.tool.ts > import { Tool, ToolContext } from "@frontmcp/sdk"; > > const firstReplyMinutes: number[] = []; // no tickets answered yet today > > @Tool({ name: "ticket_stats", description: "Today's support numbers.", inputSchema: {} }) > export class TicketStats extends ToolContext { > async execute() { > const total = firstReplyMinutes.reduce((a, b) => a + b, 0); > return { answered: firstReplyMinutes.length, avgFirstReplyMinutes: total / firstReplyMinutes.length }; > } > } > ``` > > `0 / 0` is `NaN`, so the call fails with `INVALID_OUTPUT`, and in production the message is only "Output validation failed. Please contact support." Return `null` for "no value yet", which JSON can carry, or leave the field out. ## Declaring the shape with `outputSchema` `outputSchema` tells clients the shape of a result before they call the tool. Write it with Zod, like `inputSchema`, but as one `z.object()`: Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts search.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" as const }, { id: "T-2", title: "Invoice total is wrong", status: "closed" as const }, { id: "T-3", title: "Login link expired", status: "open" as const }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string().min(3).describe("Words to look for in ticket titles") }, outputSchema: z.object({ tickets: z.array(z.object({ id: z.string(), title: z.string(), status: z.enum(["open", "closed"]) })), total: z.number().int().describe("How many tickets matched"), }), annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { const matches = tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())); return { tickets: matches, total: matches.length }; } } ``` The Capabilities card now ends with **Returns `{ tickets, total }`**, and `tools/list` in the Wire tab carries the full JSON Schema of the result next to `inputSchema`. Clients and programs that use your server know which fields to expect before they call, and can rely on `total` being a number. FrontMCP also checks every result against `outputSchema`. When a result matches, FrontMCP sends the parsed result, so fields that aren't in the schema are dropped by default, whether or not the tool has a widget. Changed in 1.10.16: development servers also warn about dropped keys. [`output.undeclaredKeys`](https://frontmcp.dev/reference/sdk/tool#output-policy) can keep them or fail the call instead; calls that render a widget still send declared keys only. When it doesn't match, the call fails. (Changed in 1.8.7: a tool with a widget used to keep its extra fields.) The **Tests** tab checks both cases: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-2" } } ``` ```ts get-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { rows } from "./db"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, outputSchema: z.object({ id: z.string(), title: z.string(), status: z.enum(["open", "closed"]) }), }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { // Returns the whole row and relies on outputSchema to trim it. return rows.find((r) => r.id === id)!; } } ``` ```ts db.ts export const rows = [ { id: "T-1", title: "Cannot log in", status: "open", internal_notes: "Legacy plan. Don't offer a refund." }, { id: "T-2", title: "Invoice total is wrong", status: "pending", internal_notes: "Finance is checking. Don't promise a date." }, ]; ``` ```ts get-ticket.test.ts import { test, expect } from "@frontmcp/testing"; test("T-1 matches outputSchema, so `internal_notes` is dropped", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result.raw.structuredContent).toEqual({ id: "T-1", title: "Cannot log in", status: "open" }); }); test("T-2's status isn't in outputSchema, so the call fails with INVALID_OUTPUT", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-2" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("INVALID_OUTPUT"); expect(result.text()).toBe("Tool output validation failed (output does not match outputSchema at status)"); }); test("nothing from T-2's row is sent", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-2" }); expect(result.raw).not.toHaveProperty("structuredContent"); expect(result.text()).not.toContain("Finance"); }); ``` Someone added a `pending` status to the database, and nobody updated `outputSchema`. T-1 still comes back trimmed, but T-2 doesn't match, so the call fails with `INVALID_OUTPUT`, and nothing from the row is sent: not the status the schema says can't happen, and not the internal note. The message names the first field that didn't match. In production it says only "Output validation failed. Please contact support." > **Pitfall: Letting outputSchema trim your results** > > Returning a whole row and letting `outputSchema` drop the extra fields works until one value doesn't match. Then the model gets an error instead of the ticket, for every ticket with that value, and in production it can't tell why. Build the result yourself, field by field, as in the next section, and test that results match. `@Tool` also checks `execute()`'s return type against `outputSchema` when TypeScript compiles, and would reject this example, because `db.ts` types `status` as any string. But types describe what you expect: a database can still hand back a status nobody added to them. ## Return what the model needs The easiest thing to return is whatever the database gave you. Here is a typical row: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { db } from "./db"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return db.tickets.find((row) => row.ticket_no === id); } } ``` ```ts db.ts export const db = { tickets: [ { id: 5501, ticket_no: "T-1", subject: "Cannot log in", status_code: 1, cust_id: 881, assignee_id: 12, body_html: "

I get Error 403 when I sign in from the office.

", internal_notes: "Legacy plan. Don't offer a refund.", created_ms: 1789808400000, updated_ms: 1789896600000, _version: 7, }, ], customers: [{ id: 881, name: "Dana Levi", email: "dana@acme.com", password_hash: "$2b$10$Qe..." }], statuses: { 1: "open", 2: "waiting on customer", 3: "closed" } as Record, }; ``` The model has to work to use this, and some of it is dangerous: - **Codes instead of meanings.** `status_code: 1` means nothing without the `statuses` table, which the model can't see. - **Two ids.** `id: 5501` and `ticket_no: "T-1"` both look like the ticket's id. Only one of them works with `get_ticket`. - **Formats a model reads badly.** `created_ms` is a number of milliseconds; `body_html` spends tokens on markup. - **Things the model shouldn't see.** `internal_notes` is for agents, and a model may quote it to the customer. Map the row to the result you want the model to read: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { db } from "./db"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, outputSchema: z.object({ id: z.string(), title: z.string(), status: z.enum(["open", "waiting on customer", "closed"]), customer: z.string(), description: z.string(), created: z.string(), updated: z.string(), }), }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const row = db.tickets.find((r) => r.ticket_no === id)!; const customer = db.customers.find((c) => c.id === row.cust_id)!; return { id: row.ticket_no, title: row.subject, status: db.statuses[row.status_code] as "open" | "waiting on customer" | "closed", customer: customer.name, description: row.body_html.replace(/<[^>]+>/g, ""), created: new Date(row.created_ms).toISOString(), updated: new Date(row.updated_ms).toISOString(), }; } } ``` ```ts db.ts export const db = { tickets: [ { id: 5501, ticket_no: "T-1", subject: "Cannot log in", status_code: 1, cust_id: 881, assignee_id: 12, body_html: "

I get Error 403 when I sign in from the office.

", internal_notes: "Legacy plan. Don't offer a refund.", created_ms: 1789808400000, updated_ms: 1789896600000, _version: 7, }, ], customers: [{ id: 881, name: "Dana Levi", email: "dana@acme.com", password_hash: "$2b$10$Qe..." }], statuses: { 1: "open", 2: "waiting on customer", 3: "closed" } as Record, }; ``` The result is shorter and says more. Some rules that got it there: - **Use the words the user and the model use.** `status: "open"`, not `status_code: 1`, and `customer: "Dana Levi"`, not `cust_id: 881`. - **Give each thing one id, in the format your other tools accept.** Here that's `T-1`, which is also what `get_ticket` takes. - **Prefer readable formats.** ISO dates, plain text instead of HTML, and units in field names (`firstReplyMinutes`) when a number has one. - **Pick fields on purpose.** Listing each field means a new database column, like a password hash, can't end up in a result without someone deciding it should. ## Ids the model can pass to the next tool Models often chain tools: search for something, then act on what they found. That only works if a result carries an id that the next tool accepts, in exactly the format it accepts. Here `search_tickets` returns short summaries, and says which tool gives the rest: Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts tickets.tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns up to 5 short matches; use get_ticket with an id for the full ticket.", inputSchema: { query: z.string().min(3).describe("Words to look for in ticket titles") }, outputSchema: z.object({ tickets: z.array(z.object({ id: z.string(), title: z.string(), status: z.string() })), total: z.number().int().describe("How many tickets matched, including any not returned"), }), annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { const q = query.toLowerCase(); const matches = tickets.filter((t) => t.title.toLowerCase().includes(q)); return { tickets: matches.slice(0, 5).map(({ id, title, status }) => ({ id, title, status })), total: matches.length, }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id, with its full description.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}. Find tickets with search_tickets.`)); return ticket; } } ``` ```ts tickets.ts export const tickets = [ { id: "T-1", title: "Cannot log in", status: "open", description: "Error 403 when signing in from the office." }, { id: "T-2", title: "Invoice total is wrong", status: "closed", description: "Charged twice for September." }, { id: "T-3", title: "Login link expired", status: "open", description: "The emailed link says it has expired." }, ]; ``` ```ts chain.test.ts import { test, expect } from "@frontmcp/testing"; test("an id from search_tickets works with get_ticket", async ({ mcp }) => { const found = await mcp.tools.call("search_tickets", { query: "log" }); const first = found.json().tickets[0]; const ticket = await mcp.tools.call("get_ticket", { id: first.id }); expect(ticket).toBeSuccessful(); expect(ticket.json().title).toBe(first.title); }); test("search results are summaries, without descriptions", async ({ mcp }) => { const found = await mcp.tools.call("search_tickets", { query: "log" }); expect(found.json().tickets[0]).not.toHaveProperty("description"); expect(found.json().total).toBe(2); }); ``` The **Tests** tab does what a model would: search, take the first id, and get the ticket. A test like this catches the mistakes that make models stumble, like search returning a database number while `get_ticket` wants `T-1`. Two more details help the model find its way: - **Search returns summaries; get returns details.** A search that returns every field of every match fills the model's context with text it didn't ask for. - **Say when a list is cut short.** `total` tells the model there were more matches than it got, so it can ask for a narrower search instead of assuming it saw everything. ## Errors the model can act on A call can fail in three ways, and each needs different handling: 1. **The arguments are wrong.** FrontMCP catches this before `execute()` runs and returns `INVALID_INPUT` with each problem. See [Schemas Are Contracts](https://frontmcp.dev/learn/schemas-are-contracts). 2. **The arguments are fine, but the request can't be done.** The ticket doesn't exist, or it's already closed. Fail with `this.fail(new PublicMcpError(message, code))`. 3. **Something broke.** The database is down. Let the error throw; FrontMCP returns it as `TOOL_EXECUTION_ERROR` and hides the details in production. For the second kind, write the message for the model. Say what went wrong, with the value it sent, and what to do next: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-2" } } ``` ```ts close-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "close_ticket", description: "Close an open support ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) { this.fail(new PublicMcpError(`There's no ticket ${id}. Find the right id with search_tickets.`, "TICKET_NOT_FOUND")); } if (ticket.status === "closed") { this.fail(new PublicMcpError(`Ticket ${id} is already closed. Nothing to do.`, "ALREADY_CLOSED")); } ticket.status = "closed"; return { id, status: ticket.status }; } } ``` ```ts close-ticket.test.ts import { test, expect } from "@frontmcp/testing"; test("a missing ticket fails with TICKET_NOT_FOUND", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-9" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("TICKET_NOT_FOUND"); expect(result.text()).toBe("There's no ticket T-9. Find the right id with search_tickets."); }); test("closing a closed ticket fails with ALREADY_CLOSED", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-2" }); expect(result.raw._meta?.code).toBe("ALREADY_CLOSED"); }); test("closing an open ticket works", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ id: "T-1", status: "closed" }); }); ``` `this.fail()` ends the call with an `isError: true` result. `PublicMcpError` marks the message as safe to show, so the model reads it word for word, in development and in production. The second argument is a code: FrontMCP puts it in the result's `_meta.code`, where programs and tests can check it without parsing the message. Leave it out and the code is `PUBLIC_ERROR`. Not every "nothing" is an error. A search with no matches should return `{ tickets: [], total: 0 }`: that's a real answer, and the model can say so or try other words. Fail when the model asked for something specific that can't be done, like closing a ticket that doesn't exist. > **Pitfall: A plain Error hides the message** > > Throwing a `PublicMcpError` instead of passing it to `this.fail()` gives the same result ([see `this.fail`](https://frontmcp.dev/reference/sdk/fail#failing-vs-throwing)), which helps in code that can't call `this.fail()`, like a provider. What matters is the class. FrontMCP treats any other error as something that broke: > > Initial call configuration: > > ```js > { tool: "close_ticket", arguments: { id: "T-9" } } > ``` > > ```ts close-ticket.tool.ts > import { Tool, ToolContext, z } from "@frontmcp/sdk"; > > @Tool({ > name: "close_ticket", > description: "Close an open support ticket.", > inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, > }) > export class CloseTicket extends ToolContext { > async execute({ id }: { id: string }) { > if (id !== "T-1") throw new Error(`There's no ticket ${id}.`); > return { id, status: "closed" }; > } > } > ``` > > The code is `TOOL_EXECUTION_ERROR`, and the message starts with `Tool "close_ticket" execution failed:` and ends with a stack trace. The Playground runs in development mode, so you still see your text. In production the model gets "Internal FrontMCP error. Please contact support with error ID: …" instead. Use `PublicMcpError` for every error the model should read. ## Returning images Results aren't limited to text. A block in `content` can be an image, as base64 data with a MIME type. Help desk customers often attach screenshots, and a model that can see images can read one: ### Returning an image ### Example: Image only Set `outputSchema: "image"` and return one image block. Initial call configuration: ```js { tool: "get_screenshot", arguments: { id: "T-1" } } ``` ```ts screenshot.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { screenshots } from "./attachments"; @Tool({ name: "get_screenshot", description: "Get the screenshot a customer attached to a ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, outputSchema: "image", }) export class GetScreenshot extends ToolContext { async execute({ id }: { id: string }) { const file = screenshots[id]; if (!file) this.fail(new PublicMcpError(`Ticket ${id} has no screenshot.`, "NO_SCREENSHOT")); return { type: "image" as const, data: file.data, mimeType: file.mimeType }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts attachments.ts hidden export const screenshots: Record = { "T-1": { name: "login-error.png", mimeType: "image/png", data: "iVBORw0KGgoAAAANSUhEUgAAAHgAAABICAMAAAAKwMFNAAAAElBMVEX////s7vFaYGnWRUE0btzIzNIk3o6XAAAAgUlEQVR42u3Z0QqAMAiF4aXt/V+5i26DRolO/Q90/WGTA2NDgjJawqoic95fD5jl8oGPoAAD+8LDOMC7wmoQ4GV49RTrwCyXC0xl1oenQb7B/0fNB79cBgpOHARHbTXNRXOVb64eE9NcNFcx+DQIcE74aX341cBUJnBbmOcf4NTwBVNjKhVy30tUAAAAAElFTkSuQmCC", }, }; ``` ### Example: Text and image Return a `content` array yourself, and FrontMCP sends it as it is. Initial call configuration: ```js { tool: "get_screenshot", arguments: { id: "T-1" } } ``` ```ts screenshot.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { screenshots } from "./attachments"; @Tool({ name: "get_screenshot", description: "Get the screenshot a customer attached to a ticket, with its file name.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetScreenshot extends ToolContext { async execute({ id }: { id: string }) { const file = screenshots[id]; if (!file) this.fail(new PublicMcpError(`Ticket ${id} has no screenshot.`, "NO_SCREENSHOT")); return { content: [ { type: "text" as const, text: `${file.name}, attached to ${id} by the customer.` }, { type: "image" as const, data: file.data, mimeType: file.mimeType }, ], }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts attachments.ts hidden export const screenshots: Record = { "T-1": { name: "login-error.png", mimeType: "image/png", data: "iVBORw0KGgoAAAANSUhEUgAAAHgAAABICAMAAAAKwMFNAAAAElBMVEX////s7vFaYGnWRUE0btzIzNIk3o6XAAAAgUlEQVR42u3Z0QqAMAiF4aXt/V+5i26DRolO/Q90/WGTA2NDgjJawqoic95fD5jl8oGPoAAD+8LDOMC7wmoQ4GV49RTrwCyXC0xl1oenQb7B/0fNB79cBgpOHARHbTXNRXOVb64eE9NcNFcx+DQIcE74aX341cBUJnBbmOcf4NTwBVNjKhVy30tUAAAAAElFTkSuQmCC", }, }; ``` ```ts screenshot.test.ts import { test, expect } from "@frontmcp/testing"; test("the result has a caption and an image", async ({ mcp }) => { const result = await mcp.tools.call("get_screenshot", { id: "T-1" }); expect(result).toHaveTextContent("login-error.png"); expect(result).toHaveImageContent(); expect(result.raw).not.toHaveProperty("structuredContent"); }); ``` The Call tab shows the image. Either way there's no `structuredContent`: an image isn't JSON data, so FrontMCP only fills in `content`. When you return a `content` array yourself, FrontMCP doesn't add anything to it, so it's also the way to control exactly what the model reads. ## Recap - A `tools/call` result has `content` (blocks the model reads) and `structuredContent` (the same data as a JSON object). - Objects arrive as they are. Strings, numbers and arrays are wrapped as `{ "value": ... }`, so return objects with named fields. - `outputSchema` advertises the shape of a result in `tools/list`, and FrontMCP checks every result against it: extra fields are dropped by default, and a result that doesn't match fails with `INVALID_OUTPUT`. - Map database rows to results: meanings instead of codes, one id per thing, readable formats, and only fields you chose. - Return ids in exactly the format your other tools accept, and test the chain. - Fail with `this.fail(new PublicMcpError(message, code))`, with a message that says what to do next. A plain `Error` is hidden in production. - Return images as `{ type: "image", data, mimeType }` with `outputSchema: "image"`, or build the `content` array yourself. ## Try some challenges ### Challenge: Trim a ticket for the model `get_ticket` returns the whole database row. Return only `id` (like `T-1`), `title`, `status` (as a word) and `customer` (the name), and declare that shape with `outputSchema`. Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { db } from "./db"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return db.tickets.find((row) => row.ticket_no === id)!; } } ``` ```ts db.ts export const db = { tickets: [ { id: 5501, ticket_no: "T-1", subject: "Cannot log in", status_code: 1, cust_id: 881, internal_notes: "Legacy plan. Don't offer a refund." }, ], customers: [{ id: 881, name: "Dana Levi", password_hash: "$2b$10$Qe..." }], statuses: { 1: "open", 2: "closed" } as Record, }; ``` **Solution file (alternative to the starter):** ```ts get-ticket.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { db } from "./db"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, outputSchema: z.object({ id: z.string(), title: z.string(), status: z.enum(["open", "closed"]), customer: z.string(), }), }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const row = db.tickets.find((r) => r.ticket_no === id)!; const customer = db.customers.find((c) => c.id === row.cust_id)!; return { id: row.ticket_no, title: row.subject, status: db.statuses[row.status_code], customer: customer.name }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts get-ticket.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the result is id, title, status and customer", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result).toBeSuccessful(); expect(result.raw.structuredContent).toEqual({ id: "T-1", title: "Cannot log in", status: "open", customer: "Dana Levi" }); }); test("internal notes never reach the model", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result.text()).not.toContain("refund"); }); test("`outputSchema` declares the four fields", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "get_ticket"); expect(Object.keys(tool?.outputSchema?.properties ?? {}).sort()).toEqual(["customer", "id", "status", "title"]); }); ``` **Hint:** Look up the customer by `cust_id` and the status word in `db.statuses`, then return a new object with just the four fields. **Solution:** The result is built field by field, so nothing reaches the model unless you listed it, and `outputSchema` tells clients the shape. Relying on `outputSchema` alone would also have trimmed this row, but only while every field matched: the day a status the schema doesn't know shows up, the call fails instead. ### Challenge: Return ids the next tool accepts `search_tickets` returns the database's numeric ids, but `get_ticket` wants ids like `T-1`, so a model can't get from one to the other. Make each search result carry an `id` that `get_ticket` accepts. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts tickets.tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { rows } from "./db"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Use get_ticket with an id for the full ticket.", inputSchema: { query: z.string().min(3) }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { const matches = rows.filter((r) => r.subject.toLowerCase().includes(query.toLowerCase())); return { tickets: matches.map((r) => ({ id: r.id, title: r.subject })) }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const row = rows.find((r) => r.ticket_no === id); if (!row) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND")); return { id: row.ticket_no, title: row.subject }; } } ``` ```ts db.ts export const rows = [ { id: 5501, ticket_no: "T-1", subject: "Cannot log in" }, { id: 5502, ticket_no: "T-2", subject: "Invoice total is wrong" }, { id: 5503, ticket_no: "T-3", subject: "Login link expired" }, ]; ``` **Solution file (alternative to the starter):** ```ts tickets.tools.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { rows } from "./db"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Use get_ticket with an id for the full ticket.", inputSchema: { query: z.string().min(3) }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { const matches = rows.filter((r) => r.subject.toLowerCase().includes(query.toLowerCase())); return { tickets: matches.map((r) => ({ id: r.ticket_no, title: r.subject })) }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const row = rows.find((r) => r.ticket_no === id); if (!row) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND")); return { id: row.ticket_no, title: row.subject }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts chain.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("every search result has an id like T-123", async ({ mcp }) => { const found = await mcp.tools.call("search_tickets", { query: "log" }); for (const t of found.json().tickets) expect(String(t.id)).toMatch(/^T-\d+$/); }); test("each id from search_tickets works with get_ticket", async ({ mcp }) => { const found = await mcp.tools.call("search_tickets", { query: "log" }); expect(found.json().tickets).toHaveLength(2); for (const t of found.json().tickets) { const ticket = await mcp.tools.call("get_ticket", { id: t.id }); expect(ticket).toBeSuccessful(); expect(ticket.json().title).toBe(t.title); } }); ``` **Hint:** The row already has the id `get_ticket` wants. It's just not the one called `id`. **Solution:** Search now returns `ticket_no` as `id`, so its results feed straight into `get_ticket`. The hidden check does exactly what a model would, search and then get, which is the easiest way to catch a broken chain before a model does. ### Challenge: Fail so the model can recover This tool throws a plain `Error` when a ticket doesn't exist, which reaches the model as an internal error. Make a missing ticket fail with the code `TICKET_NOT_FOUND` and a message that starts with `There's no ticket T-9` (for id `T-9`) and points the model to `search_tickets`. Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-9" } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new Error("Not found"); return ticket; } } ``` **Solution file (alternative to the starter):** ```ts get-ticket.tool.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) { this.fail(new PublicMcpError(`There's no ticket ${id}. Find tickets by title with search_tickets.`, "TICKET_NOT_FOUND")); } return ticket; } } ``` **Hidden fixture/test file (runs with the example):** ```ts get-ticket.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("a missing ticket fails with the code TICKET_NOT_FOUND", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-9" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("TICKET_NOT_FOUND"); }); test("the message starts with \"There's no ticket T-9\"", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-9" }); expect(result.text()).toMatch(/^There's no ticket T-9/); }); test("the message points to search_tickets", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-9" }); expect(result.text()).toContain("search_tickets"); }); test("an existing ticket still comes back", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result).toBeSuccessful(); expect(result.json().title).toBe("Cannot log in"); }); ``` **Hint:** Only a `PublicMcpError`'s message is meant for the model. It takes the code as its second argument. **Solution:** `this.fail()` sends the `PublicMcpError` as it is: your message word for word, and your code in `_meta.code`. The plain `Error` was wrapped as a `TOOL_EXECUTION_ERROR`, which production replaces with "Internal FrontMCP error". The new message also names the tool to use next, so the model can recover instead of apologizing. --- # Exposing Data with Resources > When data should be a resource instead of a tool, how to declare fixed resources and URI templates, and what clients get back when they read one. Source: https://frontmcp.dev/learn/exposing-data-with-resources [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A **resource** is data your FrontMCP server makes available at a URI, like `docs://refund-policy` or `tickets://T-2`. Tools are for things the model decides to do. Resources are for things the application reads and puts in front of the model, usually because the user picked them. A lot of what people first write as tools, like "get the policy" or "get this record", works better as a resource. **You will learn** - When data should be a resource instead of a tool, and who decides to read it - How to declare a resource with a fixed URI using `@Resource` - How to choose a MIME type, and what FrontMCP picks when you don't - How to cover a whole family of URIs, like `tickets://{id}`, with `@ResourceTemplate` - What `resources/list`, `resources/templates/list` and `resources/read` return, and what happens when a resource doesn't exist ## Data that isn't an action Support agents keep asking the model about the refund policy, so someone wrote a tool for it: Initial call configuration: ```js { tool: "get_refund_policy", arguments: {} } ``` ```ts policy.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "get_refund_policy", description: "Get the refund policy", inputSchema: {}, }) export class GetRefundPolicy extends ToolContext { async execute() { return "# Refunds\n\nFull refund within 30 days of purchase. After that, store credit only."; } } ``` It works, but a tool is the wrong shape for this: 1. **The model decides when to call it.** A support agent replying to an angry customer can't make sure the policy is in the conversation. They can only hope the model thinks to look it up. 2. **It has no address.** Nothing can point at "the refund policy": not the user, not the client's UI, not another part of your server. 3. **It takes up room among the actions.** Every tool in `tools/list` is something the model has to weigh on every turn. A document isn't an action. MCP has a separate kind of capability for data like this. The difference is **who decides** to use it: | | Tool | Resource | | --- | --- | --- | | Who decides to use it | The model, mid-conversation | The application, usually because the user picked it | | Identified by | A name, like `get_ticket` | A URI, like `tickets://T-2` | | Discovered with | `tools/list` | `resources/list` and `resources/templates/list` | | Used with | `tools/call`, with arguments | `resources/read`, with a URI | | Side effects | Allowed | None. Reading a resource shouldn't change anything. | Clients usually show resources in an attach or @-mention menu. The user picks the refund policy, the client reads it, and its text goes into the conversation before the model says a word. ## Declaring a resource Here is the refund policy as a resource: Initial call configuration: ```js { resource: "docs://refund-policy" } ``` ```ts policy.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "refund-policy", title: "Refund policy", uri: "docs://refund-policy", mimeType: "text/markdown", description: "When customers can get their money back. Attach it when answering refund questions.", }) export class RefundPolicy extends ResourceContext { async execute(uri: string) { return "# Refunds\n\nFull refund within 30 days of purchase. After that, store credit only."; } } ``` A `@Resource` has: 1. **`uri`**, the address clients read. The scheme (`docs://`) is yours to choose. Pick one that says what kind of thing lives there. 2. **`name`**, an identifier, and optionally a **`title`** for clients to show people. 3. **`description`**, what the data is and when it's worth attaching. Clients show it in their pickers, so write it for the person choosing what to attach. 4. **`mimeType`**, what kind of text it is. More on that [below](https://frontmcp.dev/learn/exposing-data-with-resources#picking-a-mime-type). 5. **The class**, which extends `ResourceContext` and implements `execute(uri)`. It runs every time a client reads the resource. The [`@Resource` reference](https://frontmcp.dev/reference/sdk/resource) lists every option. `execute()` can return plain text or an object, and FrontMCP builds the MCP result around it. Open the **Call** tab: the page already sent `resources/read`, and the text came back inside `contents`, labelled with the URI and the MIME type. ### What does the client actually receive? A client discovers resources with `resources/list`. Open the **Wire** tab and expand it. For this server it returns: ```json { "resources": [ { "name": "refund-policy", "title": "Refund policy", "uri": "docs://refund-policy", "description": "When customers can get their money back. Attach it when answering refund questions.", "mimeType": "text/markdown" } ] } ``` That's metadata only. The content arrives when the client sends `resources/read` with `{ "uri": "docs://refund-policy" }`: ```json { "contents": [ { "uri": "docs://refund-policy", "mimeType": "text/markdown", "text": "# Refunds\n\nFull refund within 30 days of purchase. After that, store credit only." } ] } ``` `contents` is a list, because one read can return several pieces. (The real responses carry a few more fields, like `_meta`; the Wire tab shows all of them.) ## Picking a MIME type `mimeType` tells the client what the text is, so it can decide how to show it and how to hand it to the model. Two cover most help desk data: - **`text/markdown`** for prose a person or model reads: policies, articles, canned replies. - **`application/json`** for records a model or program picks fields out of: a ticket, a customer, some counts. When you leave `mimeType` out, FrontMCP picks one from what `execute()` returns: an object is sent as JSON and labelled `application/json`, and a string is labelled `text/plain`. Open the **Tests** tab to see all three: Initial call configuration: ```js { resource: "stats://tickets" } ``` ```ts resources.ts active import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "refund-policy", uri: "docs://refund-policy", mimeType: "text/markdown", description: "When customers can get their money back", }) export class RefundPolicy extends ResourceContext { async execute(uri: string) { return "# Refunds\n\nFull refund within 30 days of purchase."; } } @Resource({ name: "ticket-stats", uri: "stats://tickets", description: "How many tickets are open and closed right now", }) export class TicketStats extends ResourceContext { async execute(uri: string) { return { open: 2, closed: 1 }; } } @Resource({ name: "support-hours", uri: "docs://support-hours", description: "When the support team is online", }) export class SupportHours extends ResourceContext { async execute(uri: string) { return "Monday to Friday, 8:00 to 18:00 UTC."; } } ``` ```ts resources.test.ts import { test, expect } from "@frontmcp/testing"; test("the policy is markdown, because we said so", async ({ mcp }) => { expect(await mcp.resources.read("docs://refund-policy")).toHaveMimeType("text/markdown"); }); test("an object is sent as JSON", async ({ mcp }) => { const stats = await mcp.resources.read("stats://tickets"); expect(stats).toHaveMimeType("application/json"); expect(stats.json()).toEqual({ open: 2, closed: 1 }); }); test("a string with no mimeType is plain text", async ({ mcp }) => { expect(await mcp.resources.read("docs://support-hours")).toHaveMimeType("text/plain"); }); ``` The fallback is fine for JSON, but set `mimeType` anyway: it also goes out in `resources/list`, so clients know what they'll get before they read. Notice that `ticket-stats` doesn't declare one, so the Capabilities card has no type to show. ## A family of resources with a template The refund policy has one URI. Tickets don't: there's `T-1`, `T-2`, and a new one every few minutes. You can't declare a `@Resource` for each. A **resource template** covers all of them with one URI pattern: Initial call configuration: ```js { resource: "tickets://T-2" } ``` ```ts ticket.resource.ts import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "One support ticket, with its title and status", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { return tickets.find((t) => t.id === id); } } ``` `{id}` in `uriTemplate` is a parameter. When a client reads `tickets://T-2`, FrontMCP matches the URI against the template and passes `{ id: "T-2" }` as the second argument of `execute()`. The type parameter on `ResourceContext<{ id: string }>` describes those parameters. Templates aren't in `resources/list`, because there's no single URI to list. Clients find them with `resources/templates/list`, which returns the `uriTemplate` instead of a `uri`. Look for it in the Wire tab. (Every option is in the [`@ResourceTemplate` reference](https://frontmcp.dev/reference/sdk/resource-template).) Now look at the result in the Call tab. `execute()` returned a plain object, and FrontMCP built the content around it the same way as for a fixed resource: the ticket as JSON, the template's MIME type, and the `uri` that was read, `tickets://T-2`. A client that attaches `T-1` and `T-2` gets two pieces of content, each labelled with its own ticket. Change the id in the Call tab to read other tickets. To set every field of the result yourself, return `{ contents: [{ uri, mimeType, text }] }` instead, and FrontMCP sends it as it is. The [`@Resource` reference](https://frontmcp.dev/reference/sdk/resource#executeuri-params) lists every shape `execute()` can return. > **Note** > > A template can have several parameters, like `customers://{customer}/tickets/{id}`. Each one matches a single path segment, so `tickets://{id}` matches `tickets://T-2` but not `tickets://T-2/comments`. The [Research Assistant](https://frontmcp.dev/examples/research-assistant) example uses two templates, `kb://{id}` and `tickets://{id}`, so a client can open every source an answer cites. ## When the ticket doesn't exist Read `T-9` in the example above. `tickets.find()` returns `undefined`, so `execute()` returns nothing, and the read fails with `Resource "tickets://T-9" read failed: Resource output not found`. That's how a server that broke looks, and nothing in it says the ticket doesn't exist. When a template's parameters don't point at anything, throw `ResourceNotFoundError`: Initial call configuration: ```js { resource: "tickets://T-9" } ``` ```ts ticket.resource.ts active import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "One support ticket, with its title and status", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new ResourceNotFoundError(uri); return ticket; } } ``` ```ts ticket.test.ts import { test, expect } from "@frontmcp/testing"; test("T-2 reads as JSON", async ({ mcp }) => { const result = await mcp.resources.read("tickets://T-2"); expect(result).toHaveMimeType("application/json"); expect(result.json()).toMatchObject({ id: "T-2", status: "closed" }); }); test("T-9 is a not-found error that names the URI", async ({ mcp }) => { const result = await mcp.resources.read("tickets://T-9"); expect(result).toBeError(-32602); expect(result.error.message).toBe("Resource not found: tickets://T-9"); }); test("a URI that no resource matches gets the same error", async ({ mcp }) => { const result = await mcp.resources.read("tickets://T-2/comments"); expect(result).toBeError(-32602); expect(result.error.message).toBe("Resource not found: tickets://T-2/comments"); }); ``` Unlike a tool error, a resource error isn't a result with `isError`. It's a JSON-RPC error, so there are no `contents` and nothing gets attached. The Call tab shows it: code `-32602`, which MCP 2026-07-28 uses for a resource that doesn't exist, and the message `Resource not found: tickets://T-9`. The **Tests** tab shows that a URI no resource or template matches fails the same way, before any of your code runs. For a client, a ticket that doesn't exist and a URI that points nowhere are the same thing: there's nothing to read. > **Pitfall: Throw ResourceNotFoundError, not a plain Error** > > A `ResourceNotFoundError` tells the client the ticket doesn't exist. A plain `Error` tells it the server failed: > > Initial call configuration: > > ```js > { resource: "tickets://T-9" } > ``` > > ```ts ticket.resource.ts > import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; > > const tickets = [{ id: "T-1", title: "Cannot log in", status: "open" }]; > > @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json" }) > export class TicketResource extends ResourceContext<{ id: string }> { > async execute(uri: string, { id }: { id: string }) { > const ticket = tickets.find((t) => t.id === id); > // 🚩 Says the read failed, not that T-9 doesn't exist > if (!ticket) throw new Error(`There's no ticket ${id}.`); > return ticket; > } > } > ``` > > The client gets code `-32603`, an internal error, and `Resource "tickets://T-9" read failed: There's no ticket T-9.` That's in development, which is how the Playground runs. With `NODE_ENV=production`, FrontMCP hides the message of an error like this, and the client only gets `Internal FrontMCP error. Please contact support with error ID: …`. For an error the client should read, throw `ResourceNotFoundError`, or a `PublicMcpError` with your own message. ## Recap - Tools are for actions the model decides to take. Resources are data the application reads, usually because the user picked it, and they're addressed by URI. - `@Resource` declares one fixed URI. Its class extends `ResourceContext` and returns the content from `execute(uri)`. - Set `mimeType`: `text/markdown` for prose, `application/json` for records. Without it, objects are sent as JSON and strings as `text/plain`. - `@ResourceTemplate` covers a family of URIs like `tickets://{id}` and passes the parameters to `execute(uri, params)`. FrontMCP labels what it returns with the URI that was read. - Clients discover resources with `resources/list` and templates with `resources/templates/list`, and read both with `resources/read`. - Throw `ResourceNotFoundError` when a URI doesn't point at anything. The client gets a `-32602` JSON-RPC error instead of content. A plain `Error` reads as a server failure, and production hides its message. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Turn a tool into a resource The escalation policy is a document, but it was written as a tool. Make it a resource at `docs://escalation-policy`, in markdown, and remove the tool. ```ts escalation.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "get_escalation_policy", description: "Get the escalation policy", inputSchema: {}, }) export class GetEscalationPolicy extends ToolContext { async execute() { return "# Escalation\n\nEscalate to the on-call lead when a customer is blocked for more than 4 hours."; } } ``` **Solution file (alternative to the starter):** ```ts escalation.ts solution import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "escalation-policy", uri: "docs://escalation-policy", mimeType: "text/markdown", description: "When to hand a ticket to the on-call lead", }) export class EscalationPolicy extends ResourceContext { async execute(uri: string) { return "# Escalation\n\nEscalate to the on-call lead when a customer is blocked for more than 4 hours."; } } ``` **Hidden fixture/test file (runs with the example):** ```ts escalation.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`get_escalation_policy` is no longer a tool", async ({ mcp }) => { expect(await mcp.tools.list()).not.toContainTool("get_escalation_policy"); }); test("`docs://escalation-policy` is listed as a resource", async ({ mcp }) => { expect(await mcp.resources.list()).toContainResource("docs://escalation-policy"); }); test("it's markdown, and it still says when to escalate", async ({ mcp }) => { const result = await mcp.resources.read("docs://escalation-policy"); expect(result).toHaveMimeType("text/markdown"); expect(result.text()).toContain("Escalate to the on-call lead"); }); ``` **Hint:** Swap `@Tool` for `@Resource` and `ToolContext` for `ResourceContext`. A resource needs a `uri` instead of an `inputSchema`. **Solution:** The policy now has an address, so a user can attach it and the client can read it before the model starts. Because it's markdown, the client knows it's prose, and because it's no longer in `tools/list`, the model has one fewer action to weigh. ### Challenge: Add a template for customers Support agents want to attach a customer's details the same way they attach a ticket. Add a template at `customers://{id}` that returns the customer as JSON. Initial call configuration: ```js { resource: "tickets://T-1" } ``` ```ts resources.ts import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open", customer: "C-1" }, { id: "T-2", title: "Invoice total is wrong", status: "closed", customer: "C-2" }, ]; const customers = [ { id: "C-1", name: "Acme Corp", plan: "enterprise" }, { id: "C-2", name: "Globex", plan: "starter" }, ]; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "One support ticket, with its title, status and customer", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new ResourceNotFoundError(uri); return ticket; } } // Add a `customers://{id}` template here. ``` **Solution file (alternative to the starter):** ```ts resources.ts solution import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open", customer: "C-1" }, { id: "T-2", title: "Invoice total is wrong", status: "closed", customer: "C-2" }, ]; const customers = [ { id: "C-1", name: "Acme Corp", plan: "enterprise" }, { id: "C-2", name: "Globex", plan: "starter" }, ]; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "One support ticket, with its title, status and customer", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new ResourceNotFoundError(uri); return ticket; } } @ResourceTemplate({ name: "customer", uriTemplate: "customers://{id}", mimeType: "application/json", description: "One customer, with their name and plan", }) export class CustomerResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const customer = customers.find((c) => c.id === id); if (!customer) throw new ResourceNotFoundError(uri); return customer; } } ``` **Hidden fixture/test file (runs with the example):** ```ts customers.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`customers://{id}` is listed as a template", async ({ mcp }) => { expect(await mcp.resources.listTemplates()).toContainResourceTemplate("customers://{id}"); }); test("reading `customers://C-2` returns Globex as JSON", async ({ mcp }) => { const result = await mcp.resources.read("customers://C-2"); expect(result).toHaveMimeType("application/json"); expect(result.json()).toMatchObject({ id: "C-2", name: "Globex" }); }); test("the content is labelled `customers://C-2`", async ({ mcp }) => { const result = await mcp.resources.read("customers://C-2"); expect(result.raw.contents[0].uri).toBe("customers://C-2"); }); ``` **Hint:** Copy the shape of the ticket template: `@ResourceTemplate` with a `uriTemplate` and a `mimeType`, and a class that extends `ResourceContext<{ id: string }>` whose `execute()` returns the customer. **Solution:** The template covers every customer, including ones added later, and it's listed in `resources/templates/list`. FrontMCP labels each read with the URI it was for, so the content says which customer it's about. The solution also throws `ResourceNotFoundError` for unknown ids, which the checks don't require but a real server should. ### Challenge: Don't attach a ticket that doesn't exist Reading `tickets://T-9` "succeeds" with `{"error":"not found"}`, which a client would attach as if it were a ticket. Make the read fail instead, with an error that names the URI. Initial call configuration: ```js { resource: "tickets://T-9" } ``` ```ts ticket.resource.ts import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "One support ticket, with its title and status", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { return tickets.find((t) => t.id === id) ?? { error: "not found" }; } } ``` **Solution file (alternative to the starter):** ```ts ticket.resource.ts solution import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "One support ticket, with its title and status", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new ResourceNotFoundError(uri); return ticket; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ticket.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("reading `tickets://T-9` is an error", async ({ mcp }) => { expect(await mcp.resources.read("tickets://T-9")).toBeError(); }); test("the error names `tickets://T-9`", async ({ mcp }) => { const result = await mcp.resources.read("tickets://T-9"); expect(result.error?.message ?? "").toContain("tickets://T-9"); }); test("`tickets://T-1` still reads", async ({ mcp }) => { const result = await mcp.resources.read("tickets://T-1"); expect(result).not.toBeError(); expect(result.json()).toMatchObject({ id: "T-1", title: "Cannot log in" }); }); ``` **Hint:** `ResourceNotFoundError` is exported from `@frontmcp/sdk` and takes the URI. Throw it when there's no ticket. **Solution:** Throwing `ResourceNotFoundError(uri)` turns the read into a `-32602` JSON-RPC error with the message `Resource not found: tickets://T-9`. The client gets no `contents`, so there's nothing to attach by mistake. --- # Reusable Prompts > What a prompt is and who picks it, how to declare required and optional arguments, return several messages, and put ticket data into a prompt. Source: https://frontmcp.dev/learn/reusable-prompts [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A **prompt** is a message template that the user picks, usually from a slash menu in their client. It's the third kind of MCP capability: the model decides when to call a tool, the application decides which resources to read, and the user decides when to run a prompt. Prompts are how a FrontMCP server ships the instructions that work best with it, so nobody has to write them from memory. **You will learn** - What a prompt is, and how it differs from tools and resources - How to declare a `@Prompt` with required and optional arguments - How to put a ticket's data into a prompt as an embedded resource - How to return several messages, including an example exchange - How clients show prompts to the people using them ## A workflow the user starts Every support agent triages tickets a little differently. One asks the model for a priority, another for a team, a third forgets to ask for a reply at all. When there's a way that works, put it on the server as a prompt: Initial call configuration: ```js { prompt: "triage", arguments: {} } ``` ```ts triage.prompt.ts import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "triage", title: "Triage a ticket", description: "Suggest a priority, an owning team and a first reply for a support ticket", }) export class Triage extends PromptContext { async execute(): Promise { return { messages: [ { role: "user", content: { type: "text", text: "Triage the support ticket I paste next. Suggest a priority (low, normal, high or urgent), the team that should own it, and a two-sentence first reply to the customer.", }, }, ], }; } } ``` Open the **Call** tab. The page sent `prompts/get`, and what came back is a list of **messages**, not an answer. Getting a prompt doesn't run the model. The client puts these messages into the conversation as if the user had typed them, and the model replies from there, calling your tools if it needs to. A `@Prompt` has: 1. **`name`**, what clients use to get it. Like tool names, use `snake_case`. 2. **`title`** and **`description`**, what the user sees in the client's menu. Unlike a tool's description, these are written mostly for people. 3. **`arguments`**, the values the user fills in. This one has none yet, so it leaves the option out. 4. **The class**, which extends `PromptContext` and returns `{ messages }` from `execute()`. Each message has a `role` (`"user"` or `"assistant"`) and one piece of `content`. The [`@Prompt` reference](https://frontmcp.dev/reference/sdk/prompt) lists every option. So the three kinds of capability differ in who decides to use them: | | Tool | Resource | Prompt | | --- | --- | --- | --- | | Who decides | The model | The application, often because the user attached it | The user | | Identified by | A name | A URI | A name | | Used with | `tools/call` | `resources/read` | `prompts/get` | | Gives back | A result for the model | Content for the conversation | Messages to start the conversation with | > **Note** > > A prompt that's one user message can return just its text. FrontMCP wraps a string in a `user` message, so this sends the same `messages` as the example above: > > Initial call configuration: > > ```js > { prompt: "triage", arguments: {} } > ``` > > ```ts triage.prompt.ts > import { Prompt, PromptContext } from "@frontmcp/sdk"; > > @Prompt({ > name: "triage", > title: "Triage a ticket", > description: "Suggest a priority, an owning team and a first reply for a support ticket", > }) > export class Triage extends PromptContext { > async execute() { > return "Triage the support ticket I paste next. Suggest a priority (low, normal, high or urgent), the team that should own it, and a two-sentence first reply to the customer."; > } > } > ``` > > The examples in this lesson return the full shape, and declare `execute()` as returning `Promise`. That's optional, but it makes TypeScript check each message's `role` and `content` as you write them. ## Arguments The prompt above makes the user paste the ticket in a second message. It's easier to ask for the ticket id up front: Initial call configuration: ```js { prompt: "triage_ticket", arguments: { id: "T-1", language: "French" } } ``` ```ts triage.prompt.ts import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "triage_ticket", title: "Triage a ticket", description: "Suggest a priority, an owning team and a first reply for one support ticket", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "language", description: "Language for the reply to the customer. Defaults to English." }, ], }) export class TriageTicket extends PromptContext { async execute({ id, language }: { id: string; language?: string }): Promise { return { messages: [ { role: "user", content: { type: "text", text: `Look up ticket ${id} with get_ticket, then triage it. Suggest a priority (low, normal, high or urgent), the team that should own it, and a two-sentence first reply in ${language ?? "English"}.`, }, }, ], }; } } ``` Each argument has a `name`, a `description` for the person filling it in, and `required`: - **Required arguments** must be sent. Clients ask for them before they send `prompts/get`, and FrontMCP rejects a request without them. - **Optional arguments** can be left out. A missing one is `undefined` in `execute()`, so give it a default, like `language ?? "English"`. Here is the same prompt, requested without an `id`: Initial call configuration: ```js { prompt: "triage_ticket", arguments: {} } ``` ```ts triage.prompt.ts import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "triage_ticket", title: "Triage a ticket", description: "Suggest a priority, an owning team and a first reply for one support ticket", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "language", description: "Language for the reply to the customer. Defaults to English." }, ], }) export class TriageTicket extends PromptContext { async execute({ id, language }: { id: string; language?: string }): Promise { return { messages: [ { role: "user", content: { type: "text", text: `Look up ticket ${id} with get_ticket, then triage it. Suggest a priority (low, normal, high or urgent), the team that should own it, and a two-sentence first reply in ${language ?? "English"}.`, }, }, ], }; } } ``` The request fails with a JSON-RPC error, code `-32602` (invalid params) and the message `Missing required argument: id`, and `execute()` never runs. That's the only check FrontMCP makes. Prompt arguments are plain strings in MCP, with no schema like a tool's `inputSchema`, so an id like `banana` gets through to your code. If a value matters, check it yourself. ## Putting the ticket in the prompt "Look up ticket T-1 with get_ticket" leaves a step to the model: it has to call the tool before it can start. Since the prompt runs on your server, it can look the ticket up itself and send the data along. The clearest way to send data is as an **embedded resource**: a message whose content is a resource, with a URI, instead of text: Initial call configuration: ```js { prompt: "triage_ticket", arguments: { id: "T-2" } } ``` ```ts triage.prompt.ts active import { Prompt, PromptContext, PublicMcpError, type GetPromptResult } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Prompt({ name: "triage_ticket", title: "Triage a ticket", description: "Suggest a priority, an owning team and a first reply for one support ticket", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "language", description: "Language for the reply to the customer. Defaults to English." }, ], }) export class TriageTicket extends PromptContext { async execute({ id, language }: { id: string; language?: string }): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return { messages: [ { role: "user", content: { type: "resource", resource: { uri: `tickets://${ticket.id}`, mimeType: "application/json", text: JSON.stringify(ticket) }, }, }, { role: "user", content: { type: "text", text: `Triage the ticket above. Suggest a priority (low, normal, high or urgent), the team that should own it, and a two-sentence first reply in ${language ?? "English"}.`, }, }, ], }; } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets = [ { id: "T-1", title: "Cannot log in", status: "open", customer: "Acme Corp" }, { id: "T-2", title: "Invoice total is wrong", status: "closed", customer: "Globex" }, { id: "T-3", title: "Login link expired", status: "open", customer: "Acme Corp" }, ]; get(id: string) { return this.tickets.find((t) => t.id === id); } } ``` ```ts ticket.resource.ts import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "One support ticket", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new ResourceNotFoundError(uri); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } ``` ```ts triage.test.ts import { test, expect } from "@frontmcp/testing"; test("the ticket arrives as an embedded resource", async ({ mcp }) => { const prompt = await mcp.prompts.get("triage_ticket", { id: "T-2" }); expect(prompt).toHaveMessages(2); expect(prompt.messages[0].content).toMatchObject({ type: "resource", resource: { uri: "tickets://T-2", mimeType: "application/json" }, }); }); test("it's the same data as reading tickets://T-2", async ({ mcp }) => { const prompt = await mcp.prompts.get("triage_ticket", { id: "T-2" }); const read = await mcp.resources.read("tickets://T-2"); expect(JSON.parse(prompt.messages[0].content.resource.text)).toEqual(read.json()); }); test("an unknown ticket is an error the user can read", async ({ mcp }) => { const prompt = await mcp.prompts.get("triage_ticket", { id: "T-9" }); expect(prompt).toBeError(-32602); expect(prompt.error.message).toBe("There's no ticket T-9."); }); ``` A few things changed: 1. **The prompt gets the ticket from a provider.** `PromptContext` has `this.get()`, like tools and resources, so the prompt and the `tickets://{id}` template read the same `TicketStore`. 2. **The first message is the ticket itself**, as `{ type: "resource", resource: { uri, mimeType, text } }`. The URI says where the data came from, and it's the same URI the [ticket template](https://frontmcp.dev/learn/exposing-data-with-resources#a-family-of-resources-with-a-template) serves. Clients can show it as an attached ticket instead of a wall of JSON the user seems to have typed, and the model can tell data apart from instructions. 3. **The instructions come second**, as text, and refer to "the ticket above". 4. **An unknown id fails.** `throw new PublicMcpError(...)` turns into a JSON-RPC error, code `-32602`, whose message is yours, so the client can tell the user that `T-9` doesn't exist. Open the **Tests** tab to see all three. > **Pitfall: Throw PublicMcpError, not a plain Error** > > `PublicMcpError` is for messages the user should read. A plain `Error` means the server failed: > > Initial call configuration: > > ```js > { prompt: "triage_ticket", arguments: { id: "T-9" } } > ``` > > ```ts triage.prompt.ts > import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; > > const tickets = [{ id: "T-1", title: "Cannot log in" }]; > > @Prompt({ name: "triage_ticket", arguments: [{ name: "id", required: true }] }) > export class TriageTicket extends PromptContext { > async execute({ id }: { id: string }): Promise { > const ticket = tickets.find((t) => t.id === id); > // 🚩 A server failure, as far as the client can tell > if (!ticket) throw new Error(`There's no ticket ${id}.`); > return { messages: [{ role: "user", content: { type: "text", text: `Triage ticket ${ticket.id}: ${ticket.title}` } }] }; > } > } > ``` > > The client gets code `-32603`, an internal error, and `Prompt execution failed: There's no ticket T-9.` That's in development, which is how the Playground runs. With `NODE_ENV=production`, FrontMCP hides the message and sends `Internal FrontMCP error. Please contact support with error ID: …` instead, so the user never learns what was wrong. ## Several messages A prompt can return more than one message, and they don't all have to be from the user. A message with `role: "assistant"` is a turn the model appears to have already taken. The most useful thing to do with that is show the model an example of the answer you want: Initial call configuration: ```js { prompt: "triage_ticket", arguments: { id: "T-3" } } ``` ```ts triage.prompt.ts active import { Prompt, PromptContext, PublicMcpError, type GetPromptResult } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; const instructions = "Triage support tickets. Answer with a priority (low, normal, high or urgent), the team that should own the ticket, and a two-sentence reply to the customer."; const exampleTicket = { id: "T-0", title: "Password reset email never arrives", status: "open", customer: "Initech" }; const exampleAnswer = [ "Priority: high", "Team: Accounts", "Reply: Sorry the reset email hasn't reached you. We've sent a fresh link, and if it isn't in your inbox within ten minutes, please check your spam folder.", ].join("\n"); @Prompt({ name: "triage_ticket", title: "Triage a ticket", description: "Suggest a priority, an owning team and a first reply for one support ticket", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class TriageTicket extends PromptContext { async execute({ id }: { id: string }): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return { messages: [ { role: "user", content: { type: "text", text: `${instructions}\n\n${JSON.stringify(exampleTicket)}` } }, { role: "assistant", content: { type: "text", text: exampleAnswer } }, { role: "user", content: { type: "resource", resource: { uri: `tickets://${ticket.id}`, mimeType: "application/json", text: JSON.stringify(ticket) }, }, }, ], }; } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets = [ { id: "T-1", title: "Cannot log in", status: "open", customer: "Acme Corp" }, { id: "T-2", title: "Invoice total is wrong", status: "closed", customer: "Globex" }, { id: "T-3", title: "Login link expired", status: "open", customer: "Acme Corp" }, ]; get(id: string) { return this.tickets.find((t) => t.id === id); } } ``` The client adds all three messages to the conversation in order: the instructions with a made-up ticket, a model turn that answers it in exactly the format you want, and then the real ticket. The model continues the pattern. An example like this pins down the format far better than describing it, and it costs you one extra message. ## How clients show prompts Clients discover prompts with `prompts/list`, and most show them as slash commands or in a menu of actions. When the user picks one, the client asks for its arguments, then sends `prompts/get` with the answers and puts the messages it gets back into the conversation. What the user sees comes from your metadata: - **`title`** is the label in the menu. Without one, clients fall back to `name`. - **`description`** says what the prompt will do, so the user can pick the right one. - **Each argument's `description`** is the hint next to its input, and `required` decides whether the user can skip it. The Playground works the same way. On the Capabilities tab, a prompt card lists its arguments, with `?` after optional ones, and the Call tab turns them into a form. ### What does the client actually receive? For the `triage_ticket` prompt with an `id` and a `language`, `prompts/list` returns: ```json { "prompts": [ { "name": "triage_ticket", "title": "Triage a ticket", "description": "Suggest a priority, an owning team and a first reply for one support ticket", "arguments": [ { "name": "id", "description": "Ticket id, like T-1", "required": true }, { "name": "language", "description": "Language for the reply to the customer. Defaults to English." } ] } ] } ``` An argument you didn't mark `required` is sent without the field, which MCP reads as optional. The client then sends `prompts/get` with `{ "name": "triage_ticket", "arguments": { "id": "T-2" } }`, and gets back the `messages` exactly as `execute()` returned them. If you don't return a `description` of your own, FrontMCP adds the prompt's. Open the Wire tab of any example above to see the full exchange. ## Recap - A prompt is a message template the user picks. Getting it returns messages for the conversation; it doesn't run the model. - A `@Prompt` has a `name`, a `title` and `description` for people, `arguments`, and a class that extends `PromptContext` and returns `{ messages }`. - Required arguments must be sent, or `prompts/get` fails with `-32602`. Optional ones are `undefined` when left out. FrontMCP checks nothing else about them. - Put data in a prompt as an embedded resource (`type: "resource"`) with a URI, and get it from the same provider your resources use. - Messages can alternate between `user` and `assistant`. An example exchange shows the model the answer format you want. - Throw `PublicMcpError` for problems the user should see. A plain `Error` is a server failure, and production hides its message. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Add an optional tone The `draft_reply` prompt always asks for a friendly reply. Some customers need a formal one. Add an optional `tone` argument, with a description, that can be `friendly` or `formal`, and use `friendly` when it's left out. Initial call configuration: ```js { prompt: "draft_reply", arguments: { id: "T-1" } } ``` ```ts draft-reply.prompt.ts import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "draft_reply", title: "Draft a reply", description: "Draft a reply to the customer on a ticket", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class DraftReply extends PromptContext { async execute({ id }: { id: string }): Promise { return { messages: [ { role: "user", content: { type: "text", text: `Look up ticket ${id} with get_ticket and draft a friendly reply to the customer.` }, }, ], }; } } ``` **Solution file (alternative to the starter):** ```ts draft-reply.prompt.ts solution import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "draft_reply", title: "Draft a reply", description: "Draft a reply to the customer on a ticket", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "tone", description: "friendly or formal. Defaults to friendly." }, ], }) export class DraftReply extends PromptContext { async execute({ id, tone }: { id: string; tone?: string }): Promise { return { messages: [ { role: "user", content: { type: "text", text: `Look up ticket ${id} with get_ticket and draft a ${tone ?? "friendly"} reply to the customer.` }, }, ], }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts draft-reply.test.ts hidden import { test, expect } from "@frontmcp/testing"; const textOf = (prompt: { messages: any[] }) => prompt.messages.map((m) => m.content.text ?? "").join("\n"); test("`tone` is listed, with a description, and is optional", async ({ mcp }) => { const prompt = (await mcp.prompts.list()).find((p: any) => p.name === "draft_reply"); const tone = prompt?.arguments?.find((a: any) => a.name === "tone"); expect(tone).toBeDefined(); expect(tone?.description?.length ?? 0).toBeGreaterThan(5); expect(tone?.required ?? false).toBe(false); }); test("without `tone`, it asks for a friendly reply", async ({ mcp }) => { const prompt = await mcp.prompts.get("draft_reply", { id: "T-1" }); expect(prompt).not.toBeError(); expect(textOf(prompt)).toContain("friendly"); }); test("`tone: formal` asks for a formal reply", async ({ mcp }) => { const prompt = await mcp.prompts.get("draft_reply", { id: "T-1", tone: "formal" }); expect(textOf(prompt)).toContain("formal"); expect(textOf(prompt)).not.toContain("friendly"); }); ``` **Hint:** Add a second entry to `arguments` without `required: true`. In `execute()`, it arrives as `undefined` when the user leaves it out. **Solution:** `tone` has no `required`, so clients let the user skip it, and `prompts/list` doesn't mark it required. `tone ?? "friendly"` supplies the default. The prompt passes the value through as text, which is fine here: the model reads it, and nothing breaks if a user types something else. ### Challenge: Show the model an example The triage answers come back in a different format every time. Turn this prompt into three messages: the instructions with the example ticket (from the user), the example answer (from the assistant), and then the real ticket (from the user), as text like `Ticket T-3: Login link expired`. Initial call configuration: ```js { prompt: "triage_ticket", arguments: { id: "T-3" } } ``` ```ts triage.prompt.ts import { Prompt, PromptContext, PublicMcpError, type GetPromptResult } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-2", title: "Invoice total is wrong" }, { id: "T-3", title: "Login link expired" }, ]; const instructions = "Triage support tickets. Answer with a priority (low, normal, high or urgent) and the team that should own the ticket."; const exampleTicket = "Ticket T-0: Password reset email never arrives"; const exampleAnswer = "Priority: high\nTeam: Accounts"; @Prompt({ name: "triage_ticket", title: "Triage a ticket", description: "Suggest a priority and an owning team for one support ticket", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class TriageTicket extends PromptContext { async execute({ id }: { id: string }): Promise { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return { messages: [ { role: "user", content: { type: "text", text: `${instructions}\n\nTicket ${ticket.id}: ${ticket.title}` } }, ], }; } } ``` **Solution file (alternative to the starter):** ```ts triage.prompt.ts solution import { Prompt, PromptContext, PublicMcpError, type GetPromptResult } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-2", title: "Invoice total is wrong" }, { id: "T-3", title: "Login link expired" }, ]; const instructions = "Triage support tickets. Answer with a priority (low, normal, high or urgent) and the team that should own the ticket."; const exampleTicket = "Ticket T-0: Password reset email never arrives"; const exampleAnswer = "Priority: high\nTeam: Accounts"; @Prompt({ name: "triage_ticket", title: "Triage a ticket", description: "Suggest a priority and an owning team for one support ticket", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class TriageTicket extends PromptContext { async execute({ id }: { id: string }): Promise { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return { messages: [ { role: "user", content: { type: "text", text: `${instructions}\n\n${exampleTicket}` } }, { role: "assistant", content: { type: "text", text: exampleAnswer } }, { role: "user", content: { type: "text", text: `Ticket ${ticket.id}: ${ticket.title}` } }, ], }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts triage.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("it returns three messages: user, assistant, user", async ({ mcp }) => { const prompt = await mcp.prompts.get("triage_ticket", { id: "T-3" }); expect(prompt).toHaveMessages(3); expect(prompt.messages.map((m: any) => m.role)).toEqual(["user", "assistant", "user"]); }); test("the first message has the instructions and the example ticket", async ({ mcp }) => { const [first] = (await mcp.prompts.get("triage_ticket", { id: "T-3" })).messages; expect(first.content.text).toContain("Triage support tickets"); expect(first.content.text).toContain("Password reset email never arrives"); }); test("the assistant message is the example answer", async ({ mcp }) => { const [, second] = (await mcp.prompts.get("triage_ticket", { id: "T-3" })).messages; expect(second.content.text).toBe("Priority: high\nTeam: Accounts"); }); test("the last message is the real ticket", async ({ mcp }) => { const [, , third] = (await mcp.prompts.get("triage_ticket", { id: "T-3" })).messages; expect(third.content.text).toContain("Login link expired"); expect(third.content.text).not.toContain("Password reset"); }); ``` **Hint:** `messages` is an array. Each entry has its own `role` and `content`. `exampleTicket` and `exampleAnswer` are already defined; they just aren't used yet. **Solution:** The model sees a finished example exchange before it gets the real ticket, so it answers in the same two lines. The instructions still say what to do; the example shows what the answer looks like. ### Challenge: Attach the ticket instead of pasting it This prompt pastes the ticket's JSON into the instructions. Send it as an embedded resource instead, with the URI `tickets://` and the `application/json` type, followed by the instructions as a separate text message. Initial call configuration: ```js { prompt: "summarize_ticket", arguments: { id: "T-2" } } ``` ```ts summarize.prompt.ts import { Prompt, PromptContext, PublicMcpError, type GetPromptResult } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Prompt({ name: "summarize_ticket", title: "Summarize a ticket", description: "Summarize a ticket for a teammate who's taking it over", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class SummarizeTicket extends PromptContext { async execute({ id }: { id: string }): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return { messages: [ { role: "user", content: { type: "text", text: `Here is a ticket: ${JSON.stringify(ticket)}\n\nSummarize it in three bullet points for a teammate who's taking it over.`, }, }, ], }; } } ``` **Solution file (alternative to the starter):** ```ts summarize.prompt.ts solution import { Prompt, PromptContext, PublicMcpError, type GetPromptResult } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Prompt({ name: "summarize_ticket", title: "Summarize a ticket", description: "Summarize a ticket for a teammate who's taking it over", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class SummarizeTicket extends PromptContext { async execute({ id }: { id: string }): Promise { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return { messages: [ { role: "user", content: { type: "resource", resource: { uri: `tickets://${ticket.id}`, mimeType: "application/json", text: JSON.stringify(ticket) }, }, }, { role: "user", content: { type: "text", text: "Summarize the ticket above in three bullet points for a teammate who's taking it over." }, }, ], }; } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets = [ { id: "T-1", title: "Cannot log in", status: "open", customer: "Acme Corp" }, { id: "T-2", title: "Invoice total is wrong", status: "closed", customer: "Globex" }, ]; get(id: string) { return this.tickets.find((t) => t.id === id); } } ``` **Hidden fixture/test file (runs with the example):** ```ts summarize.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the first message is the ticket, as a resource at `tickets://T-2`", async ({ mcp }) => { const prompt = await mcp.prompts.get("summarize_ticket", { id: "T-2" }); expect(prompt.messages[0]?.content).toMatchObject({ type: "resource", resource: { uri: "tickets://T-2", mimeType: "application/json" }, }); expect(JSON.parse(prompt.messages[0].content.resource.text)).toMatchObject({ id: "T-2", title: "Invoice total is wrong" }); }); test("the instructions follow as text, without the JSON", async ({ mcp }) => { const prompt = await mcp.prompts.get("summarize_ticket", { id: "T-2" }); expect(prompt).toHaveMessages(2); expect(prompt.messages[1].content.type).toBe("text"); expect(prompt.messages[1].content.text).toContain("Summarize"); expect(prompt.messages[1].content.text).not.toContain("Invoice total is wrong"); }); test("an unknown ticket is still an error", async ({ mcp }) => { expect(await mcp.prompts.get("summarize_ticket", { id: "T-9" })).toBeError(); }); ``` **Hint:** An embedded resource is `{ type: "resource", resource: { uri, mimeType, text } }` as a message's `content`. Each message has one piece of content, so the ticket and the instructions become two messages. **Solution:** The ticket now travels as data with an address, `tickets://T-2`, and the instructions are only instructions. A client can show the ticket as an attachment, and the model doesn't have to find where the JSON starts and ends. --- # Grouping Capabilities into Apps > How @App groups tools, resources, prompts and providers, how a @FrontMcp server composes several apps, what happens when their names collide, and how apps share a provider. Source: https://frontmcp.dev/learn/grouping-capabilities-into-apps [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 As a server grows, its tools, resources and prompts fall into areas: tickets, billing, a knowledge base. A FrontMCP **app** (`@App`) is one of those areas, with the capabilities that belong to it and the providers they use. A **server** (`@FrontMcp`) puts several apps behind one endpoint. Clients never see the apps, only one list of everything, so splitting a server into apps is mostly about organising your code. It does change two things, and this lesson covers both: what happens when names collide, and which providers each app can reach. **You will learn** - What an `@App` groups, and how a `@FrontMcp` server lists apps - What clients see when a server has several apps - What FrontMCP does when two apps use the same name - Why a provider registered on one app isn't available to another, and how to share it - When it's worth splitting a server into apps ## One app Here is the help desk from the previous lessons, laid out as a small project: a server in `main.ts`, and one app with its tools, resource, prompt and provider in its own folder. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./apps/tickets/tickets.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp], }) export default class HelpDeskServer {} ``` ```ts apps/tickets/tickets.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket, SearchTickets } from "./tools"; import { TicketResource } from "./ticket.resource"; import { TriageTicket } from "./triage.prompt"; import { TicketStore } from "./ticket-store"; @App({ id: "tickets", name: "Tickets", description: "Search, read and triage support tickets", tools: [SearchTickets, GetTicket], resources: [TicketResource], prompts: [TriageTicket], providers: [TicketStore], }) export class TicketsApp {} ``` ```ts apps/tickets/tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title", inputSchema: { query: z.string().min(2) }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` ```ts apps/tickets/ticket.resource.ts import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @ResourceTemplate({ name: "ticket", uriTemplate: "tickets://{id}", mimeType: "application/json", description: "One support ticket", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) throw new ResourceNotFoundError(uri); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } ``` ```ts apps/tickets/triage.prompt.ts import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "triage_ticket", title: "Triage a ticket", description: "Suggest a priority and an owning team for one ticket", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class TriageTicket extends PromptContext { async execute({ id }: { id: string }): Promise { return { messages: [ { role: "user", content: { type: "text", text: `Read ticket ${id} with get_ticket, then suggest a priority and an owning team.` } }, ], }; } } ``` ```ts apps/tickets/ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; status: "open" | "closed" }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, { id: "T-4", title: "Charged twice in March", status: "open" }, ]; search(query: string) { return this.tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())); } get(id: string) { return this.tickets.find((t) => t.id === id); } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` Two decorators hold it together: - **`@App`** lists what belongs to one area: its `tools`, `resources`, `prompts`, and the `providers` they get with `this.get()`. `id` is a short, stable identifier that FrontMCP uses to tell apps apart, and `name` and `description` are for people reading your code and logs. A capability that isn't listed in an app doesn't exist as far as clients are concerned. - **`@FrontMcp`** is the server. It lists `apps` and holds server-wide settings like `info`, which clients see as the server's name and version. Open the **Capabilities** tab. It shows two tools, a template and a prompt, and nothing about an app called Tickets. MCP has no idea of apps: `tools/list`, `resources/templates/list` and `prompts/list` each return one flat list. (The [`@App`](https://frontmcp.dev/reference/sdk/app) and [`@FrontMcp`](https://frontmcp.dev/reference/sdk/frontmcp) references list every option.) ## A server with several apps Billing is a different area, with its own data and its own tools, so it gets its own app. The server lists both: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-7" } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./apps/tickets/tickets.app"; import { BillingApp } from "./apps/billing/billing.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], }) export default class HelpDeskServer {} ``` ```ts apps/billing/billing.app.ts import { App } from "@frontmcp/sdk"; import { GetInvoice, RefundInvoice } from "./tools"; @App({ id: "billing", name: "Billing", description: "Look up and refund invoices", tools: [GetInvoice, RefundInvoice], }) export class BillingApp {} ``` ```ts apps/billing/tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const invoices = [ { id: "INV-7", customer: "Acme Corp", total: 1200, status: "paid", ticket: "T-4" }, { id: "INV-8", customer: "Globex", total: 300, status: "paid", ticket: null }, ]; @Tool({ name: "get_invoice", description: "Get one invoice by its id, like INV-7", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const invoice = invoices.find((i) => i.id === id); if (!invoice) this.fail(new PublicMcpError(`There's no invoice ${id}.`)); return invoice; } } @Tool({ name: "refund_invoice", description: "Refund an invoice in full", inputSchema: { id: z.string() }, }) export class RefundInvoice extends ToolContext { async execute({ id }: { id: string }) { const invoice = invoices.find((i) => i.id === id); if (!invoice) this.fail(new PublicMcpError(`There's no invoice ${id}.`)); invoice.status = "refunded"; return invoice; } } ``` ```ts apps/tickets/tickets.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket, SearchTickets } from "./tools"; import { TicketStore } from "./ticket-store"; @App({ id: "tickets", name: "Tickets", description: "Search and read support tickets", tools: [SearchTickets, GetTicket], providers: [TicketStore], }) export class TicketsApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts apps/tickets/tools.ts hidden import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title", inputSchema: { query: z.string().min(2) }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` **Hidden fixture/test file (runs with the example):** ```ts apps/tickets/ticket-store.ts hidden import { Provider, ProviderScope } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; status: "open" | "closed" }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, { id: "T-4", title: "Charged twice in March", status: "open" }, ]; search(query: string) { return this.tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())); } get(id: string) { return this.tickets.find((t) => t.id === id); } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` ```ts server.test.ts import { test, expect } from "@frontmcp/testing"; test("clients see one list, with every tool under its own name", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name); expect(names).toEqual(["get_invoice", "get_ticket", "refund_invoice", "search_tickets"]); }); test("each tool still works from its own app", async ({ mcp }) => { expect((await mcp.tools.call("get_invoice", { id: "INV-7" })).json()).toMatchObject({ total: 1200 }); expect((await mcp.tools.call("get_ticket", { id: "T-4" })).json()).toMatchObject({ status: "open" }); }); ``` The **Tests** tab shows what a client sees: four tools in one list, each under the name it was declared with. Nothing tells the client which app a tool came from. For a client, this server is no different from one app with four tools. ## When two apps use the same name Each app is written on its own, often by a different person, so it's easy for two of them to pick the same name. Say both teams called their search tool `search`: Initial call configuration: ```js { tool: "search", arguments: { query: "log" } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./apps/tickets.app"; import { BillingApp } from "./apps/billing.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], }) export default class HelpDeskServer {} ``` ```ts apps/tickets.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-3", title: "Login link expired" }, ]; @Tool({ name: "search", description: "Search support tickets by title", inputSchema: { query: z.string() } }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } @App({ id: "tickets", name: "Tickets", tools: [SearchTickets] }) export class TicketsApp {} ``` ```ts apps/billing.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; const invoices = [ { id: "INV-7", customer: "Acme Corp" }, { id: "INV-8", customer: "Globex" }, ]; @Tool({ name: "search", description: "Search invoices by customer name", inputSchema: { query: z.string() } }) export class SearchInvoices extends ToolContext { async execute({ query }: { query: string }) { return { invoices: invoices.filter((i) => i.customer.toLowerCase().includes(query.toLowerCase())) }; } } @App({ id: "billing", name: "Billing", tools: [SearchInvoices] }) export class BillingApp {} ``` ```ts collision.test.ts import { test, expect } from "@frontmcp/testing"; test("both tools are renamed to `:search`", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name); expect(names).toEqual(["billing:search", "tickets:search"]); }); test("neither has a title to tell them apart", async ({ mcp }) => { const titles = (await mcp.tools.list()).map((t: { title?: string }) => t.title); expect(titles).toEqual([undefined, undefined]); }); test("each can be called by its new name", async ({ mcp }) => { expect((await mcp.tools.call("billing:search", { query: "acme" })).json()).toHaveProperty("invoices"); expect((await mcp.tools.call("tickets:search", { query: "log" })).json()).toHaveProperty("tickets"); }); test("plain `search` still works, and reaches the first app in `apps`", async ({ mcp }) => { expect((await mcp.tools.call("search", { query: "log" })).json()).toHaveProperty("tickets"); }); ``` FrontMCP doesn't refuse to start. When a tool name appears in more than one app, it renames **every** tool with that name to `:`, and logs a warning about the conflict (look in the **Logs** tab). Names that don't collide are left alone. Open the **Tests** tab to see the result. That keeps each tool reachable, but it isn't a good place to stay: - **The names depend on what else is installed.** `search` was called `search` until the billing app arrived. Anything that referred to it by name, like a prompt that says "call search", now means something else. - **The old name still answers.** A client that calls plain `search` reaches the tool in the first app listed in `apps`, here the ticket search, with no error to say it was ambiguous. - **The model has only the prefixes and the descriptions to tell them apart.** Neither tool declared a `title`, so `tools/list` has none for them, and an app id like `billing` is a word you picked for your code, not for the model. The fix is to give tools names that are unique across the whole server, and that say what they search: `search_tickets` and `search_invoices`. Treat the prefixes as a warning, not as a way to namespace tools. > **Pitfall: Resource URIs are never renamed** > > FrontMCP can't rename a URI, because the URI is the address clients read. If two apps both serve `policy://sla`, the first app in `apps` serves it, and the other app's resource is neither listed nor read. FrontMCP logs a warning that names both (look in the **Logs** tab), and starts anyway: > > Initial call configuration: > > ```js > { resource: "policy://sla" } > ``` > > ```ts main.ts active > import { FrontMcp } from "@frontmcp/sdk"; > import { TicketsApp, BillingApp } from "./apps"; > > @FrontMcp({ > info: { name: "Help Desk", version: "1.0.0" }, > apps: [TicketsApp, BillingApp], > }) > export default class HelpDeskServer {} > ``` > > ```ts apps.ts > import { App, Resource, ResourceContext } from "@frontmcp/sdk"; > > @Resource({ name: "sla", uri: "policy://sla", mimeType: "text/markdown" }) > export class TicketsSla extends ResourceContext { > async execute(uri: string) { > return "# Support SLA\n\nFirst reply within 4 business hours."; > } > } > > @Resource({ name: "sla", uri: "policy://sla", mimeType: "text/markdown" }) > export class BillingSla extends ResourceContext { > async execute(uri: string) { > return "# Billing SLA\n\nRefunds are processed within 5 business days."; > } > } > > @App({ id: "tickets", name: "Tickets", resources: [TicketsSla] }) > export class TicketsApp {} > > @App({ id: "billing", name: "Billing", resources: [BillingSla] }) > export class BillingApp {} > ``` > > ```ts sla.test.ts > import { test, expect } from "@frontmcp/testing"; > > test("only the first app's resource is listed", async ({ mcp }) => { > const listed = (await mcp.resources.list()).map((r: { name: string; uri: string }) => [r.name, r.uri]); > expect(listed).toEqual([["sla", "policy://sla"]]); > }); > > test("reading the URI returns the first app's SLA, never the billing one", async ({ mcp }) => { > expect((await mcp.resources.read("policy://sla")).text()).toContain("Support SLA"); > }); > ``` > > Give each app its own URI scheme, like `tickets://sla` and `billing://sla`, so their addresses can't meet. ## Sharing a provider between apps When an invoice is refunded, the ticket that asked for the refund should close. So the billing app's `refund_invoice` needs the `TicketStore`, which belongs to the tickets app: Initial call configuration: ```js { tool: "refund_invoice", arguments: { id: "INV-7" } } ``` ```ts apps/billing/tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "../tickets/ticket-store"; const invoices = [ { id: "INV-7", customer: "Acme Corp", total: 1200, status: "paid", ticket: "T-4" }, { id: "INV-8", customer: "Globex", total: 300, status: "paid", ticket: null }, ]; @Tool({ name: "refund_invoice", description: "Refund an invoice in full, and close the ticket that asked for it", inputSchema: { id: z.string() }, }) export class RefundInvoice extends ToolContext { async execute({ id }: { id: string }) { const invoice = invoices.find((i) => i.id === id); if (!invoice) this.fail(new PublicMcpError(`There's no invoice ${id}.`)); invoice.status = "refunded"; if (invoice.ticket) this.get(TicketStore).close(invoice.ticket); return invoice; } } ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./apps/tickets/tickets.app"; import { BillingApp } from "./apps/billing/billing.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], }) export default class HelpDeskServer {} ``` ```ts apps/billing/billing.app.ts import { App } from "@frontmcp/sdk"; import { RefundInvoice } from "./tools"; @App({ id: "billing", name: "Billing", tools: [RefundInvoice] }) export class BillingApp {} ``` ```ts apps/tickets/tickets.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket } from "./tools"; import { TicketStore } from "./ticket-store"; @App({ id: "tickets", name: "Tickets", tools: [GetTicket], providers: [TicketStore] }) export class TicketsApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts apps/tickets/tools.ts hidden import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` ```ts apps/tickets/ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; status: "open" | "closed" }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, { id: "T-4", title: "Charged twice in March", status: "open" }, ]; get(id: string) { return this.tickets.find((t) => t.id === id); } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` The call fails with `Provider "TicketStore" is not available: not found in local or parent registries`. Importing the class isn't enough. A provider registered on an app is **private to that app**: FrontMCP looks for it in the calling tool's app, then in the server, and `TicketStore` is in neither place for a billing tool. Move it up to the server. Providers listed in `@FrontMcp({ providers })` are available to every app, and with `ProviderScope.GLOBAL` there's one instance for all of them: Initial call configuration: ```js { tool: "refund_invoice", arguments: { id: "INV-7" } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./apps/tickets/tickets.app"; import { BillingApp } from "./apps/billing/billing.app"; import { TicketStore } from "./shared/ticket-store"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], providers: [TicketStore], }) export default class HelpDeskServer {} ``` ```ts apps/tickets/tickets.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket } from "./tools"; @App({ id: "tickets", name: "Tickets", tools: [GetTicket] }) export class TicketsApp {} ``` ```ts apps/billing/billing.app.ts import { App } from "@frontmcp/sdk"; import { RefundInvoice } from "./tools"; @App({ id: "billing", name: "Billing", tools: [RefundInvoice] }) export class BillingApp {} ``` ```ts apps/billing/tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "../../shared/ticket-store"; const invoices = [ { id: "INV-7", customer: "Acme Corp", total: 1200, status: "paid", ticket: "T-4" }, { id: "INV-8", customer: "Globex", total: 300, status: "paid", ticket: null }, ]; @Tool({ name: "refund_invoice", description: "Refund an invoice in full, and close the ticket that asked for it", inputSchema: { id: z.string() }, }) export class RefundInvoice extends ToolContext { async execute({ id }: { id: string }) { const invoice = invoices.find((i) => i.id === id); if (!invoice) this.fail(new PublicMcpError(`There's no invoice ${id}.`)); invoice.status = "refunded"; if (invoice.ticket) this.get(TicketStore).close(invoice.ticket); return invoice; } } ``` **Hidden fixture/test file (runs with the example):** ```ts apps/tickets/tools.ts hidden import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "../../shared/ticket-store"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` ```ts shared/ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; status: "open" | "closed" }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, { id: "T-4", title: "Charged twice in March", status: "open" }, ]; get(id: string) { return this.tickets.find((t) => t.id === id); } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` ```ts refund.test.ts import { test, expect } from "@frontmcp/testing"; test("refunding INV-7 closes T-4, which the tickets app then sees", async ({ mcp }) => { expect((await mcp.tools.call("get_ticket", { id: "T-4" })).json()).toMatchObject({ status: "open" }); const refund = await mcp.tools.call("refund_invoice", { id: "INV-7" }); expect(refund).toBeSuccessful(); expect((await mcp.tools.call("get_ticket", { id: "T-4" })).json()).toMatchObject({ status: "closed" }); }); ``` The store moved to `shared/`, `TicketsApp` no longer lists it, and the server does. Both apps' tools get it with the same `this.get(TicketStore)`, and the **Tests** tab shows a refund in one app closing a ticket that the other app then reads as closed. > **Pitfall: Registering a provider in two apps makes two of them** > > It's tempting to fix the error by adding `TicketStore` to `BillingApp`'s `providers` as well. The error goes away, but each app now builds its own `TicketStore`, even with `ProviderScope.GLOBAL`. The refund closes T-4 in billing's copy, and the tickets app keeps saying it's open. The last challenge below starts from exactly this mistake. If apps need to share state, register the provider once, on the server. ## When to split into apps Apps are mostly for you: clients get the same flat list either way. Splitting changes two things at runtime, both covered above: providers registered on an app are private to it, and names that collide across apps get prefixed. That suggests when to split and when not to: - **Split along the areas of your domain.** Tickets, billing and a knowledge base each have their own data, their own services and their own words for things. An app per area keeps each one's providers out of the others' reach. - **Split where ownership splits.** If a different team owns billing, its app is the unit they change, review and test, and it's a class another `@FrontMcp` server could list too. - **Put what several apps need on the server.** A ticket store that billing also uses, a clock, an HTTP client with your credentials: register it in `@FrontMcp({ providers })` once. - **Don't split just to organise files.** Folders do that. Two apps that share everything are one app with extra wiring. - **Keep names unique across the server.** The model sees one list, so `search_tickets` and `search_invoices` are better than two `search` tools in two apps. ## Recap - `@App` groups the tools, resources, prompts and providers of one area. `@FrontMcp` is the server that lists the apps and holds settings like `info`. - Clients don't see apps. `tools/list`, `resources/list` and `prompts/list` each return one flat list across all apps. - When two apps use the same tool name, FrontMCP renames each to `:` and logs a warning. The bare name still reaches the first app. Pick names that are unique across the server instead. - Resource URIs are never renamed. When two apps serve the same URI, only the first app's resource is listed and read. Give each app its own scheme. - A provider registered on an app is private to that app. Register providers that several apps need on the server, once. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Register the billing app The billing app is written, but nobody can call `get_invoice`. Add the app to the server, and name the server `Help Desk`. ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./apps/tickets.app"; @FrontMcp({ info: { name: "Untitled", version: "1.0.0" }, apps: [TicketsApp], }) export default class HelpDeskServer {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./apps/tickets.app"; import { BillingApp } from "./apps/billing.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], }) export default class HelpDeskServer {} ``` ```ts apps/tickets.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @App({ id: "tickets", name: "Tickets", tools: [GetTicket] }) export class TicketsApp {} ``` ```ts apps/billing.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_invoice", description: "Get one invoice by its id, like INV-7", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, customer: "Acme Corp", total: 1200 }; } } @App({ id: "billing", name: "Billing", tools: [GetInvoice] }) export class BillingApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts server.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`get_invoice` is listed", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("get_invoice"); }); test("`get_ticket` is still listed", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("get_ticket"); }); test("the server is called Help Desk", async ({ mcp }) => { const response = await mcp.raw.request({ method: "tools/list" }); expect(response.result._meta["io.modelcontextprotocol/serverInfo"].name).toBe("Help Desk"); }); ``` **Hint:** An app only exists for clients once it's in the server's `apps` array. Import it into `main.ts` first. **Solution:** `apps: [TicketsApp, BillingApp]` puts both apps behind the server, and their tools appear in one list. `info.name` is what clients see as the server's name: FrontMCP sends it in the `_meta` of every result. ### Challenge: Fix a name collision Both apps call their search tool `search`, so clients see `billing:search` and `tickets:search`. Rename them so each has a clear name of its own, `search_tickets` and `search_invoices`, and no tool is prefixed. ```ts apps.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-3", title: "Login link expired" }, ]; const invoices = [ { id: "INV-7", customer: "Acme Corp" }, { id: "INV-8", customer: "Globex" }, ]; @Tool({ name: "search", description: "Search support tickets by title", inputSchema: { query: z.string() } }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } @Tool({ name: "search", description: "Search invoices by customer name", inputSchema: { query: z.string() } }) export class SearchInvoices extends ToolContext { async execute({ query }: { query: string }) { return { invoices: invoices.filter((i) => i.customer.toLowerCase().includes(query.toLowerCase())) }; } } @App({ id: "tickets", name: "Tickets", tools: [SearchTickets] }) export class TicketsApp {} @App({ id: "billing", name: "Billing", tools: [SearchInvoices] }) export class BillingApp {} ``` **Solution file (alternative to the starter):** ```ts apps.ts solution import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-3", title: "Login link expired" }, ]; const invoices = [ { id: "INV-7", customer: "Acme Corp" }, { id: "INV-8", customer: "Globex" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by title", inputSchema: { query: z.string() } }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } @Tool({ name: "search_invoices", description: "Search invoices by customer name", inputSchema: { query: z.string() } }) export class SearchInvoices extends ToolContext { async execute({ query }: { query: string }) { return { invoices: invoices.filter((i) => i.customer.toLowerCase().includes(query.toLowerCase())) }; } } @App({ id: "tickets", name: "Tickets", tools: [SearchTickets] }) export class TicketsApp {} @App({ id: "billing", name: "Billing", tools: [SearchInvoices] }) export class BillingApp {} ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp, BillingApp } from "./apps"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], }) export default class HelpDeskServer {} ``` **Hidden fixture/test file (runs with the example):** ```ts names.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the tools are `search_invoices` and `search_tickets`", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name); expect(names).toEqual(["search_invoices", "search_tickets"]); }); test("`search_tickets` finds tickets", async ({ mcp }) => { const result = await mcp.tools.call("search_tickets", { query: "log" }); expect(result).toBeSuccessful(); expect(result.json().tickets.map((t: { id: string }) => t.id)).toEqual(["T-1", "T-3"]); }); test("`search_invoices` finds invoices", async ({ mcp }) => { const result = await mcp.tools.call("search_invoices", { query: "globex" }); expect(result).toBeSuccessful(); expect(result.json().invoices.map((i: { id: string }) => i.id)).toEqual(["INV-8"]); }); ``` **Hint:** The prefix only appears while two tools share a name. Change the `name` in each `@Tool`, not the app ids. **Solution:** With unique names there's no conflict, so FrontMCP leaves both names as declared. The names are also better for the model: `search_invoices` says what it searches before the model reads a word of the description. ### Challenge: Give each app its own URI scheme Both apps serve their SLA at `policy://sla`, so the billing SLA is never listed or read. Move them to `tickets://sla` and `billing://sla`. ```ts apps.ts import { App, Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "sla", uri: "policy://sla", mimeType: "text/markdown", description: "How fast support replies" }) export class TicketsSla extends ResourceContext { async execute(uri: string) { return "# Support SLA\n\nFirst reply within 4 business hours."; } } @Resource({ name: "sla", uri: "policy://sla", mimeType: "text/markdown", description: "How fast refunds are paid" }) export class BillingSla extends ResourceContext { async execute(uri: string) { return "# Billing SLA\n\nRefunds are processed within 5 business days."; } } @App({ id: "tickets", name: "Tickets", resources: [TicketsSla] }) export class TicketsApp {} @App({ id: "billing", name: "Billing", resources: [BillingSla] }) export class BillingApp {} ``` **Solution file (alternative to the starter):** ```ts apps.ts solution import { App, Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "support-sla", uri: "tickets://sla", mimeType: "text/markdown", description: "How fast support replies" }) export class TicketsSla extends ResourceContext { async execute(uri: string) { return "# Support SLA\n\nFirst reply within 4 business hours."; } } @Resource({ name: "billing-sla", uri: "billing://sla", mimeType: "text/markdown", description: "How fast refunds are paid" }) export class BillingSla extends ResourceContext { async execute(uri: string) { return "# Billing SLA\n\nRefunds are processed within 5 business days."; } } @App({ id: "tickets", name: "Tickets", resources: [TicketsSla] }) export class TicketsApp {} @App({ id: "billing", name: "Billing", resources: [BillingSla] }) export class BillingApp {} ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp, BillingApp } from "./apps"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], }) export default class HelpDeskServer {} ``` **Hidden fixture/test file (runs with the example):** ```ts sla.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`tickets://sla` is the support SLA", async ({ mcp }) => { expect((await mcp.resources.read("tickets://sla")).text()).toContain("Support SLA"); }); test("`billing://sla` is the billing SLA", async ({ mcp }) => { expect((await mcp.resources.read("billing://sla")).text()).toContain("Billing SLA"); }); test("both SLAs are listed", async ({ mcp }) => { expect(await mcp.resources.list()).toHaveLength(2); }); ``` **Hint:** Only the `uri` has to change. While you're there, give the two resources different `name`s too, so they don't get prefixed. **Solution:** Each app now owns a scheme, so its URIs can't collide with another app's, and both SLAs can be read. The solution also renames them `support-sla` and `billing-sla`, which keeps the names in `resources/list` as declared. ### Challenge: Share one ticket store Refunding INV-7 should close ticket T-4, but `get_ticket` keeps saying it's open. `TicketStore` is registered in both apps, so each app has its own copy. Make both apps use the same one. Initial call configuration: ```js { tool: "refund_invoice", arguments: { id: "INV-7" } } ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./apps/tickets.app"; import { BillingApp } from "./apps/billing.app"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], }) export default class HelpDeskServer {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./apps/tickets.app"; import { BillingApp } from "./apps/billing.app"; import { TicketStore } from "./ticket-store"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], providers: [TicketStore], }) export default class HelpDeskServer {} ``` ```ts apps/tickets.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "../ticket-store"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } @App({ id: "tickets", name: "Tickets", tools: [GetTicket], providers: [TicketStore] }) export class TicketsApp {} ``` **Solution file (alternative to the starter):** ```ts apps/tickets.app.ts solution import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "../ticket-store"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } @App({ id: "tickets", name: "Tickets", tools: [GetTicket] }) export class TicketsApp {} ``` ```ts apps/billing.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "../ticket-store"; @Tool({ name: "refund_invoice", description: "Refund an invoice in full, and close the ticket that asked for it", inputSchema: { id: z.string() }, }) export class RefundInvoice extends ToolContext { async execute({ id }: { id: string }) { const ticket = id === "INV-7" ? "T-4" : null; if (ticket) this.get(TicketStore).close(ticket); return { invoice: id, status: "refunded", closedTicket: ticket }; } } @App({ id: "billing", name: "Billing", tools: [RefundInvoice], providers: [TicketStore] }) export class BillingApp {} ``` **Solution file (alternative to the starter):** ```ts apps/billing.app.ts solution import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "../ticket-store"; @Tool({ name: "refund_invoice", description: "Refund an invoice in full, and close the ticket that asked for it", inputSchema: { id: z.string() }, }) export class RefundInvoice extends ToolContext { async execute({ id }: { id: string }) { const ticket = id === "INV-7" ? "T-4" : null; if (ticket) this.get(TicketStore).close(ticket); return { invoice: id, status: "refunded", closedTicket: ticket }; } } @App({ id: "billing", name: "Billing", tools: [RefundInvoice] }) export class BillingApp {} ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; status: "open" | "closed" }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-4", title: "Charged twice in March", status: "open" }, ]; get(id: string) { return this.tickets.find((t) => t.id === id); } close(id: string) { const ticket = this.get(id); if (ticket) ticket.status = "closed"; return ticket; } } ``` **Hidden fixture/test file (runs with the example):** ```ts refund.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("after refunding INV-7, `get_ticket` says T-4 is closed", async ({ mcp }) => { expect(await mcp.tools.call("refund_invoice", { id: "INV-7" })).toBeSuccessful(); expect((await mcp.tools.call("get_ticket", { id: "T-4" })).json()).toMatchObject({ status: "closed" }); }); test("tickets that weren't refunded stay open", async ({ mcp }) => { expect((await mcp.tools.call("get_ticket", { id: "T-1" })).json()).toMatchObject({ status: "open" }); }); ``` **Hint:** Take `TicketStore` out of both apps' `providers`, and list it once in `@FrontMcp`. **Solution:** A provider registered on an app belongs to that app, so two registrations meant two stores. Registered once on the server, there's a single `TicketStore`, and both apps' tools reach it through the same `this.get(TicketStore)`. --- # Writing Descriptions Agents Understand > How to write tool, argument and resource descriptions that tell a model when to use a capability, how to fill it in, and what comes back, and how to check them with tests. Source: https://frontmcp.dev/learn/writing-descriptions-agents-understand [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A description is an instruction to a model. When a model decides which tool to call, whether to call one at all, and what to put in each argument, the names and descriptions your FrontMCP server sends in `tools/list` are all it has to go on. A tool with a vague description gets skipped or misused however good its code is, and two tools with similar descriptions get mixed up. This lesson is about writing descriptions that steer a model to the right call. **You will learn** - What a tool description should say: what it does, what it returns, when to use it - How to tell a model when *not* to use a tool - How to describe arguments with units, formats and examples - Why overlapping tools confuse models, and how to merge them - The difference between `name` and `title`, and how to check descriptions with tests ## Descriptions are instructions Here are three help desk tools, written quickly. Open the **Capabilities** tab: ```ts tickets.tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", inputSchema: { query: z.string() } }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [{ id: "T-1", title: "Cannot log in", status: "open" }], query }; } } @Tool({ name: "get_ticket", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open", messages: [] as string[] }; } } @Tool({ name: "reply_to_ticket", inputSchema: { id: z.string(), body: z.string() } }) export class ReplyToTicket extends ToolContext { async execute({ id }: { id: string; body: string }) { return { id, sent: true }; } } ``` Each card says **No description. The model has only the name to go on.** A user writes: "Tell Dana we're looking into her login problem." The model can guess that `search_tickets` finds tickets, but not whether it searches titles, messages or customer names, or what comes back. It can guess that `reply_to_ticket` replies, but not that the customer receives it by email the moment it's called. Here are the same tools, described: ```ts tickets.tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns up to 10 matches, newest first, each with its id, title and status. To read a whole ticket, pass its id to get_ticket.", inputSchema: { query: z.string().min(3).describe("Words to look for in ticket titles, like \"log in\"") }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [{ id: "T-1", title: "Cannot log in", status: "open" }], query }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id, with every message in its conversation. Use it when you already have an id like T-12; to find an id, use search_tickets.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open", messages: [] as string[] }; } } @Tool({ name: "reply_to_ticket", description: "Email a reply to the customer who opened a ticket, and add it to the ticket's conversation. The customer receives it immediately, so only reply when the user asked you to.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12"), body: z.string().min(1).describe("The reply, in plain text, written to the customer"), }, }) export class ReplyToTicket extends ToolContext { async execute({ id }: { id: string; body: string }) { return { id, sent: true }; } } ``` Each description answers the questions a model has, roughly in the order it has them: 1. **What does it do?** Lead with one plain sentence in the user's terms: "Search support tickets by words in their title." 2. **What comes back?** "Up to 10 matches, newest first, each with its id, title and status." Now the model knows it may not see everything, and that the ids are there for the next step. 3. **When is it the right tool, and what comes next?** "To read a whole ticket, pass its id to get_ticket." Point from one tool to the next by name. 4. **What happens as a side effect?** "The customer receives it immediately." Anything a user would want to know before the call happens belongs here. Write for a reader who has never seen your code or your database. "Queries `tkt_main` with an `ILIKE`" describes your implementation; "Search tickets by words in their title" describes what the model can do with it. > **Note** > > `outputSchema` tells clients the *shape* of a result, like `{ tickets, total }`. The description is still where you say what it *means*: how many results at most, in what order, and what an empty list means. See [Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results) for `outputSchema`. ### Putting the result's shape in the description Not every client passes `outputSchema` on to the model. FrontMCP can also write a summary of it at the end of the description, with the `output` option: ```ts search.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns up to 10 matches, newest first.", inputSchema: { query: z.string().min(3).describe("Words to look for in ticket titles") }, outputSchema: z.object({ tickets: z.array(z.object({ id: z.string(), title: z.string() })), total: z.number().int().describe("How many tickets matched"), }), output: { schemaMode: "both" }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [], total: 0 }; } } ``` ```ts description.test.ts import { test, expect } from "@frontmcp/testing"; test("the description ends with a summary of the result", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool.description).toContain("**Returns:**"); expect(tool.description).toContain("`total`: integer (required) — How many tickets matched"); }); test("outputSchema is still listed too", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool.outputSchema?.properties).toHaveProperty("total"); }); ``` `schemaMode` can be `"definition"` (the default: `outputSchema` only), `"description"` (the summary instead of `outputSchema`), `"both"`, or `"none"`. The summary lists top-level fields with their types and `.describe()` notes, so describing output fields pays off here too. ## Say when not to use a tool Some tools are easy to mistake for each other because they do almost the same thing. A help desk has two ways to write on a ticket: a reply the customer receives, and a note only agents see. If a user says "Note that Dana is on the legacy plan," a model that picks the wrong one emails the customer your internal notes. Each description should say what makes it different, and name the other tool: Initial call configuration: ```js { tool: "add_internal_note", arguments: { id: "T-1", note: "Dana is on the legacy plan. Check before offering a refund." } } ``` ```ts write.tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "reply_to_ticket", description: "Email a reply to the customer who opened a ticket. The customer receives it immediately. For anything the customer shouldn't see, use add_internal_note instead.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12"), body: z.string().min(1).describe("The reply, in plain text, written to the customer"), }, }) export class ReplyToTicket extends ToolContext { async execute({ id }: { id: string; body: string }) { return { id, emailed: true }; } } @Tool({ name: "add_internal_note", description: "Add a note to a ticket that only support agents can see. The customer is never told. Use it for context, handover notes and anything private; to answer the customer, use reply_to_ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12"), note: z.string().min(1).describe("The note, in plain text"), }, }) export class AddInternalNote extends ToolContext { async execute({ id }: { id: string; note: string }) { return { id, visibleTo: "agents" }; } } ``` "Instead" sentences are the most useful ones in a description. They turn a guess between two similar tools into a rule: *this* tool for customers, *that* one for agents. The same pattern works for any pair that's easy to confuse, like search and get, close and delete, or preview and send. ## Describe arguments: units, formats and examples A field's name and type are rarely enough. This tool snoozes a ticket, hiding it from the queue for a while: Initial call configuration: ```js { tool: "snooze_ticket", arguments: { id: "T-1", duration: 3 } } ``` ```ts snooze.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "snooze_ticket", description: "Hide a ticket from the queue until a later time, then bring it back as open.", inputSchema: { id: z.string(), duration: z.number(), }, }) export class SnoozeTicket extends ToolContext { async execute({ id, duration }: { id: string; duration: number }) { const until = new Date(Date.UTC(2026, 8, 24, 9, 0) + duration * 60_000); return { id, snoozedUntil: until.toISOString() }; } } ``` The user said "snooze it for three days", and the model sent `duration: 3`. The code reads minutes, so the ticket comes back three minutes later. Nothing in the schema said minutes, and `id` doesn't say what an id looks like either. Put the unit in the name, say it again in the description, and give an example: Initial call configuration: ```js { tool: "snooze_ticket", arguments: { id: "T-1", minutes: 4320 } } ``` ```ts snooze.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "snooze_ticket", description: "Hide a ticket from the queue until a later time, then bring it back as open.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12. Get one from search_tickets."), minutes: z .number() .int() .min(5) .max(10080) .describe("How long to snooze, in minutes: 60 is an hour, 1440 is a day. At most 7 days."), }, }) export class SnoozeTicket extends ToolContext { async execute({ id, minutes }: { id: string; minutes: number }) { const until = new Date(Date.UTC(2026, 8, 24, 9, 0) + minutes * 60_000); return { id, snoozedUntil: until.toISOString() }; } } ``` What to put in an argument's description: - **Units.** Minutes or hours, cents or dollars, bytes or megabytes. Put the unit in the field name too (`minutes`, `amount_cents`), because a name is harder to overlook than a note. - **Formats.** `T-12`, `YYYY-MM-DD`, an email address. A `.regex()` enforces the format; the note shows the model what it looks like. - **Examples.** Short, realistic values: "like T-12", "60 is an hour". One example often says more than a sentence of explanation. - **Where the value comes from.** "Get one from search_tickets" tells the model how to get an id it doesn't have yet. The constraints matter as much as the words. `.int().min(5).max(10080)` appears in `tools/list` as `minimum` and `maximum`, and FrontMCP rejects anything outside that range before `execute()` runs, as covered in [Schemas Are Contracts](https://frontmcp.dev/learn/schemas-are-contracts). ### Does the examples option reach the model? `@Tool` also has an `examples` option, with sample inputs. FrontMCP 1.8 doesn't send it in `tools/list`: it's used by FrontMCP's [CodeCall plugin](https://frontmcp.dev/reference/plugins/codecall), which shows a tool's examples to a model that [looks the tool up](https://frontmcp.dev/learn/letting-the-model-write-code-with-codecall#finding-tools-search-then-describe). A model connected over MCP only sees the examples you write into descriptions, like "60 is an hour" above. The test below shows `examples` missing from the listed tool: ```ts snooze.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "snooze_ticket", description: "Hide a ticket from the queue until a later time, then bring it back as open.", inputSchema: { id: z.string(), minutes: z.number().int() }, examples: [{ description: "Snooze T-1 for a day", input: { id: "T-1", minutes: 1440 } }], }) export class SnoozeTicket extends ToolContext { async execute({ id, minutes }: { id: string; minutes: number }) { return { id, minutes }; } } ``` ```ts examples.test.ts import { test, expect } from "@frontmcp/testing"; test("`examples` isn't part of tools/list", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "snooze_ticket"); expect(tool).not.toHaveProperty("examples"); expect(JSON.stringify(tool)).not.toContain("Snooze T-1 for a day"); }); ``` ## One tool per job Every tool you add is one more option the model has to weigh. When several tools do nearly the same thing, it has to guess between them. These three all return tickets: ```ts search.tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string().min(3) }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [] as { id: string }[], query }; } } @Tool({ name: "find_customer_tickets", description: "Find a customer's support tickets.", inputSchema: { email: z.string().email() }, }) export class FindCustomerTickets extends ToolContext { async execute({ email }: { email: string }) { return { tickets: [] as { id: string }[], email }; } } @Tool({ name: "list_open_tickets", description: "List open support tickets.", inputSchema: {}, }) export class ListOpenTickets extends ToolContext { async execute() { return { tickets: [] as { id: string }[] }; } } ``` "Are there any open tickets from Dana about logging in?" needs all three filters, and no tool has them. The model picks one and filters the rest itself, or calls all three and merges the lists, or gives up. When tools differ only by a filter, merge them into one tool with optional arguments: Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log", status: "open", customer: "dana@acme.com" } } ``` ```ts search.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "search_tickets", description: "Search support tickets. Every filter is optional, and filters combine: words in the title, status, and the customer's email. Returns up to 10 matches, newest first. With no filters, returns the 10 newest tickets.", inputSchema: { query: z.string().min(3).optional().describe("Words to look for in ticket titles, like \"log in\""), status: z.enum(["open", "closed"]).optional().describe("Leave out to include both"), customer: z.string().email().optional().describe("The customer's email address, like dana@acme.com"), }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query, status, customer }: { query?: string; status?: "open" | "closed"; customer?: string }) { const matches = tickets.filter( (t) => (!query || t.title.toLowerCase().includes(query.toLowerCase())) && (!status || t.status === status) && (!customer || t.customer === customer), ); return { tickets: matches.slice(0, 10), total: matches.length }; } } ``` ```ts tickets.ts export const tickets = [ { id: "T-4", title: "Login link expired", status: "open", customer: "dana@acme.com" }, { id: "T-3", title: "Cannot log in", status: "closed", customer: "dana@acme.com" }, { id: "T-2", title: "Invoice total is wrong", status: "open", customer: "dana@acme.com" }, { id: "T-1", title: "Cannot log in", status: "open", customer: "sam@globex.com" }, ]; ``` One tool, one description, three described filters, and the question takes one call. Keep tools separate when they genuinely do different things: they have different side effects (reading and writing), different permissions, or return different kinds of results. Merge them when the only difference is which records they return. ## `name` is for the model, `title` is for people A tool has two names, and they have different jobs: - **`name`** is the identifier the model uses to call the tool, like `search_tickets`. It should be a `snake_case` verb and noun, unique on your server, and stable: models, prompts and tests refer to it, so renaming it breaks them. - **`title`** is a display name for people, like "Search tickets". Clients can show it in their UI, for example when they ask the user to approve a call. Set it with `@Tool({ title })`. `tools/list` sends `title` only for tools that have one; for the others, clients show the name. Resources and prompts take a `title` option too: ```ts search.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", title: "Search tickets", description: "Search support tickets by words in their title. Returns up to 10 matches, newest first.", inputSchema: { query: z.string().min(3).describe("Words to look for in ticket titles") }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [] as { id: string }[], query }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id, with every message in its conversation.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, messages: [] as string[] }; } } ``` ```ts refund-policy.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "refund-policy", title: "Refund policy", uri: "docs://refund-policy", mimeType: "text/markdown", description: "When customers can get a refund, and how much. Read it before answering any question about refunds or charges.", }) export class RefundPolicy extends ResourceContext { async execute(uri: string) { return { contents: [{ uri, mimeType: "text/markdown", text: "# Refunds\n\nFull refund within 30 days of purchase." }] }; } } ``` ```ts titles.test.ts import { test, expect } from "@frontmcp/testing"; test("search_tickets has the display name \"Search tickets\"", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "search_tickets"); expect(tool?.title).toBe("Search tickets"); }); test("get_ticket has no title, so it's listed without one", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "get_ticket"); expect(tool).not.toHaveProperty("title"); }); test("the resource has its own `title`", async ({ mcp }) => { const [resource] = await mcp.resources.list(); expect(resource.title).toBe("Refund policy"); }); ``` Open the Wire tab to see both lists. MCP also has an older place for a tool's display name, `annotations.title`. FrontMCP sends it as you set it, but `title` is the one to use. The resource's description follows the same rules as a tool's: say what's in it and when it's useful. Resources are usually picked by an application or a user rather than by the model, so the reader of that description may be a person choosing what to attach to a conversation. See [Exposing Data with Resources](https://frontmcp.dev/learn/exposing-data-with-resources). ## Checking descriptions with tests Descriptions drift. A tool gets renamed and another tool's description still points to the old name; someone adds an argument without a note. Tests over `tools/list` catch these, the same way they catch bugs in `execute()`: ```ts tickets.tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns up to 10 matches, newest first, each with its id, title and status. To read a whole ticket, pass its id to get_ticket.", inputSchema: { query: z.string().min(3).describe("Words to look for in ticket titles, like \"log in\"") }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [] as { id: string }[], query }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id, with every message in its conversation. Use it when you already have an id like T-12; to find an id, use search_tickets.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, messages: [] as string[] }; } } ``` ```ts descriptions.test.ts import { test, expect } from "@frontmcp/testing"; test("every tool has a description of at least 60 characters", async ({ mcp }) => { for (const tool of await mcp.tools.list()) { expect(tool.description?.length ?? 0).toBeGreaterThanOrEqual(60); } }); test("every argument has a description", async ({ mcp }) => { for (const tool of await mcp.tools.list()) { for (const [name, field] of Object.entries(tool.inputSchema.properties ?? {})) { expect([tool.name, name, field.description?.length > 0]).toEqual([tool.name, name, true]); } } }); test("tools named in descriptions exist", async ({ mcp }) => { const tools = await mcp.tools.list(); const names = tools.map((t) => t.name); for (const tool of tools) { for (const mentioned of tool.description?.match(/\b[a-z]+(?:_[a-z]+)+\b/g) ?? []) { expect(names).toContain(mentioned); } } }); ``` The **Tests** tab runs three checks: every tool has a real description, every argument has a note, and every `snake_case` tool name mentioned in a description is a tool that exists. Try renaming `get_ticket` to `read_ticket` and run the tests again: the third check fails, because `search_tickets` still sends the model to `get_ticket`. The second check puts the tool and field names in its comparison, so a failure says which argument is missing its note. Tests like these check that the words are there, not that a model understands them. For that, connect a real client (see [Installation](https://frontmcp.dev/learn/installation#connecting-a-client)), ask the questions your users ask, and watch which tools the model picks and what it sends. ## Recap - A model chooses tools and fills in arguments from names, descriptions and schemas alone. Descriptions are instructions. - A tool description says what it does, what it returns, when to use it (and which tool to use instead), and any side effects. - Name the other tool in an "instead" sentence when two tools are easy to confuse. - Argument descriptions give units, formats, examples and where values come from. Put units in field names too. - `@Tool({ examples })` isn't sent in `tools/list` in FrontMCP 1.8. Write examples into descriptions. - Merge tools that differ only by a filter into one tool with optional arguments. - `name` is the stable identifier the model calls; `title` is a display name for people. Tools, resources and prompts all take a `title` option. - Test descriptions over `tools/list`: presence, length, argument notes, and references to other tools. ## Try some challenges ### Challenge: Keep the model from deleting real tickets `close_ticket` and `delete_ticket` have descriptions a model can't tell apart. Rewrite both descriptions so that `close_ticket` says it's for solved problems and names `delete_ticket` as the one *not* to use, and `delete_ticket` says it's permanent, is only for spam, and names `close_ticket` as the one to use instead. Each should be at least 60 characters. ```ts tickets.tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "delete_ticket", description: "Remove a ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, annotations: { destructiveHint: true }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: true }; } } ``` **Solution file (alternative to the starter):** ```ts tickets.tools.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket once the customer's problem is solved. The ticket stays in the history and can be reopened. Don't use delete_ticket for this.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "delete_ticket", description: "Permanently delete a ticket and its conversation. Only for spam or tickets opened by mistake; to finish a real ticket, use close_ticket instead. This can't be undone.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, annotations: { destructiveHint: true }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: true }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts descriptions.test.ts hidden import { test, expect } from "@frontmcp/testing"; async function descriptionOf(mcp: any, name: string): Promise { const tool = (await mcp.tools.list()).find((t: any) => t.name === name); return tool?.description ?? ""; } test("both descriptions are at least 60 characters", async ({ mcp }) => { expect((await descriptionOf(mcp, "close_ticket")).length).toBeGreaterThanOrEqual(60); expect((await descriptionOf(mcp, "delete_ticket")).length).toBeGreaterThanOrEqual(60); }); test("close_ticket says it's for solved problems", async ({ mcp }) => { expect(await descriptionOf(mcp, "close_ticket")).toMatch(/solved|resolved|fixed/i); }); test("close_ticket names delete_ticket", async ({ mcp }) => { expect(await descriptionOf(mcp, "close_ticket")).toContain("delete_ticket"); }); test("delete_ticket says it's permanent", async ({ mcp }) => { expect(await descriptionOf(mcp, "delete_ticket")).toMatch(/permanent|can't be undone|cannot be undone/i); }); test("delete_ticket says it's only for spam", async ({ mcp }) => { expect(await descriptionOf(mcp, "delete_ticket")).toMatch(/spam/i); }); test("delete_ticket names close_ticket as the alternative", async ({ mcp }) => { expect(await descriptionOf(mcp, "delete_ticket")).toContain("close_ticket"); }); ``` **Hint:** Write each description in the order from this lesson: what it does, then when to use the other tool instead. The riskier tool needs the clearer warning. **Solution:** Each description now says what the tool is for and names the other one, so "we fixed Dana's problem" leads to `close_ticket` and "this ticket is spam" leads to `delete_ticket`. The `destructiveHint` annotation tells clients the call is risky, but only the description tells the model *when* it's the right call. ### Challenge: Say which unit `issue_refund` takes an `amount`, and the code reads it in cents. A model asked to "refund $19.99" will send `19.99`, and the customer gets 20 cents back. Rename the argument to `amount_cents`, make it a whole number of at least 1, and describe it with the unit and an example. Initial call configuration: ```js { tool: "issue_refund", arguments: { id: "T-2", amount: 19.99 } } ``` ```ts refund.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "issue_refund", description: "Refund part or all of a customer's payment on a ticket. The money goes back to the card they paid with.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12"), amount: z.number(), }, }) export class IssueRefund extends ToolContext { async execute({ id, amount }: { id: string; amount: number }) { return { id, refunded: `$${(amount / 100).toFixed(2)}` }; } } ``` **Solution file (alternative to the starter):** ```ts refund.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "issue_refund", description: "Refund part or all of a customer's payment on a ticket. The money goes back to the card they paid with.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12"), amount_cents: z.number().int().min(1).describe("How much to refund, in cents: 1999 is $19.99"), }, }) export class IssueRefund extends ToolContext { async execute({ id, amount_cents }: { id: string; amount_cents: number }) { return { id, refunded: `$${(amount_cents / 100).toFixed(2)}` }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts refund.test.ts hidden import { test, expect } from "@frontmcp/testing"; async function fields(mcp: any) { const tool = (await mcp.tools.list()).find((t: any) => t.name === "issue_refund"); return tool.inputSchema.properties; } test("the argument is called `amount_cents`", async ({ mcp }) => { const props = await fields(mcp); expect(props).toHaveProperty("amount_cents"); expect(props).not.toHaveProperty("amount"); }); test("its description says \"cents\"", async ({ mcp }) => { expect((await fields(mcp)).amount_cents?.description).toMatch(/cents/i); }); test("it's a whole number of at least 1", async ({ mcp }) => { const field = (await fields(mcp)).amount_cents; expect(field?.type).toBe("integer"); expect(field?.minimum).toBe(1); }); test("refunding 1999 cents refunds $19.99", async ({ mcp }) => { const result = await mcp.tools.call("issue_refund", { id: "T-2", amount_cents: 1999 }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ id: "T-2", refunded: "$19.99" }); }); test("19.99 is rejected instead of refunding 20 cents", async ({ mcp }) => { const result = await mcp.tools.call("issue_refund", { id: "T-2", amount_cents: 19.99 }); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); ``` **Hint:** `.int()` makes a number whole, and shows up in `tools/list` as `"type": "integer"`. Rename the field in `execute()` too. **Solution:** The unit is now in three places a model reads: the name `amount_cents`, the note "in cents: 1999 is $19.99", and `"type": "integer"`, which rules out `19.99`. If a model still sends dollars, FrontMCP rejects the call instead of refunding the wrong amount. ### Challenge: Make the description checks pass These tools fail the description checks from this lesson. `search_tickets` points to a tool that was renamed, `get_ticket` has no description, and `reply_to_ticket` has an argument without a note. Fix the descriptions until every check passes. ```ts tickets.tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns up to 10 matches. Use fetch_ticket for details.", inputSchema: { query: z.string().min(3).describe("Words to look for in ticket titles") }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [] as { id: string }[], query }; } } @Tool({ name: "get_ticket", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, messages: [] as string[] }; } } @Tool({ name: "reply_to_ticket", description: "Email a reply to the customer who opened a ticket. The customer receives it immediately.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12"), body: z.string().min(1), }, }) export class ReplyToTicket extends ToolContext { async execute({ id }: { id: string; body: string }) { return { id, sent: true }; } } ``` **Solution file (alternative to the starter):** ```ts tickets.tools.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Returns up to 10 matches. Use get_ticket for details.", inputSchema: { query: z.string().min(3).describe("Words to look for in ticket titles") }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [] as { id: string }[], query }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id, with every message in its conversation. To find an id, use search_tickets.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, messages: [] as string[] }; } } @Tool({ name: "reply_to_ticket", description: "Email a reply to the customer who opened a ticket. The customer receives it immediately.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12"), body: z.string().min(1).describe("The reply, in plain text, written to the customer"), }, }) export class ReplyToTicket extends ToolContext { async execute({ id }: { id: string; body: string }) { return { id, sent: true }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts descriptions.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("every tool has a description of at least 60 characters", async ({ mcp }) => { for (const tool of await mcp.tools.list()) { expect([tool.name, tool.description?.length >= 60]).toEqual([tool.name, true]); } }); test("every argument has a description", async ({ mcp }) => { for (const tool of await mcp.tools.list()) { for (const [name, field] of Object.entries(tool.inputSchema.properties ?? {})) { expect([tool.name, name, field.description?.length > 0]).toEqual([tool.name, name, true]); } } }); test("tools named in descriptions exist", async ({ mcp }) => { const tools = await mcp.tools.list(); const names = tools.map((t) => t.name); for (const tool of tools) { for (const mentioned of tool.description?.match(/\b[a-z]+(?:_[a-z]+)+\b/g) ?? []) { expect(names).toContain(mentioned); } } }); ``` **Hint:** Open the **Checks** tab after pressing Check: each failure names the tool, and for arguments, the field. **Solution:** Three small fixes: point `search_tickets` at `get_ticket`, give `get_ticket` a description that says what it returns and where ids come from, and describe `body`. Checks like these are cheap to keep in your own test suite, so the next rename fails a test instead of confusing a model. ### Challenge: Give a tool a display title Clients show tool names to users, for example when asking them to approve a call, and `close_ticket` isn't friendly. Give the tool the display title "Close ticket" without changing its `name`. ```ts close.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket once the customer's problem is solved. The ticket can be reopened later.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } ``` **Solution file (alternative to the starter):** ```ts close.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket once the customer's problem is solved. The ticket can be reopened later.", title: "Close ticket", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-12") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts title.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the display title is \"Close ticket\"", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "close_ticket"); expect(tool?.title).toBe("Close ticket"); }); test("the name is still close_ticket", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("close_ticket"); }); ``` **Hint:** Look at how the lesson gave `search_tickets` its display name. **Solution:** `title` goes out in `tools/list` next to the name, for clients to show. The `name` stays `close_ticket`, so nothing that calls the tool has to change. --- # Talking to Clients > How a tool talks to the client while it runs. Asking the user a question mid-call, and reporting progress and logs from long-running tools. Source: https://frontmcp.dev/learn/talking-to-clients [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 So far, every call has gone one way: the model calls a tool, the tool runs, and a result comes back. A FrontMCP tool can also talk to the client in between. It can stop and ask the person using the client a question, and it can report how far along it is while it works. This chapter covers both, and what each one looks like on the wire under MCP 2026-07-28. A server can also speak when nobody called it: a channel pushes an event into an open Claude Code session, and the last section shows where to start. **In this chapter** - [How to ask the user a question in the middle of a call](https://frontmcp.dev/learn/asking-the-user) - [How to report progress and send log messages from a long-running tool](https://frontmcp.dev/learn/reporting-progress) ## Asking the user mid-call Some calls need a person, not a model: a yes before something that can't be undone, or a detail only the user knows. `this.elicit()` sends the user a question with a small form and gives your tool their answer. The call below stops to ask. Press **Accept**, **Decline** or **Cancel** in the Call tab to answer it: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket and email the customer. Asks the user to confirm first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const answer = await this.elicit( `Close ${id} and email the customer that it's resolved?`, z.object({ confirm: z.boolean().describe("Tick to close the ticket") }), ); if (answer.status !== "accept" || answer.content?.confirm !== true) { return { id, closed: false, reason: `The user didn't confirm (${answer.status}).` }; } return { id, closed: true }; } } ``` Under 2026-07-28 nothing waits on the server while the user thinks: the call returns `input_required`, and the client sends the same request again with the answer. ### [Asking the User Mid-Call](https://frontmcp.dev/learn/asking-the-user) Learn how to handle accept, decline and cancel, why `execute()` runs twice, what happens with clients that can't show a form, and how to turn elicitation on and test it. ## Reporting progress and logs A slow tool looks just like a stuck one until it returns. `this.progress()` reports how much is done, and `this.notify()` sends log messages about what's happening. Clients ask for them per request, and get them as a stream before the result: Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts export-tickets.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; const tickets = ["T-1", "T-2", "T-3", "T-4"]; @Tool({ name: "export_tickets", description: "Export every support ticket to tickets.csv. Takes a few seconds.", inputSchema: {}, }) export class ExportTickets extends ToolContext { async execute() { await this.notify(`Exporting ${tickets.length} tickets`); for (const [i, id] of tickets.entries()) { await new Promise((resolve) => setTimeout(resolve, 100)); await this.progress(i + 1, tickets.length, `Exported ${id}`); } return { file: "tickets.csv", rows: tickets.length }; } } ``` The Call tab shows the notifications above the result. Untick **Stream progress & logs** and call again: the tool works the same, it just has nobody to report to. ### [Reporting Progress and Logs](https://frontmcp.dev/learn/reporting-progress) Learn what to pass to `progress()` and `notify()`, how log levels work, what the event stream looks like, and how to test notifications. ## Telling a session something it didn't ask for Asking and reporting both happen inside a call. A channel has no call to answer: when something happens on the server, it sends an event to the sessions that are connected, and the model reads it as a `` tag. Here `report_outage` emits an `outage` event, and the channel turns it into the text a session gets: Initial call configuration: ```js { tool: "report_outage", arguments: { service: "billing" } } ``` ```ts outages.channel.ts active import { Channel, ChannelContext, type ChannelNotification } from "@frontmcp/sdk"; @Channel({ name: "outages", source: { type: "app-event", event: "outage" } }) export class OutagesChannel extends ChannelContext { async onEvent(payload: unknown): Promise { const { service } = payload as { service: string }; return { content: `${service} is down`, meta: { service } }; } } ``` ```ts main.ts import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; import { OutagesChannel } from "./outages.channel"; @Tool({ name: "report_outage", description: "Report that a service is down, and alert every connected session", inputSchema: { service: z.string().describe("The service's name, like billing") }, }) export class ReportOutage extends ToolContext { async execute({ service }: { service: string }) { this.scope.channelEventBus?.emit("outage", { service }); return { reported: service }; } } @App({ id: "ops", name: "Ops", tools: [ReportOutage], channels: [OutagesChannel] }) export class OpsApp {} export const config = { info: { name: "ops", version: "1.0.0" }, apps: [OpsApp], channels: { enabled: true }, }; @FrontMcp(config) export default class Server {} ``` ```ts outages.test.ts import { test, expect } from "@frontmcp/testing"; import { connect } from "@frontmcp/sdk"; import { config } from "./main"; test("a connected session gets the event, without calling anything for it", async () => { const session = await connect(config, { capabilities: { experimental: { "claude/channel": {} } } }); const received: unknown[] = []; session.onNotification((message: { method: string; params?: unknown }) => { if (message.method === "notifications/claude/channel") received.push(message.params); }); await session.callTool("report_outage", { service: "billing" }); await new Promise((resolve) => setTimeout(resolve, 50)); expect(received).toEqual([{ content: "billing is down", meta: { service: "billing", source: "outages" } }]); await session.close(); }); ``` The Call tab shows only the tool's result: the Playground's client has no session to push into. The test in the Tests tab opens one, and the event arrives there as a `notifications/claude/channel` message. Channels are a Claude Code research preview. Claude Code reads them from a server it starts over stdio, in a session started with a flag that names the server. Since FrontMCP 1.12.0 a stdio server with a channel declines MCP 2026-07-28, which makes Claude Code open a session, and sends its events to that session without being asked, also through `runShared()` and `frontmcp dev --stdio`. The reference has the ways of running a server that serve such a session, what each needs, and what was checked: [Channels in Claude Code](https://frontmcp.dev/reference/sdk/channel#channels-in-claude-code). A server that already publishes [events](https://frontmcp.dev/reference/sdk/event) can send them the same way, with the event's `channel` option. ## What's next? Start the chapter with [Asking the User Mid-Call](https://frontmcp.dev/learn/asking-the-user). After it, [Structuring a Server](https://frontmcp.dev/learn/structuring-a-server) covers how a server grows: shared state in providers, plugins, and hooks around every call. --- # Asking the User Mid-Call > How a tool asks the person using the client a question in the middle of a call, with this.elicit(), and what happens on the wire under MCP 2026-07-28. Source: https://frontmcp.dev/learn/asking-the-user [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Some tools can't finish on their own. A tool that closes a ticket and emails the customer is about to do something that can't be taken back. A tool that assigns a ticket needs to know who should get it, and only the person using the client knows. `this.elicit()` lets a FrontMCP tool pause its call to ask that person a question, through a form their client shows them. The model doesn't answer it. The user does. **You will learn** - How to ask the user a question with `this.elicit()` - How to handle each answer: accept, decline and cancel - What goes over the wire under MCP 2026-07-28, and why `execute()` runs twice - What happens with clients that can't show a form - How to turn elicitation on in your server, and how to test a tool that asks ## A tool that acts without asking This tool closes a ticket and emails the customer that their problem is solved. A user says "I think the login problem is sorted", and the model calls it: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { outbox, tickets } from "./store"; @Tool({ name: "close_ticket", description: "Close a support ticket and email the customer that it's resolved.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "closed"; outbox.push(`To the customer of ${id}: "${ticket.title}" is resolved.`); return { id, closed: true }; } } ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "open" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); export const outbox: string[] = []; ``` The ticket is closed and the email is gone before anyone confirmed that the problem really is solved. `destructiveHint: true` lets a client warn the user before it sends the call, but it's a hint: whether anyone is asked depends on the client. If the tool itself needs a yes before it acts, the tool has to ask. ## Asking with `this.elicit()` `this.elicit(message, schema)` asks the user a question and returns their answer. The message is the question. The schema is a `z.object()` describing the form the client shows: here, one checkbox. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { outbox, tickets } from "./store"; @Tool({ name: "close_ticket", description: "Close a support ticket and email the customer that it's resolved. Asks the user to confirm first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); const answer = await this.elicit( `Close ${id} ("${ticket.title}") and email the customer that it's resolved?`, z.object({ confirm: z.boolean().describe("Tick to close the ticket") }), ); if (answer.status === "decline") return { id, closed: false, reason: "The user said no. Leave the ticket open." }; if (answer.status === "cancel") return { id, closed: false, reason: "The user dismissed the question without answering." }; if (answer.content?.confirm !== true) return { id, closed: false, reason: "The user didn't tick the box." }; ticket.status = "closed"; outbox.push(`To the customer of ${id}: "${ticket.title}" is resolved.`); return { id, closed: true }; } } ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "open" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); export const outbox: string[] = []; ``` The Call tab shows the form the user would see. Tick the box and press **Accept**, then call the tool again and try **Decline** and **Cancel**. `elicit()` returns an object with a `status`, and `content` when there is one: | `status` | What the user did | `content` | | --- | --- | --- | | `"accept"` | Submitted the form | The form's values, like `{ confirm: true }` | | `"decline"` | Said no | none | | `"cancel"` | Closed the form without choosing | none | Handle all three, and say in the result what happened. The model reads the result: "The user said no" tells it to stop, where a bare `closed: false` might send it straight back to try again. Keep the schema a flat object of strings, numbers, booleans and enums. Clients have to turn it into a form, and that's all the MCP spec allows in one. `.describe()` on a field goes into the schema as its description, which clients show next to the field. This tool asks on every call. To ask once and let later calls through, put the tool behind [approval](https://frontmcp.dev/learn/asking-for-approval), which records the user's yes and checks for it before each call. ## Asking for a missing detail Elicitation isn't only for confirmations. When a tool needs something only the user can decide, it can ask for it. Here, the model may pass an `agent`, and if it doesn't, the tool asks the user to pick one: Initial call configuration: ```js { tool: "assign_ticket", arguments: { id: "T-2" } } ``` ```ts assign-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const AGENTS = ["Nour", "Sam", "Priya"] as const; const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", agent: "Nour" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", agent: "" }], ]); @Tool({ name: "assign_ticket", description: "Assign a support ticket to an agent. If you don't know who should take it, leave `agent` out and the user will be asked.", inputSchema: { id: z.string().describe("Ticket id, like T-1"), agent: z.enum(AGENTS).optional().describe("Who should take the ticket"), }, }) export class AssignTicket extends ToolContext { async execute({ id, agent }: { id: string; agent?: (typeof AGENTS)[number] }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); if (!agent) { const answer = await this.elicit( `Who should take ${id} ("${ticket.title}")?`, z.object({ agent: z.enum(AGENTS).describe("Support agent") }), ); const picked = answer.content?.agent; if (answer.status !== "accept" || !picked || !AGENTS.includes(picked)) { return { id, assigned: false, reason: "The user didn't pick an agent." }; } agent = picked; } ticket.agent = agent; return { id, assigned: true, agent }; } } ``` Pick an agent and press **Accept**. Then change the call to include `agent` and send it again: the tool doesn't ask, because it doesn't need to. That's the split to aim for. The model fills in `inputSchema` from what it knows. The user answers an elicitation, for what only they can decide. Asking for something the model could have passed just interrupts the user. > **Pitfall: Check the answer** > > FrontMCP checks an accepted answer against the schema before `elicit()` returns. A missing or mistyped field fails the call with `INVALID_INPUT` and "The elicitation answer does not match the requested schema", so your tool never sees it. Decline and cancel answers have no `content`; check `answer.status` before using accepted fields. Changed in 1.11.3: before, older protocol versions did not validate answers, and decline and cancel answers could carry content. The tests [further down](https://frontmcp.dev/learn/asking-the-user#testing-a-tool-that-asks) show a malformed answer being rejected. ## What happens on the wire In MCP 2026-07-28, the server never holds a call open while it waits for the user. Open the **Wire** tab in the example above, answer the question, and look at the two `tools/call` requests: 1. The first `tools/call` runs `execute()` until it reaches `elicit()`. Instead of a normal result, the call returns `resultType: "input_required"`, with the question in `inputRequests` and a signed `requestState`: ```json { "resultType": "input_required", "inputRequests": { "elicitation-1": { "method": "elicitation/create", "params": { "message": "Who should take T-2 (\"Invoice total is wrong\")?", "requestedSchema": { "type": "object", "properties": { "agent": { "type": "string", "enum": ["Nour", "Sam", "Priya"], "description": "Support agent" } }, "required": ["agent"], "additionalProperties": false } } } }, "requestState": "eyJyIjp7fSwicCI6…" } ``` 2. The client shows the form. Nothing is waiting on the server: the first request is finished. 3. The client sends the **same** `tools/call` again, with the answer in `inputResponses` under the same key, and the `requestState` it was given: ```json { "name": "assign_ticket", "arguments": { "id": "T-2" }, "inputResponses": { "elicitation-1": { "action": "accept", "content": { "agent": "Priya" } } }, "requestState": "eyJyIjp7fSwicCI6…" } ``` 4. FrontMCP runs `execute()` again **from the top**. This time `elicit()` finds an answer for `elicitation-1` and returns it instead of asking, and the call finishes with a normal result. Both messages are trimmed here; the Wire tab shows them in full, with `_meta` and the schema's `$schema`. The key counts the `elicit()` calls in one run of `execute()`: the first is `elicitation-1`, a second would be `elicitation-2`. On the wire the answer is `action`, and FrontMCP hands it to your code as `status`. Changed in 1.10.13: before, a string in place of `inputResponses` or one of its answer objects could reach the tool. FrontMCP now rejects it with JSON-RPC `-32602` before `execute()` runs. Invalid fields inside an accepted answer's `content` still produce the `INVALID_INPUT` tool result described above. See [the request checks](https://frontmcp.dev/reference/server/protocol-versions#rejecting-malformed-requests). ### What's in requestState? `requestState` is a token FrontMCP creates and the client passes back without reading. It holds the answers from earlier rounds, and it's signed with an HMAC, bound to the caller and to the tool name and arguments, and expires after 10 minutes. If a returned state fails any of those checks, FrontMCP ignores it and logs a warning. The signing key is `VAULT_SECRET` or `JWT_SECRET` from the environment. Without either, each server process picks a random key, so if you run several instances behind a load balancer, give them all [the same secret](https://frontmcp.dev/learn/running-several-instances#the-secrets-every-instance-shares). ## Ask first, then act Because `execute()` starts over when the answer arrives, every line before `elicit()` runs once per round trip. This version writes to the ticket's history before it asks. Accept the question and look at `history`: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = new Map([["T-1", { id: "T-1", status: "open", history: ["Opened by the customer"] }]]); @Tool({ name: "close_ticket", description: "Close a support ticket. Asks the user to confirm first.", inputSchema: { id: z.string() }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.history.push("Close requested"); // 🚩 runs on both round trips const answer = await this.elicit(`Close ${id}?`, z.object({ confirm: z.boolean() })); if (answer.status !== "accept" || answer.content?.confirm !== true) { return { id, closed: false, history: ticket.history }; } ticket.status = "closed"; ticket.history.push("Closed"); return { id, closed: true, history: ticket.history }; } } ``` "Close requested" is there twice. Reading data before you ask is fine; changing anything, sending anything or charging anything is not. Do those after the answer, as the `close_ticket` [above](https://frontmcp.dev/learn/asking-the-user#asking-with-thiselicit) does. > **Pitfall: Ask for everything in one form** > > Each question is a full round trip, and each one runs `execute()` again from the top. If you need several details, ask for them together, in one `z.object()` with several fields. ## Testing a tool that asks In a test, nobody is there to fill in the form. `mcp.onElicitation()` registers the answer the test client gives when a tool asks. The handler receives the request, with its `message` and `requestedSchema`, and returns `{ action, content }`. Open the **Tests** tab: ```ts close-ticket.test.ts active import { test, expect } from "@frontmcp/testing"; test.describe("close_ticket", () => { test("asks about the right ticket, and closes it on yes", async ({ mcp }) => { let question = ""; mcp.onElicitation((request) => { question = request.message; return { action: "accept", content: { confirm: true } }; }); const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(question).toContain("T-1"); expect(result.json()).toEqual({ id: "T-1", closed: true }); }); test("leaves the ticket open when the user declines", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "decline" })); const result = await mcp.tools.call("close_ticket", { id: "T-2" }); expect(result.json()).toMatchObject({ closed: false }); }); test("an answer that doesn't match the schema is rejected", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirm: "yes" } })); const result = await mcp.tools.call("close_ticket", { id: "T-3" }); expect(result).toBeError("INVALID_INPUT"); expect(result.text()).toContain("does not match the requested schema"); }); }); ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { outbox, tickets } from "./store"; @Tool({ name: "close_ticket", description: "Close a support ticket and email the customer that it's resolved. Asks the user to confirm first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); const answer = await this.elicit( `Close ${id} ("${ticket.title}") and email the customer that it's resolved?`, z.object({ confirm: z.boolean().describe("Tick to close the ticket") }), ); if (answer.status === "decline") return { id, closed: false, reason: "The user said no. Leave the ticket open." }; if (answer.status === "cancel") return { id, closed: false, reason: "The user dismissed the question without answering." }; if (answer.content?.confirm !== true) return { id, closed: false, reason: "The user didn't tick the box." }; ticket.status = "closed"; outbox.push(`To the customer of ${id}: "${ticket.title}" is resolved.`); return { id, closed: true }; } } ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "open" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); export const outbox: string[] = []; ``` The last test sends `confirm: "yes"`, a string where the schema says boolean. FrontMCP rejects the answer before `elicit()` returns, so the call fails with `INVALID_INPUT` and `execute()` never gets past the question. [Testing Your Server](https://frontmcp.dev/learn/testing-your-server) covers the rest of `@frontmcp/testing`. ## Clients that can't ask Not every client can show a form. Under 2026-07-28, every request says what its client supports, in `_meta["io.modelcontextprotocol/clientCapabilities"]`. The Playground sends `{ elicitation: { form: {} } }`, so its calls can be asked questions. A client that leaves `elicitation` out gets a JSON-RPC error instead: `-32021`, with the capability it's missing in `data.requiredCapabilities`. The first test below sends a 2026-07-28 request the way such a client would, with an empty capabilities object: ```ts capabilities.test.ts active import { test, expect } from "@frontmcp/testing"; test("a client without the elicitation capability gets error -32021", async ({ mcp }) => { const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "close_ticket", arguments: { id: "T-1" }, _meta: { "io.modelcontextprotocol/clientCapabilities": {} }, }, }); expect(response).toHaveErrorCode(-32021); expect(response.error?.data).toEqual({ requiredCapabilities: { elicitation: { form: {} } } }); }); test("2026-07-28 clients don't see the fallback tool", async ({ mcp }) => { expect(await mcp.tools.list()).not.toContainTool("sendElicitationResult"); }); ``` ```ts close-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket. Asks the user to confirm first.", inputSchema: { id: z.string() }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const answer = await this.elicit(`Close ${id}?`, z.object({ confirm: z.boolean() })); return { id, closed: answer.status === "accept" && answer.content?.confirm === true }; } } ``` The error happens at `elicit()`, so the tool never gets an answer and the client gets no result. If a tool can do something useful without asking, like a read-only preview, make asking optional in its input rather than letting such clients fail. The second test is about a tool you may see in other clients: `sendElicitationResult`, which you didn't write. FrontMCP adds it when elicitation is enabled, as a fallback for clients on older protocol versions that keep a session open but can't show forms. For those clients, FrontMCP tells the model what to ask instead, in the tool's result or in a log message while the call waits. The model asks the user in the chat and calls `sendElicitationResult` with the answer, and FrontMCP runs the original tool again with it. FrontMCP lists the tool only for those clients, so a 2026-07-28 client like the Playground never sees it; one without the capability gets `-32021`, as above. ## Turning elicitation on The Playground turns elicitation on for you when an example calls `this.elicit()`. A real server has to ask for it. This example exports its own `@FrontMcp` server, so the Playground uses its configuration as written: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { CloseTicket } from "./close-ticket.tool"; @App({ id: "help-desk", name: "Help desk", tools: [CloseTicket] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts close-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket. Asks the user to confirm first.", inputSchema: { id: z.string() }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const answer = await this.elicit(`Close ${id}?`, z.object({ confirm: z.boolean() })); return { id, closed: answer.status === "accept" && answer.content?.confirm === true }; } } ``` The call fails with `ELICITATION_DISABLED`: "Elicitation is disabled in server configuration", followed by how to enable it. Elicitation is off unless you enable it in `@FrontMcp`: ```ts main.ts @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, }) export default class Server {} ``` ## Recap - `this.elicit(message, z.object({...}))` asks the user a question through their client. The model doesn't answer it. - Handle `accept`, `decline` and `cancel`, and say in the result what happened. FrontMCP rejects an accepted answer that doesn’t match the schema on every protocol revision. Decline and cancel carry no content. - Use `inputSchema` for what the model knows and elicitation for what only the user can decide. - Under 2026-07-28 the call returns `input_required`, and the client sends the same request again with `inputResponses`. `execute()` runs again from the top, so don't change anything before you ask. - A client that doesn't declare the `elicitation` capability gets error `-32021`. - Enable elicitation with `@FrontMcp({ elicitation: { enabled: true } })`, and answer questions in tests with `mcp.onElicitation()`. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Confirm before deleting `delete_ticket` deletes a ticket as soon as it's called. Make it ask the user first, with a `confirm` checkbox and a message that names the ticket. Only delete when the user accepts and ticks the box. Initial call configuration: ```js { tool: "delete_ticket", arguments: { id: "T-1" } } ``` ```ts delete-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in" }], ["T-2", { id: "T-2", title: "Invoice total is wrong" }], ["T-3", { id: "T-3", title: "Login link expired" }], ["T-4", { id: "T-4", title: "Password reset email missing" }], ]); @Tool({ name: "delete_ticket", description: "Permanently delete a support ticket.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); tickets.delete(id); return { id, deleted: true }; } } ``` **Solution file (alternative to the starter):** ```ts delete-ticket.tool.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in" }], ["T-2", { id: "T-2", title: "Invoice total is wrong" }], ["T-3", { id: "T-3", title: "Login link expired" }], ["T-4", { id: "T-4", title: "Password reset email missing" }], ]); @Tool({ name: "delete_ticket", description: "Permanently delete a support ticket. Asks the user to confirm first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); const answer = await this.elicit( `Permanently delete ${id} ("${ticket.title}")? This can't be undone.`, z.object({ confirm: z.boolean().describe("Tick to delete the ticket") }), ); if (answer.status !== "accept" || answer.content?.confirm !== true) { return { id, deleted: false, reason: `The user didn't confirm (${answer.status}).` }; } tickets.delete(id); return { id, deleted: true }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts delete-ticket.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("it asks about the ticket it's deleting", async ({ mcp }) => { let question = ""; mcp.onElicitation((request) => { question = request.message; return { action: "decline" }; }); await mcp.tools.call("delete_ticket", { id: "T-1" }); expect(question).toContain("T-1"); }); test("declining keeps the ticket", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "decline" })); const result = await mcp.tools.call("delete_ticket", { id: "T-2" }); expect(result).toBeSuccessful(); expect(result.json()).toMatchObject({ deleted: false }); }); test("cancelling keeps the ticket", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "cancel" })); const result = await mcp.tools.call("delete_ticket", { id: "T-3" }); expect(result.json()).toMatchObject({ deleted: false }); }); test("accepting without ticking `confirm` keeps the ticket", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirm: false } })); const result = await mcp.tools.call("delete_ticket", { id: "T-4" }); expect(result.json()).toMatchObject({ deleted: false }); }); test("accepting with `confirm` ticked deletes it", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirm: true } })); const result = await mcp.tools.call("delete_ticket", { id: "T-4" }); expect(result.json()).toEqual({ id: "T-4", deleted: true }); }); ``` **Hint:** Call `this.elicit()` after looking the ticket up and before `tickets.delete()`. Its second argument is `z.object({ confirm: z.boolean() })`. **Solution:** The tool asks first, and deletes only when `status` is `"accept"` and `confirm` is exactly `true`. Everything else, a decline, a cancel or an unticked box, keeps the ticket and says why. Asking comes after the lookup, which only reads, and before the delete, which is the one thing that mustn't run on the first round. ### Challenge: Send the email once This `close_ticket` asks before closing, but customers get their "resolved" email twice, and sometimes when the user said no. Fix it so accepting sends exactly one email and declining sends none. `list_outbox` shows what was sent. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { outbox, tickets } from "./store"; @Tool({ name: "close_ticket", description: "Close a support ticket and email the customer that it's resolved. Asks the user to confirm first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); outbox.push(`To the customer of ${id}: "${ticket.title}" is resolved.`); const answer = await this.elicit(`Close ${id} and email the customer?`, z.object({ confirm: z.boolean() })); if (answer.status !== "accept" || answer.content?.confirm !== true) { return { id, closed: false }; } ticket.status = "closed"; return { id, closed: true }; } } ``` **Solution file (alternative to the starter):** ```ts close-ticket.tool.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { outbox, tickets } from "./store"; @Tool({ name: "close_ticket", description: "Close a support ticket and email the customer that it's resolved. Asks the user to confirm first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); const answer = await this.elicit(`Close ${id} and email the customer?`, z.object({ confirm: z.boolean() })); if (answer.status !== "accept" || answer.content?.confirm !== true) { return { id, closed: false }; } ticket.status = "closed"; outbox.push(`To the customer of ${id}: "${ticket.title}" is resolved.`); return { id, closed: true }; } } ``` ```ts outbox.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; import { outbox } from "./store"; @Tool({ name: "list_outbox", description: "List the emails sent to customers.", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class ListOutbox extends ToolContext { async execute() { return { emails: outbox }; } } ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "open" }], ]); export const outbox: string[] = []; ``` **Hidden fixture/test file (runs with the example):** ```ts close-ticket.test.ts hidden import { test, expect } from "@frontmcp/testing"; const emailsAbout = async (mcp: any, id: string) => (await mcp.tools.call("list_outbox", {})).json().emails.filter((e: string) => e.includes(id)); test("accepting closes the ticket and sends exactly one email", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirm: true } })); const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result.json()).toEqual({ id: "T-1", closed: true }); expect(await emailsAbout(mcp, "T-1")).toHaveLength(1); }); test("declining sends no email", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "decline" })); const result = await mcp.tools.call("close_ticket", { id: "T-2" }); expect(result.json()).toEqual({ id: "T-2", closed: false }); expect(await emailsAbout(mcp, "T-2")).toHaveLength(0); }); ``` **Hint:** Count the round trips. The first run of `execute()` stops at `elicit()`; the second runs from the top with the answer. Which lines run in both? **Solution:** `outbox.push()` ran before `elicit()`, so it ran on the first round trip, when nobody had answered yet, and again on the second. Moving it after the check means it runs once, and only when the user said yes. The same goes for anything else with a side effect: ask first, then act. ### Challenge: Turn elicitation on This server exports its own `@FrontMcp` configuration, and `close_ticket` fails with "Elicitation is disabled". Turn elicitation on so the tool can ask. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { CloseTicket } from "./close-ticket.tool"; @App({ id: "help-desk", name: "Help desk", tools: [CloseTicket] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { App, FrontMcp } from "@frontmcp/sdk"; import { CloseTicket } from "./close-ticket.tool"; @App({ id: "help-desk", name: "Help desk", tools: [CloseTicket] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, }) export default class Server {} ``` ```ts close-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket. Asks the user to confirm first.", inputSchema: { id: z.string() }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const answer = await this.elicit(`Close ${id}?`, z.object({ confirm: z.boolean() })); return { id, closed: answer.status === "accept" && answer.content?.confirm === true }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts main.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("close_ticket asks the user and closes on yes", async ({ mcp }) => { let asked = false; mcp.onElicitation(() => { asked = true; return { action: "accept", content: { confirm: true } }; }); const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result).toBeSuccessful(); expect(asked).toBe(true); expect(result.json()).toEqual({ id: "T-1", closed: true }); }); ``` **Hint:** It's one option on `@FrontMcp`, next to `info` and `apps`. **Solution:** `elicitation: { enabled: true }` in `@FrontMcp` lets tools call `this.elicit()`. With it, FrontMCP also adds the `sendElicitationResult` fallback tool for clients on older protocol versions that can't show forms. The Playground speaks 2026-07-28, so its Capabilities tab still lists only `close_ticket`. --- # Reporting Progress and Logs > How a long-running tool tells the client how far along it is and what it's doing, with this.progress() and this.notify(), and how clients opt in under MCP 2026-07-28. Source: https://frontmcp.dev/learn/reporting-progress [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A tool that takes ten seconds looks exactly like a tool that's stuck, until it returns. FrontMCP tools report while they work with `this.progress()` and `this.notify()`: how much is done, and anything worth knowing along the way. The client can show a progress bar, or a line in a log, and the person waiting knows the call is still alive. **You will learn** - How to report progress with `this.progress()` - How to send log messages with `this.notify()`, and which level to use - How a client asks for notifications under MCP 2026-07-28, and what the response looks like - What happens when a client doesn't ask - How to test progress and logs ## A tool that goes quiet This tool exports every ticket to a CSV file, one ticket at a time. Each ticket takes a moment: Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts export-tickets.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; import { exportRow, tickets } from "./store"; @Tool({ name: "export_tickets", description: "Export every support ticket to tickets.csv. Takes a few seconds.", inputSchema: {}, }) export class ExportTickets extends ToolContext { async execute() { const rows: string[] = []; for (const ticket of tickets) { rows.push(await exportRow(ticket)); } return { file: "tickets.csv", rows: rows.length }; } } ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-2", title: "" }, { id: "T-3", title: "Login link expired" }, { id: "T-4", title: "Password reset email missing" }, { id: "T-5", title: "Invoice total is wrong" }, ]; /** Pretend each ticket takes a moment to export. */ export async function exportRow(ticket: { id: string; title: string }) { await new Promise((resolve) => setTimeout(resolve, 150)); return `${ticket.id},"${ticket.title}"`; } ``` With five tickets that's under a second. With five thousand, the user stares at a spinner for minutes and can't tell a slow export from a stuck one. Nothing about this tool is wrong, except that it says nothing until it's done. ## Reporting progress `this.progress(progress, total, message)` sends a progress notification to the client that made the call: - `progress` is how much is done so far. It should go up with every call; the MCP spec requires it. - `total` is how much there is in all, if you know it. Leave it out if you don't. - `message` is a short description of the current step. It's optional too. Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts export-tickets.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; import { exportRow, tickets } from "./store"; @Tool({ name: "export_tickets", description: "Export every support ticket to tickets.csv. Takes a few seconds.", inputSchema: {}, }) export class ExportTickets extends ToolContext { async execute() { const rows: string[] = []; for (const [i, ticket] of tickets.entries()) { rows.push(await exportRow(ticket)); await this.progress(i + 1, tickets.length, `Exported ${ticket.id}`); } return { file: "tickets.csv", rows: rows.length }; } } ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-2", title: "" }, { id: "T-3", title: "Login link expired" }, { id: "T-4", title: "Password reset email missing" }, { id: "T-5", title: "Invoice total is wrong" }, ]; /** Pretend each ticket takes a moment to export. */ export async function exportRow(ticket: { id: string; title: string }) { await new Promise((resolve) => setTimeout(resolve, 150)); return `${ticket.id},"${ticket.title}"`; } ``` The Call tab now shows a progress bar and five `progress` notifications above the result. A real client gets each one as it's sent, while the tool is still running. The Playground collects the whole response first, so here they appear together when the call ends. Report after each real unit of work, like a ticket, a page or a file. Progress that jumps from 0 to 100% at the end doesn't tell anyone anything. ## Sending log messages Progress says how far along a tool is. `this.notify(message, level)` says what's happening, as a log message: Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts export-tickets.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; import { exportRow, tickets } from "./store"; @Tool({ name: "export_tickets", description: "Export every support ticket to tickets.csv. Takes a few seconds.", inputSchema: {}, }) export class ExportTickets extends ToolContext { async execute() { await this.notify(`Exporting ${tickets.length} tickets to tickets.csv`); const rows: string[] = []; for (const [i, ticket] of tickets.entries()) { if (!ticket.title) await this.notify(`${ticket.id} has no title. It's exported with an empty one.`, "warning"); rows.push(await exportRow(ticket)); await this.progress(i + 1, tickets.length, `Exported ${ticket.id}`); } await this.notify({ file: "tickets.csv", bytes: rows.join("\n").length }, "debug"); return { file: "tickets.csv", rows: rows.length }; } } ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-2", title: "" }, { id: "T-3", title: "Login link expired" }, { id: "T-4", title: "Password reset email missing" }, { id: "T-5", title: "Invoice total is wrong" }, ]; /** Pretend each ticket takes a moment to export. */ export async function exportRow(ticket: { id: string; title: string }) { await new Promise((resolve) => setTimeout(resolve, 150)); return `${ticket.id},"${ticket.title}"`; } ``` Each call to `notify()` sends a `notifications/message`: - A string becomes `data: { message: "..." }`. An object is sent as `data` as it is, for clients that read structured logs. - `level` is one of MCP's log levels, from least to most severe: `"debug"`, `"info"`, `"notice"`, `"warning"`, `"error"`, `"critical"`, `"alert"` and `"emergency"`. It defaults to `"info"`. - FrontMCP sets `logger` to the tool's name, so the client knows which tool said it. The client chooses the lowest level it wants, and FrontMCP drops anything below it. The Call tab asks for `"info"` and up, which is why the `debug` message with the byte count isn't in the list above. > **Note** > > A client may show notifications to the user or write them to a log, and it doesn't have to pass them to the model. The model reads the result. If the model needs to know something, like which tickets were skipped, put it in the result, and use `notify()` for the person watching. ## How a client asks for notifications In MCP 2026-07-28, notifications belong to the request that caused them, and a client asks for them in that request's `_meta`: - a `progressToken` asks for progress. The server copies the token into every progress notification, so a client with several calls in flight knows which one each update is about. - `io.modelcontextprotocol/logLevel` asks for log messages at that level and above. Open the **Wire** tab in the example above and expand the `tools/call`. The request carries both: ```json { "method": "tools/call", "params": { "name": "export_tickets", "arguments": {}, "_meta": { "progressToken": "progress-1", "io.modelcontextprotocol/logLevel": "info" } } } ``` (The real request's `_meta` also holds the protocol version, client info and capabilities.) When a request asks for either, FrontMCP answers with `Content-Type: text/event-stream` instead of plain JSON. Each notification is an event, sent as it happens, and the last event is the result: ```text event: message data: {"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","logger":"export_tickets","data":{"message":"Exporting 5 tickets to tickets.csv"}}} event: message data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"progress-1","progress":1,"total":5,"message":"Exported T-1"}} … event: message data: {"jsonrpc":"2.0","id":6,"result":{"content":[…],"structuredContent":{"file":"tickets.csv","rows":5}}} ``` The Wire tab labels this response **SSE** and shows each event before the final response. When the call ends, the stream ends with it. A client in your own code asks the same way. One made with [`connect()`](https://frontmcp.dev/reference/sdk/connect#hearing-a-tools-progress) passes `{ onProgress }` as `callTool()`'s third argument, which sends a progress token with that call, and gets each update: see [`this.progress()`](https://frontmcp.dev/reference/sdk/progress#asking-for-progress). (Changed in 1.9.3: before, a `connect()` client had no way to ask.) ## When the client doesn't ask Not every client asks for notifications, and a client that asks for some calls may not ask for others. A tool has to work either way. This version puts what `progress()` returned into the result, so you can see it: Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts export-tickets.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; import { exportRow, tickets } from "./store"; @Tool({ name: "export_tickets", description: "Export every support ticket to tickets.csv. Takes a few seconds.", inputSchema: {}, }) export class ExportTickets extends ToolContext { async execute() { let reported = false; for (const [i, ticket] of tickets.entries()) { await exportRow(ticket); reported = await this.progress(i + 1, tickets.length, `Exported ${ticket.id}`); } // Only here to show what progress() returned. return { file: "tickets.csv", rows: tickets.length, progressReported: reported }; } } ``` ```ts no-listener.test.ts import { test, expect } from "@frontmcp/testing"; test("the export works for a client that doesn't ask for notifications", async ({ mcp }) => { const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "export_tickets", arguments: {} }, }); expect(response.result).toMatchObject({ structuredContent: { file: "tickets.csv", rows: 5, progressReported: false }, }); }); ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-2", title: "" }, { id: "T-3", title: "Login link expired" }, { id: "T-4", title: "Password reset email missing" }, { id: "T-5", title: "Invoice total is wrong" }, ]; /** Pretend each ticket takes a moment to export. */ export async function exportRow(ticket: { id: string; title: string }) { await new Promise((resolve) => setTimeout(resolve, 150)); return `${ticket.id},"${ticket.title}"`; } ``` The first call asked for progress, so `progressReported` is `true`. Untick **Stream progress & logs** and call again: the response is plain JSON, with no notifications, and `progressReported` is `false`. The export itself is the same. `progress()` and `notify()` return `true` when the notification was queued for the client, and `false` when the client didn't ask for it (or, for `notify()`, asked only for higher levels). They never throw for that reason, so you don't need to check before calling them. The test file does the same thing from code: `mcp.raw.request()` sends a request exactly as you write it, without a `progressToken`. ## Testing progress and logs The test client records the notifications that come back. `mcp.notifications.collectProgress().all` lists the progress updates, and `mcp.notifications.collect().received` lists every notification, logs included. In the Playground, each `mcp.tools.call()` asks for progress and for every log level, `debug` included: ```ts export-tickets.test.ts active import { test, expect } from "@frontmcp/testing"; test("reports progress once per ticket", async ({ mcp }) => { const progress = mcp.notifications.collectProgress(); const result = await mcp.tools.call("export_tickets", {}); expect(result).toBeSuccessful(); expect(progress.all.map((p) => p.progress)).toEqual([1, 2, 3, 4, 5]); expect(progress.all.every((p) => p.total === 5)).toBe(true); }); type LogMessage = { level: string; logger?: string; data: { message?: string } }; test("warns about the ticket with no title", async ({ mcp }) => { const notifications = mcp.notifications.collect(); await mcp.tools.call("export_tickets", {}); const warnings = notifications.received .filter((n) => n.method === "notifications/message") .map((n) => n.params as LogMessage) .filter((log) => log.level === "warning"); expect(warnings).toHaveLength(1); expect(warnings[0].data.message).toContain("T-2"); }); ``` ```ts export-tickets.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; import { exportRow, tickets } from "./store"; @Tool({ name: "export_tickets", description: "Export every support ticket to tickets.csv. Takes a few seconds.", inputSchema: {}, }) export class ExportTickets extends ToolContext { async execute() { await this.notify(`Exporting ${tickets.length} tickets to tickets.csv`); const rows: string[] = []; for (const [i, ticket] of tickets.entries()) { if (!ticket.title) await this.notify(`${ticket.id} has no title. It's exported with an empty one.`, "warning"); rows.push(await exportRow(ticket)); await this.progress(i + 1, tickets.length, `Exported ${ticket.id}`); } await this.notify({ file: "tickets.csv", bytes: rows.join("\n").length }, "debug"); return { file: "tickets.csv", rows: rows.length }; } } ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-2", title: "" }, { id: "T-3", title: "Login link expired" }, { id: "T-4", title: "Password reset email missing" }, { id: "T-5", title: "Invoice total is wrong" }, ]; /** Pretend each ticket takes a moment to export. */ export async function exportRow(ticket: { id: string; title: string }) { await new Promise((resolve) => setTimeout(resolve, 150)); return `${ticket.id},"${ticket.title}"`; } ``` > **Pitfall: Under frontmcp test, ask for notifications and wait for them** > > The Playground's test client asks for progress and for every log level with each call. The one `frontmcp test` uses records notifications too, but sends a `progressToken` only once `collectProgress()` is active, never sets a log level by itself, and can return from `tools.call()` before the notifications arrive. So in your project, call `collectProgress()` before the call, send `logging/setLevel` for log messages, and wait with `waitForComplete()` or `waitFor()`. [Checking notifications](https://frontmcp.dev/reference/testing#checking-notifications) has a test that passes in both. ## Recap - `this.progress(progress, total, message)` reports how far along a tool is. `progress` should go up with every call, and `total` and `message` are optional. - `this.notify(message, level)` sends a log message. A string becomes `data.message`, an object is sent as `data`, and `level` defaults to `"info"`. - Under 2026-07-28 a client asks per request, with a `progressToken` and `io.modelcontextprotocol/logLevel` in `_meta`. The response is then an event stream: notifications first, the result last. - A client that doesn't ask gets a plain JSON result. `progress()` and `notify()` return `false`, and the call works the same. - Notifications are for the client and the person watching. Put what the model needs in the result. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Report progress while importing `import_tickets` copies tickets from the old help desk, one at a time, and says nothing until it's done. Report progress after each ticket, with the total number of tickets. Initial call configuration: ```js { tool: "import_tickets", arguments: { tickets: [{ id: "OLD-1", title: "Printer on fire" }, { id: "OLD-2", title: "Cannot log in" }, { id: "OLD-3", title: "Refund request" }] } } ``` ```ts import-tickets.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const imported: { id: string; title: string }[] = []; @Tool({ name: "import_tickets", description: "Import tickets from the old help desk. Takes about a second per 5 tickets.", inputSchema: { tickets: z.array(z.object({ id: z.string(), title: z.string() })).min(1).max(20), }, }) export class ImportTickets extends ToolContext { async execute({ tickets }: { tickets: { id: string; title: string }[] }) { for (const ticket of tickets) { await new Promise((resolve) => setTimeout(resolve, 100)); imported.push(ticket); } return { imported: tickets.length }; } } ``` **Solution file (alternative to the starter):** ```ts import-tickets.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const imported: { id: string; title: string }[] = []; @Tool({ name: "import_tickets", description: "Import tickets from the old help desk. Takes about a second per 5 tickets.", inputSchema: { tickets: z.array(z.object({ id: z.string(), title: z.string() })).min(1).max(20), }, }) export class ImportTickets extends ToolContext { async execute({ tickets }: { tickets: { id: string; title: string }[] }) { for (const [i, ticket] of tickets.entries()) { await new Promise((resolve) => setTimeout(resolve, 100)); imported.push(ticket); await this.progress(i + 1, tickets.length, `Imported ${ticket.id}`); } return { imported: tickets.length }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts import-tickets.test.ts hidden import { test, expect } from "@frontmcp/testing"; const three = [ { id: "OLD-1", title: "Printer on fire" }, { id: "OLD-2", title: "Cannot log in" }, { id: "OLD-3", title: "Refund request" }, ]; test("there's a progress update for each ticket", async ({ mcp }) => { const progress = mcp.notifications.collectProgress(); await mcp.tools.call("import_tickets", { tickets: three }); expect(progress.all.length).toBeGreaterThanOrEqual(3); }); test("every update has `total` set to the number of tickets", async ({ mcp }) => { const progress = mcp.notifications.collectProgress(); await mcp.tools.call("import_tickets", { tickets: three }); expect(progress.all.length).toBeGreaterThan(0); expect(progress.all.map((p) => p.total)).toEqual(progress.all.map(() => 3)); }); test("progress goes up and ends at the total", async ({ mcp }) => { const progress = mcp.notifications.collectProgress(); await mcp.tools.call("import_tickets", { tickets: three }); const values = progress.all.map((p) => p.progress); expect(values.length).toBeGreaterThan(0); expect(values.every((v, i) => i === 0 || v > values[i - 1])).toBe(true); expect(values.at(-1)).toBe(3); }); test("the import still returns its result", async ({ mcp }) => { const result = await mcp.tools.call("import_tickets", { tickets: three }); expect(result.json()).toEqual({ imported: 3 }); }); ``` **Hint:** `tickets.entries()` gives you the index as well as the ticket. The first ticket done is progress `1`, not `0`. **Solution:** After each ticket is imported, `this.progress(i + 1, tickets.length, ...)` reports how many are done out of how many. The last update has `progress` equal to `total`, which is how a client knows the bar is full. ### Challenge: Warn about skipped tickets Tickets with an empty title can't be imported, and this tool skips them without a word. Send a `"warning"` log message for each skipped ticket, naming its id. Don't warn about tickets that were imported. Initial call configuration: ```js { tool: "import_tickets", arguments: { tickets: [{ id: "OLD-1", title: "Printer on fire" }, { id: "OLD-2", title: "" }, { id: "OLD-3", title: "Refund request" }] } } ``` ```ts import-tickets.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const imported: { id: string; title: string }[] = []; @Tool({ name: "import_tickets", description: "Import tickets from the old help desk. Tickets without a title are skipped.", inputSchema: { tickets: z.array(z.object({ id: z.string(), title: z.string() })).min(1).max(20), }, }) export class ImportTickets extends ToolContext { async execute({ tickets }: { tickets: { id: string; title: string }[] }) { let count = 0; for (const ticket of tickets) { if (!ticket.title.trim()) continue; imported.push(ticket); count++; } return { imported: count }; } } ``` **Solution file (alternative to the starter):** ```ts import-tickets.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const imported: { id: string; title: string }[] = []; @Tool({ name: "import_tickets", description: "Import tickets from the old help desk. Tickets without a title are skipped.", inputSchema: { tickets: z.array(z.object({ id: z.string(), title: z.string() })).min(1).max(20), }, }) export class ImportTickets extends ToolContext { async execute({ tickets }: { tickets: { id: string; title: string }[] }) { let count = 0; for (const ticket of tickets) { if (!ticket.title.trim()) { await this.notify(`Skipped ${ticket.id}: it has no title.`, "warning"); continue; } imported.push(ticket); count++; } return { imported: count }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts import-tickets.test.ts hidden import { test, expect } from "@frontmcp/testing"; const warningsIn = (notifications: { received: any[] }) => notifications.received.filter((n) => n.method === "notifications/message" && n.params.level === "warning"); test("a skipped ticket gets a warning that names it", async ({ mcp }) => { const notifications = mcp.notifications.collect(); await mcp.tools.call("import_tickets", { tickets: [{ id: "OLD-1", title: "Printer on fire" }, { id: "OLD-2", title: "" }], }); const warnings = warningsIn(notifications); expect(warnings).toHaveLength(1); expect(JSON.stringify(warnings[0].params.data)).toContain("OLD-2"); }); test("each skipped ticket gets its own warning", async ({ mcp }) => { const notifications = mcp.notifications.collect(); await mcp.tools.call("import_tickets", { tickets: [{ id: "OLD-3", title: " " }, { id: "OLD-4", title: "" }, { id: "OLD-5", title: "Refund request" }], }); const text = warningsIn(notifications).map((w) => JSON.stringify(w.params.data)); expect(text).toHaveLength(2); expect(text.some((t) => t.includes("OLD-3"))).toBe(true); expect(text.some((t) => t.includes("OLD-4"))).toBe(true); }); test("no warnings when nothing is skipped", async ({ mcp }) => { const notifications = mcp.notifications.collect(); await mcp.tools.call("import_tickets", { tickets: [{ id: "OLD-6", title: "Cannot log in" }] }); expect(warningsIn(notifications)).toHaveLength(0); }); test("the import still counts what it imported", async ({ mcp }) => { const result = await mcp.tools.call("import_tickets", { tickets: [{ id: "OLD-7", title: "Printer on fire" }, { id: "OLD-8", title: "" }], }); expect(result.json()).toEqual({ imported: 1 }); }); ``` **Hint:** `this.notify(message, "warning")`. Put the ticket's id in the message. **Solution:** Each skipped ticket sends one `notifications/message` at level `"warning"`, which clients can show differently from routine `"info"` messages. The result is unchanged: the warnings are for the person watching the import. ### Challenge: Tell the model what was skipped This version warns about skipped tickets, but the model only gets `{ imported: 1 }` and has no idea anything went wrong. Add a `skipped` list of ticket ids to the result, so the model can tell the user. It must work for clients that don't ask for notifications, too. Initial call configuration: ```js { tool: "import_tickets", arguments: { tickets: [{ id: "OLD-1", title: "Printer on fire" }, { id: "OLD-2", title: "" }] } } ``` ```ts import-tickets.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const imported: { id: string; title: string }[] = []; @Tool({ name: "import_tickets", description: "Import tickets from the old help desk. Tickets without a title are skipped.", inputSchema: { tickets: z.array(z.object({ id: z.string(), title: z.string() })).min(1).max(20), }, }) export class ImportTickets extends ToolContext { async execute({ tickets }: { tickets: { id: string; title: string }[] }) { let count = 0; for (const ticket of tickets) { if (!ticket.title.trim()) { await this.notify(`Skipped ${ticket.id}: it has no title.`, "warning"); continue; } imported.push(ticket); count++; } return { imported: count }; } } ``` **Solution file (alternative to the starter):** ```ts import-tickets.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const imported: { id: string; title: string }[] = []; @Tool({ name: "import_tickets", description: "Import tickets from the old help desk. Tickets without a title are skipped and listed in `skipped`.", inputSchema: { tickets: z.array(z.object({ id: z.string(), title: z.string() })).min(1).max(20), }, }) export class ImportTickets extends ToolContext { async execute({ tickets }: { tickets: { id: string; title: string }[] }) { const skipped: string[] = []; for (const ticket of tickets) { if (!ticket.title.trim()) { skipped.push(ticket.id); await this.notify(`Skipped ${ticket.id}: it has no title.`, "warning"); continue; } imported.push(ticket); } return { imported: tickets.length - skipped.length, skipped }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts import-tickets.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the result lists the skipped ids in `skipped`", async ({ mcp }) => { const result = await mcp.tools.call("import_tickets", { tickets: [{ id: "OLD-1", title: "Printer on fire" }, { id: "OLD-2", title: "" }, { id: "OLD-3", title: " " }], }); expect(result.json()).toEqual({ imported: 1, skipped: ["OLD-2", "OLD-3"] }); }); test("`skipped` is empty when nothing is skipped", async ({ mcp }) => { const result = await mcp.tools.call("import_tickets", { tickets: [{ id: "OLD-4", title: "Cannot log in" }] }); expect(result.json()).toEqual({ imported: 1, skipped: [] }); }); test("a client that doesn't ask for notifications still gets `skipped`", async ({ mcp }) => { const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "import_tickets", arguments: { tickets: [{ id: "OLD-5", title: "" }] } }, }); expect(response.result).toMatchObject({ structuredContent: { imported: 0, skipped: ["OLD-5"] } }); }); test("skipped tickets still get a warning", async ({ mcp }) => { const notifications = mcp.notifications.collect(); await mcp.tools.call("import_tickets", { tickets: [{ id: "OLD-6", title: "" }] }); expect(notifications.received.some((n) => n.params?.level === "warning")).toBe(true); }); ``` **Hint:** Collect the ids in an array as you skip them, and return it next to `imported`. **Solution:** The warning tells the person watching; `skipped` tells the model, which reads the result whether or not the client asked for notifications. Keep both: they're for different readers. --- # Structuring a Server > Where the code that isn't any one tool's job goes in a FrontMCP server. Providers for shared services and state, plugins for reusable behaviour, and hooks that run around every call. Source: https://frontmcp.dev/learn/structuring-a-server [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 [Grouping Capabilities into Apps](https://frontmcp.dev/learn/grouping-capabilities-into-apps) split a server into apps, and showed a provider shared between them. As a server grows, more of its code stops belonging to any one tool: the store every tool reads, the settings they all follow, the audit log every call should reach, the checks that should run before any tool does. This chapter is about where that code goes in a FrontMCP server, so that tools stay small and new ones get it all for free. **In this chapter** - [How to share services and state between tools with providers](https://frontmcp.dev/learn/sharing-state-with-providers) - [How to package behaviour for many tools as a plugin](https://frontmcp.dev/learn/extending-with-plugins) - [How to run code before and after the stages of every call with hooks](https://frontmcp.dev/learn/hooking-into-calls) ## Sharing state with providers A variable at the top of a file is shared by every request, and nothing can replace it in a test. A **provider** is a class FrontMCP creates for you and hands to any tool that asks with `this.get()`. Its scope decides how long it lives: `GLOBAL` for as long as the server runs, `CONTEXT` for one request. Call `close_ticket` twice, once for `T-1` and once for `T-3`: the store remembers the first call, and each receipt only has its own steps. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts help-desk.app.ts import { App, Provider, ProviderScope, Tool, ToolContext, z } from "@frontmcp/sdk"; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { open = new Set(["T-1", "T-3"]); } @Provider({ name: "Receipt", scope: ProviderScope.CONTEXT }) export class Receipt { steps: string[] = []; } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const store = this.get(TicketStore); this.get(Receipt).steps.push(store.open.delete(id) ? `closed ${id}` : `${id} was already closed`); return { receipt: this.get(Receipt).steps, stillOpen: [...store.open] }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], providers: [TicketStore, Receipt] }) export class HelpDeskApp {} ``` ### [Sharing State with Providers](https://frontmcp.dev/learn/sharing-state-with-providers) Learn why module-level state breaks under concurrent calls, what `GLOBAL` and `CONTEXT` mean per request, how to build a provider from configuration, and how to swap one for a fake in tests. ## Extending with plugins Some behaviour belongs around every tool rather than inside one: an audit log, a maintenance switch, a cache. A **plugin** (`@Plugin`) packages it, with its own providers, the tools it adds and the hooks it runs, and an app turns it on in `plugins`. Call `close_ticket`, then `audit_log`: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts help-desk.app.ts import { App, DynamicPlugin, FlowCtxOf, Plugin, Provider, Tool, ToolContext, ToolHook, z } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: string[] = []; } @Tool({ name: "audit_log", description: "Show every tool call made so far", inputSchema: {} }) export class ShowAuditLog extends ToolContext { async execute() { return { entries: [...this.get(AuditLog).entries] }; } } @Plugin({ name: "audit", providers: [AuditLog], tools: [ShowAuditLog] }) export class AuditPlugin extends DynamicPlugin { @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { this.get(AuditLog).entries.push(`${ctx.state.tool?.metadata.name} ${JSON.stringify(ctx.state.toolContext?.input)}`); } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], plugins: [AuditPlugin] }) export class HelpDeskApp {} ``` ### [Extending with Plugins](https://frontmcp.dev/learn/extending-with-plugins) Learn what a plugin can add to an app, how it shares its providers, how to make it configurable, where to register it, and what the official plugins do. ## Hooking into calls Every `tools/call` runs through a flow of named stages: find the tool, validate the arguments, execute, format the result. A **hook** in a plugin runs just before (`Will`) or just after (`Did`) a stage, on every call. This one cleans up ticket ids before the schema checks them, so `" t-2 "` works: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: " t-2 " } } ``` ```ts help-desk.app.ts import { App, DynamicPlugin, FlowCtxOf, Plugin, Tool, ToolContext, ToolHook, z } from "@frontmcp/sdk"; @Plugin({ name: "ticket-ids" }) export class TicketIdsPlugin extends DynamicPlugin { @ToolHook.Will("validateInput") async normalizeTicketId(ctx: FlowCtxOf<"tools:call-tool">) { const args = ctx.state.input?.arguments; if (typeof args?.id === "string") args.id = args.id.trim().toUpperCase(); } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Invoice total is wrong", status: "closed" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], plugins: [TicketIdsPlugin] }) export class HelpDeskApp {} ``` ### [Hooking into Calls](https://frontmcp.dev/learn/hooking-into-calls) Learn the stages of a tool call, what a hook can read and change at each, how to log calls, block them and rewrite their results, and the order hooks run in. ## What's next? Start the chapter with [Sharing State with Providers](https://frontmcp.dev/learn/sharing-state-with-providers). After it, [Securing a Server](https://frontmcp.dev/learn/securing-a-server) covers who may call your server and what each caller is allowed to do. --- # Sharing State with Providers > Why tools shouldn't keep shared state in module variables, and how @Provider shares services instead. Scopes per request, factories built from configuration, and swapping a provider in tests. Source: https://frontmcp.dev/learn/sharing-state-with-providers [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Tools rarely work alone. They read the same ticket store, call the same API client and follow the same settings. The quickest way to share something between tools is a variable at the top of a file, and that works right up until two calls run at the same time, or a test needs a different one. A **provider** is FrontMCP's place for shared things. You declare it with `@Provider`, register it where it belongs, and any tool that needs it asks for it with `this.get()`. FrontMCP decides when to create it and how long it lives. **You will learn** - Why a module-level variable is the wrong place for shared state - How `@Provider` and `this.get()` share one service between tools - What `GLOBAL` and `CONTEXT` scopes mean for each request - How to build a provider from configuration with a factory - How to swap a provider for a fake in tests, and why that decides where you register it ## State in a module variable `close_ticket` returns a receipt of what it did, so the model can tell the user. It collects the steps in an array that lives at the top of `receipt.ts`, and empties it at the start of each call: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1", notify: true } } ``` ```ts close-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { receipt, sendEmail } from "./receipt"; @Tool({ name: "close_ticket", description: "Close a support ticket, and optionally email the customer. Returns a receipt of the steps taken.", inputSchema: { id: z.string().describe("Ticket id, like T-1"), notify: z.boolean().optional().describe("Email the customer that the ticket is closed"), }, }) export class CloseTicket extends ToolContext { async execute({ id, notify }: { id: string; notify?: boolean }) { receipt.length = 0; // start this call's receipt receipt.push(`closed ${id}`); if (notify) { await sendEmail(id); receipt.push(`emailed the customer about ${id}`); } return { id, receipt: [...receipt] }; } } ``` ```ts receipt.ts // 🚩 One array for the whole server, shared by every call export const receipt: string[] = []; export async function sendEmail(ticketId: string) { await new Promise((resolve) => setTimeout(resolve, 200)); // stands in for a mail server } ``` ```ts receipt.test.ts import { test, expect } from "@frontmcp/testing"; test("one call on its own gets the right receipt", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1", notify: true }); expect(result.json().receipt).toEqual(["closed T-1", "emailed the customer about T-1"]); }); test("two calls at once share one receipt", async ({ mcp }) => { const [first, second] = await Promise.all([ mcp.tools.call("close_ticket", { id: "T-1", notify: true }), mcp.tools.call("close_ticket", { id: "T-2" }), ]); expect(second.json().receipt).toEqual(["closed T-2"]); // 🚩 T-1's receipt lost its first step and gained one from T-2 expect(first.json().receipt).toEqual(["closed T-2", "emailed the customer about T-1"]); }); ``` One call at a time, the receipt is right. Open the **Tests** tab to see two calls at once. While the first call waits for the mail server, the second one empties the array and writes its own step, and the first call's receipt comes back with a step from a ticket it never touched. A server handles many requests at the same time, from many clients, so this isn't rare in production. A module variable belongs to the file, not to the call, and that causes more than this one bug: 1. **Every request shares it.** Anything that should belong to one call, like this receipt, leaks between calls. 2. **Nothing can replace it.** A test can't give the tool a different store or a fake mail server, because the tool imports the real one directly. 3. **It's built when the file is imported**, before your configuration is read or a database is connected. 4. **It's invisible.** Nothing in the app's declaration says `close_ticket` depends on it. Providers fix all four, and the rest of this lesson shows how. For a value one caller should get back on their next call, like a preference, [Remembering Across Calls](https://frontmcp.dev/learn/remembering-across-calls) uses the Remember plugin. ## Sharing a service with `@Provider` A provider is a class that FrontMCP creates for you. Using one takes three steps: decorate the class with `@Provider`, list it in the app's `providers`, and get it inside `execute()` with `this.get()`: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return this.get(TicketStore).close(id); } } @Tool({ name: "list_open_tickets", description: "List the support tickets that are still open", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class ListOpenTickets extends ToolContext { async execute() { return { tickets: this.get(TicketStore).open().map((t) => t.id) }; } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; status: "open" | "closed" }; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; open() { return this.tickets.filter((t) => t.status === "open"); } close(id: string) { const ticket = this.tickets.find((t) => t.id === id); if (ticket) ticket.status = "closed"; return { id, status: ticket?.status ?? "not found" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, ListOpenTickets } from "./tools"; import { TicketStore } from "./ticket-store"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket, ListOpenTickets], providers: [TicketStore], }) export class HelpDeskApp {} ``` ```ts store.test.ts import { test, expect } from "@frontmcp/testing"; test("a ticket closed by one tool is gone from the other's list", async ({ mcp }) => { expect((await mcp.tools.call("list_open_tickets", {})).json()).toEqual({ tickets: ["T-1", "T-3"] }); await mcp.tools.call("close_ticket", { id: "T-1" }); expect((await mcp.tools.call("list_open_tickets", {})).json()).toEqual({ tickets: ["T-3"] }); }); ``` - **`@Provider({ name })`** marks the class. `name` shows up in logs and error messages; omit it with `@Provider()` to use the class name. Changed in 1.10.16: before, `name` was required. - **`providers: [TicketStore]`** registers it. Decorating the class isn't enough: if neither the tool's app nor the server lists it, the call fails with `Provider "TicketStore" is not available`. - **`this.get(TicketStore)`** returns the instance. The class itself is the key you ask with, so `this.get()` knows the type it returns. Both tools get the same `TicketStore`, so a ticket closed by one is gone from the other's list. The tools also say what they depend on now: the app's `providers` lists it, and a test can put something else in its place. > **Note** > > `ProviderScope.GLOBAL` is the default, and means one instance for each place the provider is registered. List the same class in two apps and each app gets its own. To share one instance between apps, register it once on the server, as [Grouping Capabilities into Apps](https://frontmcp.dev/learn/grouping-capabilities-into-apps#sharing-a-provider-between-apps) shows. ## State for one request: `CONTEXT` The ticket store should outlive every call. The receipt should live for exactly one. That's what a provider's **scope** decides: | Scope | One instance per | Created | | --- | --- | --- | | `ProviderScope.GLOBAL` (the default) | place it's registered: an app, or the server | When the server starts | | `ProviderScope.CONTEXT` | request, under MCP 2026-07-28 | At the start of each tool call | Here is the receipt as a `CONTEXT` provider. Every `this.get(Receipt)` during one call returns the same receipt, and the next call gets a new one: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1", notify: true } } ``` ```ts close-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { Receipt, sendEmail } from "./receipt"; @Tool({ name: "close_ticket", description: "Close a support ticket, and optionally email the customer. Returns a receipt of the steps taken.", inputSchema: { id: z.string().describe("Ticket id, like T-1"), notify: z.boolean().optional().describe("Email the customer that the ticket is closed"), }, }) export class CloseTicket extends ToolContext { async execute({ id, notify }: { id: string; notify?: boolean }) { const receipt = this.get(Receipt); receipt.add(`closed ${id}`); if (notify) { await sendEmail(id); receipt.add(`emailed the customer about ${id}`); } return { id, receipt: receipt.steps }; } } ``` ```ts receipt.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; // ✅ A new receipt for every request @Provider({ name: "Receipt", scope: ProviderScope.CONTEXT }) export class Receipt { steps: string[] = []; add(step: string) { this.steps.push(step); } } export async function sendEmail(ticketId: string) { await new Promise((resolve) => setTimeout(resolve, 200)); // stands in for a mail server } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket } from "./close-ticket.tool"; import { Receipt } from "./receipt"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], providers: [Receipt] }) export class HelpDeskApp {} ``` ```ts receipt.test.ts import { test, expect } from "@frontmcp/testing"; // In Node the two calls run at once. Your browser has no AsyncLocalStorage, so there two calls // that overlap can see each other's providers: the Playground sends them one after the other. const inNode = typeof (globalThis as { WorkerGlobalScope?: unknown }).WorkerGlobalScope === "undefined"; test("two calls keep separate receipts", async ({ mcp }) => { const calls = [ () => mcp.tools.call("close_ticket", { id: "T-1", notify: true }), () => mcp.tools.call("close_ticket", { id: "T-2" }), ]; const [first, second] = inNode ? await Promise.all(calls.map((call) => call())) : [await calls[0](), await calls[1]()]; expect(first.json().receipt).toEqual(["closed T-1", "emailed the customer about T-1"]); expect(second.json().receipt).toEqual(["closed T-2"]); }); ``` The code no longer empties anything, because there's nothing left over to empty. The **Tests** tab runs the same two calls as before, and each receipt has only its own steps. (In Node they run at once. Your browser can't keep two overlapping calls apart, so the Playground runs them one after the other there.) "Per request" is how MCP 2026-07-28 works: every request stands alone, and there are no sessions to keep a provider alive between them. Clients on older protocol versions open a session, and for them a `CONTEXT` provider lasts for the whole session instead. If something must survive between calls, don't count on either: make it `GLOBAL`, or better, keep it in a database. > **Pitfall: A GLOBAL provider can't use a CONTEXT one** > > A `GLOBAL` provider lives longer than any request, so FrontMCP won't build one that depends on a `CONTEXT` provider: the server refuses to start with `Invalid dependency: DEFAULT-scoped provider … cannot depend on scoped provider …`. Pass the per-request value into the global provider's methods as an argument instead. ### When exactly is a provider built? A `GLOBAL` provider is built once, before the server answers its first request. A `CONTEXT` provider is built at the start of **every tool call in its app**, whether or not the tool asks for it. This example counts constructions. Call `ping` a few times: Initial call configuration: ```js { tool: "ping", arguments: {} } ``` ```ts help-desk.app.ts active import { App, Provider, ProviderScope, Tool, ToolContext } from "@frontmcp/sdk"; const built: string[] = []; @Provider({ name: "Shared", scope: ProviderScope.GLOBAL }) export class Shared { constructor() { built.push("Shared"); } } @Provider({ name: "PerRequest", scope: ProviderScope.CONTEXT }) export class PerRequest { constructor() { built.push("PerRequest"); } } @Tool({ name: "ping", description: "List the providers built so far", inputSchema: {} }) export class Ping extends ToolContext { async execute() { return { built: [...built] }; // never calls this.get() } } @App({ id: "help-desk", name: "Help Desk", tools: [Ping], providers: [Shared, PerRequest] }) export class HelpDeskApp {} ``` ```ts built.test.ts import { test, expect } from "@frontmcp/testing"; test("CONTEXT providers are built for every call, even unused", async ({ mcp }) => { await mcp.tools.call("ping", {}); await mcp.tools.call("ping", {}); const result = await mcp.tools.call("ping", {}); expect(result.json().built).toEqual(["Shared", "PerRequest", "PerRequest", "PerRequest"]); }); ``` So keep `CONTEXT` providers cheap to construct: hold per-request data in them, and leave connections and clients to `GLOBAL` ones. ## Building a provider from configuration Some things you want to share aren't classes you wrote: a settings object, a client from a library, something that has to be loaded first. For those, register a **factory**: an object with the key to provide, a `name`, the providers it needs, and a function that builds the value. The SLA hours below come from `Settings`, which stands in for environment variables, so they arrive as strings. The factory turns them into the numbers the tool needs: Initial call configuration: ```js { tool: "reply_due", arguments: { priority: "high" } } ``` ```ts help-desk.app.ts active import { App } from "@frontmcp/sdk"; import { DeskConfig, Settings } from "./config"; import { ReplyDue } from "./reply-due.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [ReplyDue], providers: [ Settings, { provide: DeskConfig, name: "DeskConfig", inject: () => [Settings] as const, useFactory: (settings) => ({ slaHours: { high: Number(settings.get("SLA_HIGH_HOURS")), normal: Number(settings.get("SLA_NORMAL_HOURS")), }, }), }, ], }) export class HelpDeskApp {} ``` ```ts config.ts import { Provider } from "@frontmcp/sdk"; // The key tools ask for. An abstract class gives this.get() a type. export abstract class DeskConfig { abstract slaHours: { high: number; normal: number }; } @Provider({ name: "Settings" }) export class Settings { private values: Record = { SLA_HIGH_HOURS: "4", SLA_NORMAL_HOURS: "24" }; get(key: string) { return this.values[key]; } } ``` ```ts reply-due.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { DeskConfig } from "./config"; @Tool({ name: "reply_due", description: "How many hours support has to reply to a ticket of this priority", inputSchema: { priority: z.enum(["high", "normal"]) }, annotations: { readOnlyHint: true }, }) export class ReplyDue extends ToolContext { async execute({ priority }: { priority: "high" | "normal" }) { return { priority, hours: this.get(DeskConfig).slaHours[priority] }; } } ``` ```ts config.test.ts import { test, expect } from "@frontmcp/testing"; test("hours come from the settings, as numbers", async ({ mcp }) => { expect((await mcp.tools.call("reply_due", { priority: "high" })).json()).toEqual({ priority: "high", hours: 4 }); expect((await mcp.tools.call("reply_due", { priority: "normal" })).json()).toEqual({ priority: "normal", hours: 24 }); }); ``` A factory has four parts: - **`provide`** is the key tools pass to `this.get()`. An abstract class works well: it exists at run time, so it can be a key, and `this.get(DeskConfig)` knows the value's type. A `Symbol` works too, with the type passed yourself: `this.get(SLA_HOURS)`. - **`name`** is optional for factories; it defaults to the class name, symbol description or string token. Changed in 1.10.16: before, factories required a name. - **`inject`** is a function that returns the providers to pass in, in order. With `as const`, TypeScript infers `settings` in `useFactory`. - **`useFactory`** builds the value. It can be `async`, for something that has to be loaded first ([example](https://frontmcp.dev/reference/sdk/provider#providing-a-value-or-configuration)). A factory can take a `scope` too. It's `GLOBAL` unless you say otherwise, so this one runs once, when the server starts. > **Pitfall: Use a function for inject** > > FrontMCP accepts a `@Provider` class, a factory, `{ provide, useValue }` with a plain value or class instance, and `{ provide, useClass }`. A factory's `inject` must be a function: an array is ignored, and the factory is called with no arguments. The [`@Provider` troubleshooting](https://frontmcp.dev/reference/sdk/provider#troubleshooting) has the exact error messages. ## Swapping a provider in tests `snooze_ticket` hides a ticket for some hours and says when it comes back. It reads the time from a `Clock` provider rather than calling `new Date()` itself, and that's what makes it testable. The real server gives it the system clock: ```ts src/main.ts import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "./tickets.app"; import { Clock, SystemClock } from "./clock"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp], providers: [{ provide: Clock, name: "Clock", useValue: new SystemClock() }], }) export default class HelpDeskServer {} ``` A test can't check the answer against a clock that keeps moving. So the tests start a second entry file, which lists the same app with a clock stopped at 09:00. This Playground runs that test server: Initial call configuration: ```js { tool: "snooze_ticket", arguments: { id: "T-1", hours: 2 } } ``` ```ts e2e/test-server.ts active import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "../src/tickets.app"; import { Clock } from "../src/clock"; import { FixedClock } from "./fixed-clock"; @FrontMcp({ info: { name: "Help Desk (tests)", version: "1.0.0" }, apps: [TicketsApp], providers: [{ provide: Clock, name: "Clock", useValue: new FixedClock("2026-03-02T09:00:00.000Z") }], }) export default class TestServer {} ``` ```ts e2e/fixed-clock.ts import { Provider } from "@frontmcp/sdk"; import { Clock } from "../src/clock"; @Provider({ name: "FixedClock" }) export class FixedClock extends Clock { constructor(private readonly time: string) { super(); } now() { return new Date(this.time); } } ``` ```ts e2e/snooze.test.ts import { test, expect } from "@frontmcp/testing"; test("a 2-hour snooze from 09:00 ends at 11:00", async ({ mcp }) => { const result = await mcp.tools.call("snooze_ticket", { id: "T-1", hours: 2 }); expect(result.json()).toEqual({ id: "T-1", until: "2026-03-02T11:00:00.000Z" }); }); ``` ```ts src/clock.ts import { Provider } from "@frontmcp/sdk"; export abstract class Clock { abstract now(): Date; } @Provider({ name: "SystemClock" }) export class SystemClock extends Clock { now() { return new Date(); } } ``` ```ts src/snooze.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { Clock } from "./clock"; @Tool({ name: "snooze_ticket", description: "Hide a ticket from the queue for some hours. Returns when it comes back.", inputSchema: { id: z.string().describe("Ticket id, like T-1"), hours: z.number().int().min(1).max(72), }, }) export class SnoozeTicket extends ToolContext { async execute({ id, hours }: { id: string; hours: number }) { const until = new Date(this.get(Clock).now().getTime() + hours * 60 * 60 * 1000); return { id, until: until.toISOString() }; } } ``` ```ts src/tickets.app.ts import { App } from "@frontmcp/sdk"; import { SnoozeTicket } from "./snooze.tool"; // No Clock here: each entry file (main.ts, test-server.ts) provides its own. @App({ id: "tickets", name: "Tickets", tools: [SnoozeTicket] }) export class TicketsApp {} ``` The tool and the app are the same code in both servers. Only the entry file differs, and it chooses the clock. In a project, point `@frontmcp/testing` at the test entry file: ```ts e2e/snooze.e2e.spec.ts import { test, expect } from "@frontmcp/testing"; test.use({ server: "./e2e/test-server.ts" }); test("a 2-hour snooze from 09:00 ends at 11:00", async ({ mcp }) => { const result = await mcp.tools.call("snooze_ticket", { id: "T-1", hours: 2 }); expect(result.json()).toEqual({ id: "T-1", until: "2026-03-02T11:00:00.000Z" }); }); ``` The same approach works for anything a test shouldn't touch for real: a mail sender that records messages instead of sending them, or an API client that returns canned answers. ### An app's own provider comes first Notice that `TicketsApp` doesn't register `Clock`. When a tool calls `this.get()`, FrontMCP looks in the tool's own app first and only then in the server. So an app that registers a provider hides the server's provider with the same key. That's handy for overrides: here the whole server replies within 24 hours, and the VIP app within 2. Initial call configuration: ```js { tool: "vip_reply_due", arguments: {} } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp, VipApp } from "./apps"; import { deskConfig } from "./config"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, VipApp], providers: [deskConfig(24)], }) export default class HelpDeskServer {} ``` ```ts apps.ts import { App, Tool, ToolContext } from "@frontmcp/sdk"; import { DeskConfig, deskConfig } from "./config"; @Tool({ name: "reply_due", description: "Hours support has to reply to a ticket", inputSchema: {} }) export class ReplyDue extends ToolContext { async execute() { return { hours: this.get(DeskConfig).replyHours }; } } @Tool({ name: "vip_reply_due", description: "Hours support has to reply to a VIP ticket", inputSchema: {} }) export class VipReplyDue extends ToolContext { async execute() { return { hours: this.get(DeskConfig).replyHours }; } } @App({ id: "tickets", name: "Tickets", tools: [ReplyDue] }) export class TicketsApp {} @App({ id: "vip", name: "VIP", tools: [VipReplyDue], providers: [deskConfig(2)] }) export class VipApp {} ``` ```ts config.ts export abstract class DeskConfig { abstract replyHours: number; } export function deskConfig(replyHours: number) { return { provide: DeskConfig, name: "DeskConfig", inject: () => [] as const, useFactory: () => ({ replyHours }) }; } ``` ```ts override.test.ts import { test, expect } from "@frontmcp/testing"; test("the VIP app's own DeskConfig wins over the server's", async ({ mcp }) => { expect((await mcp.tools.call("vip_reply_due", {})).json()).toEqual({ hours: 2 }); }); test("other apps still get the server's", async ({ mcp }) => { expect((await mcp.tools.call("reply_due", {})).json()).toEqual({ hours: 24 }); }); ``` The same rule works against you in tests. If `TicketsApp` registered `SystemClock` itself, the test server's `FixedClock` would never be seen, and the snooze test would fail. Register a provider that differs between environments on the **server**, in each entry file, and keep it out of the app. The last challenge below starts from exactly that mistake. ## Recap - A module-level variable is shared by every request and every test, can't be replaced, and doesn't show up as a dependency. Use a provider. - Decorate the class with `@Provider({ name })`, list it in `providers`, and get it with `this.get()`. The class is the key. - `GLOBAL` (the default) is one instance per place it's registered. `CONTEXT` is a new instance for each request under MCP 2026-07-28, built at the start of every tool call. - A factory (`provide`, `name`, `inject: () => [...]`, `useFactory`) builds a provider from other providers or configuration, and can be `async`. - `this.get()` looks in the tool's app first, then in the server. Register providers that differ between environments on the server, and swap them in a test entry file. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Give each call its own receipt The receipt is a provider now, but the second call's receipt still starts with the first call's steps. Make every request get a fresh receipt, without emptying it by hand. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts receipt.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "Receipt", scope: ProviderScope.GLOBAL }) export class Receipt { steps: string[] = []; add(step: string) { this.steps.push(step); } } ``` **Solution file (alternative to the starter):** ```ts receipt.ts solution import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "Receipt", scope: ProviderScope.CONTEXT }) export class Receipt { steps: string[] = []; add(step: string) { this.steps.push(step); } } ``` ```ts close-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { Receipt } from "./receipt"; @Tool({ name: "close_ticket", description: "Close a support ticket. Returns a receipt of the steps taken.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const receipt = this.get(Receipt); receipt.add(`checked ${id} exists`); receipt.add(`closed ${id}`); return { id, receipt: [...receipt.steps] }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket } from "./close-ticket.tool"; import { Receipt } from "./receipt"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], providers: [Receipt] }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts receipt.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the first call's receipt has its two steps", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result.json().receipt).toEqual(["checked T-1 exists", "closed T-1"]); }); test("the second call's receipt has only its own steps", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-1" }); const result = await mcp.tools.call("close_ticket", { id: "T-2" }); expect(result.json().receipt).toEqual(["checked T-2 exists", "closed T-2"]); }); ``` **Hint:** The class is fine. What decides how long one instance lives? **Solution:** `ProviderScope.CONTEXT` makes FrontMCP build a new `Receipt` at the start of every request, so each call starts with an empty `steps` array. With `GLOBAL`, there was one receipt for the whole app, and it kept growing. ### Challenge: Build the SLA config with a factory `reply_due` asks for `DeskConfig`, but nothing provides it, so every call fails. Register a factory that builds `DeskConfig` from `Settings`. The settings are strings, and `hours` should be a number. Initial call configuration: ```js { tool: "reply_due", arguments: { priority: "high" } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { Settings } from "./config"; import { ReplyDue } from "./reply-due.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [ReplyDue], providers: [Settings], }) export class HelpDeskApp {} ``` **Solution file (alternative to the starter):** ```ts help-desk.app.ts solution import { App } from "@frontmcp/sdk"; import { DeskConfig, Settings } from "./config"; import { ReplyDue } from "./reply-due.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [ReplyDue], providers: [ Settings, { provide: DeskConfig, name: "DeskConfig", inject: () => [Settings] as const, useFactory: (settings) => ({ slaHours: { high: Number(settings.get("SLA_HIGH_HOURS")), normal: Number(settings.get("SLA_NORMAL_HOURS")), }, }), }, ], }) export class HelpDeskApp {} ``` ```ts config.ts import { Provider } from "@frontmcp/sdk"; export abstract class DeskConfig { abstract slaHours: { high: number; normal: number }; } @Provider({ name: "Settings" }) export class Settings { private values: Record = { SLA_HIGH_HOURS: "2", SLA_NORMAL_HOURS: "12" }; get(key: string) { return this.values[key]; } } ``` ```ts reply-due.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { DeskConfig } from "./config"; @Tool({ name: "reply_due", description: "How many hours support has to reply to a ticket of this priority", inputSchema: { priority: z.enum(["high", "normal"]) }, }) export class ReplyDue extends ToolContext { async execute({ priority }: { priority: "high" | "normal" }) { return { priority, hours: this.get(DeskConfig).slaHours[priority] }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts config.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`reply_due` works", async ({ mcp }) => { expect(await mcp.tools.call("reply_due", { priority: "high" })).toBeSuccessful(); }); test("high priority comes from SLA_HIGH_HOURS, as a number", async ({ mcp }) => { expect((await mcp.tools.call("reply_due", { priority: "high" })).json()).toEqual({ priority: "high", hours: 2 }); }); test("normal priority comes from SLA_NORMAL_HOURS, as a number", async ({ mcp }) => { expect((await mcp.tools.call("reply_due", { priority: "normal" })).json()).toEqual({ priority: "normal", hours: 12 }); }); ``` **Hint:** A factory needs `provide`, `name`, `inject` and `useFactory`. `inject` is a function that returns an array, not an array. **Solution:** The factory is registered under `DeskConfig`, the key the tool asks for. `inject: () => [Settings] as const` hands it the `Settings` instance, and `useFactory` converts the strings with `Number()` so the result matches the `DeskConfig` type. ### Challenge: Let the test clock through The test server provides a clock stopped at 09:00, but the snooze test still gets the real time. Find out why, and fix the app so the test server's clock is the one the tool sees. Initial call configuration: ```js { tool: "snooze_ticket", arguments: { id: "T-1", hours: 2 } } ``` ```ts src/tickets.app.ts import { App } from "@frontmcp/sdk"; import { SnoozeTicket } from "./snooze.tool"; import { Clock, SystemClock } from "./clock"; @App({ id: "tickets", name: "Tickets", tools: [SnoozeTicket], providers: [{ provide: Clock, name: "Clock", useValue: new SystemClock() }], }) export class TicketsApp {} ``` **Solution file (alternative to the starter):** ```ts src/tickets.app.ts solution import { App } from "@frontmcp/sdk"; import { SnoozeTicket } from "./snooze.tool"; @App({ id: "tickets", name: "Tickets", tools: [SnoozeTicket] }) export class TicketsApp {} ``` ```ts e2e/test-server.ts import { FrontMcp } from "@frontmcp/sdk"; import { TicketsApp } from "../src/tickets.app"; import { Clock } from "../src/clock"; import { FixedClock } from "./fixed-clock"; @FrontMcp({ info: { name: "Help Desk (tests)", version: "1.0.0" }, apps: [TicketsApp], providers: [{ provide: Clock, name: "Clock", useValue: new FixedClock("2026-03-02T09:00:00.000Z") }], }) export default class TestServer {} ``` ```ts e2e/fixed-clock.ts import { Provider } from "@frontmcp/sdk"; import { Clock } from "../src/clock"; @Provider({ name: "FixedClock" }) export class FixedClock extends Clock { constructor(private readonly time: string) { super(); } now() { return new Date(this.time); } } ``` ```ts src/clock.ts import { Provider } from "@frontmcp/sdk"; export abstract class Clock { abstract now(): Date; } @Provider({ name: "SystemClock" }) export class SystemClock extends Clock { now() { return new Date(); } } ``` ```ts src/snooze.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { Clock } from "./clock"; @Tool({ name: "snooze_ticket", description: "Hide a ticket from the queue for some hours. Returns when it comes back.", inputSchema: { id: z.string().describe("Ticket id, like T-1"), hours: z.number().int().min(1).max(72), }, }) export class SnoozeTicket extends ToolContext { async execute({ id, hours }: { id: string; hours: number }) { const until = new Date(this.get(Clock).now().getTime() + hours * 60 * 60 * 1000); return { id, until: until.toISOString() }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts e2e/snooze.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("a 2-hour snooze from the test clock's 09:00 ends at 11:00", async ({ mcp }) => { const result = await mcp.tools.call("snooze_ticket", { id: "T-1", hours: 2 }); expect(result.json()).toEqual({ id: "T-1", until: "2026-03-02T11:00:00.000Z" }); }); test("a 24-hour snooze ends the next morning", async ({ mcp }) => { const result = await mcp.tools.call("snooze_ticket", { id: "T-1", hours: 24 }); expect(result.json().until).toBe("2026-03-03T09:00:00.000Z"); }); ``` **Hint:** Where does `this.get(Clock)` look first: in the tool's app, or in the server? **Solution:** `this.get()` checks the tool's own app before the server, so the app's `SystemClock` hid the test server's `FixedClock`. With `Clock` out of the app, each entry file decides: `src/main.ts` registers `SystemClock`, and `e2e/test-server.ts` registers the fixed one. --- # Extending with Plugins > What a FrontMCP plugin is, how to write one that adds providers, tools and hooks to an app, how to configure and register it, and what the official plugins do. Source: https://frontmcp.dev/learn/extending-with-plugins [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Some behaviour belongs to no single tool. Every call should land in an audit log, a server under maintenance should refuse changes, slow lookups should be cached. You could write that code into every tool, and every new tool would have to remember it. A FrontMCP **plugin** (`@Plugin`) packages it once: the providers it needs, the tools it adds, and hooks that run around every call. An app turns it on with one line. **You will learn** - What a plugin can add to an app - How to write a plugin with a provider, a tool and a hook - How a plugin shares its providers with the app's tools - How to make a plugin configurable - Where to register a plugin, and what the official plugins do ## Code every tool has to remember The help desk keeps an audit log of every change, and an `audit_log` tool that shows it. Each tool that changes a ticket records itself: Initial call configuration: ```js { tool: "audit_log", arguments: {} } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { AuditLog } from "./audit-log"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { this.get(AuditLog).record("close_ticket", { id }); return { id, status: "closed" }; } } @Tool({ name: "reopen_ticket", description: "Reopen a closed support ticket", inputSchema: { id: z.string() } }) export class ReopenTicket extends ToolContext { async execute({ id }: { id: string }) { this.get(AuditLog).record("reopen_ticket", { id }); return { id, status: "open" }; } } @Tool({ name: "assign_ticket", description: "Assign a support ticket to an agent", inputSchema: { id: z.string(), agent: z.string() }, }) export class AssignTicket extends ToolContext { async execute({ id, agent }: { id: string; agent: string }) { // 🚩 Forgot to record return { id, agent }; } } @Tool({ name: "audit_log", description: "Show every change made to tickets", inputSchema: {} }) export class ShowAuditLog extends ToolContext { async execute() { return { entries: [...this.get(AuditLog).entries] }; } } ``` ```ts audit-log.ts import { Provider } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { AssignTicket, CloseTicket, ReopenTicket, ShowAuditLog } from "./tools"; import { AuditLog } from "./audit-log"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket, ReopenTicket, AssignTicket, ShowAuditLog], providers: [AuditLog], }) export class HelpDeskApp {} ``` ```ts audit.test.ts import { test, expect } from "@frontmcp/testing"; test("assign_ticket never reaches the log", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-1" }); await mcp.tools.call("assign_ticket", { id: "T-1", agent: "nour" }); const tools = (await mcp.tools.call("audit_log", {})).json().entries.map((e: { tool: string }) => e.tool); expect(tools).toEqual(["close_ticket"]); }); ``` `assign_ticket` forgot, so the **Tests** tab shows a log with a hole in it. Nothing warned about it, and nothing will warn about the next tool either. The tool name is typed by hand in each tool, so a copied tool can record the wrong name too. The audit log isn't part of any tool's job. It's something that should happen around all of them. ## Writing a plugin Here the audit log is a plugin. The tools don't mention it at all: Initial call configuration: ```js { tool: "audit_log", arguments: {} } ``` ```ts audit.plugin.ts active import { DynamicPlugin, FlowCtxOf, Plugin, Tool, ToolContext, ToolHook } from "@frontmcp/sdk"; import { AuditLog } from "./audit-log"; @Tool({ name: "audit_log", description: "Show every tool call made so far", inputSchema: {} }) export class ShowAuditLog extends ToolContext { async execute() { return { entries: [...this.get(AuditLog).entries] }; } } @Plugin({ name: "audit", description: "Records every tool call in an audit log", providers: [AuditLog], tools: [ShowAuditLog], }) export class AuditPlugin extends DynamicPlugin { // Runs after every tool's execute() succeeds @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; // input is typed unknown here, because the hook runs for every tool this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` ```ts audit-log.ts import { Provider } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "reopen_ticket", description: "Reopen a closed support ticket", inputSchema: { id: z.string() } }) export class ReopenTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "open" }; } } @Tool({ name: "assign_ticket", description: "Assign a support ticket to an agent", inputSchema: { id: z.string(), agent: z.string() }, }) export class AssignTicket extends ToolContext { async execute({ id, agent }: { id: string; agent: string }) { return { id, agent }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { AssignTicket, CloseTicket, ReopenTicket } from "./tools"; import { AuditPlugin } from "./audit.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket, ReopenTicket, AssignTicket], plugins: [AuditPlugin], }) export class HelpDeskApp {} ``` ```ts audit.test.ts import { test, expect } from "@frontmcp/testing"; test("the plugin adds audit_log to the app's tools", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("audit_log"); }); test("every call is recorded, with its input", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-1" }); await mcp.tools.call("assign_ticket", { id: "T-1", agent: "nour" }); expect((await mcp.tools.call("audit_log", {})).json().entries).toEqual([ { tool: "close_ticket", input: { id: "T-1" } }, { tool: "assign_ticket", input: { id: "T-1", agent: "nour" } }, ]); }); ``` Open the **Capabilities** tab: the app lists four tools, and one of them came from the plugin. The **Tests** tab shows every call in the log, with the name and input FrontMCP had, not ones typed by hand. A plugin is a class with `@Plugin`, and its metadata says what it adds: | Option | What it adds | | --- | --- | | `name` | **Required.** Names the plugin in logs and errors. | | `providers` | Providers for the plugin's own use: its hooks and its tools. | | `exports` | Which of those providers the app's own tools may use too. [Below.](https://frontmcp.dev/learn/extending-with-plugins#sharing-a-plugins-providers-with-the-app) | | `tools`, `resources`, `prompts` | Capabilities added to the app, listed to clients like the app's own. | | `contextExtensions` | Properties added to every tool's `this`, like `this.auditLog`. [Below.](https://frontmcp.dev/learn/extending-with-plugins#sharing-a-plugins-providers-with-the-app) | | `plugins` | Other plugins this one brings along. | The class body holds **hooks**: methods marked with a decorator like `@ToolHook.Did("execute")`, which FrontMCP calls at a point in every tool call. `Did("execute")` runs after a tool's `execute()` returns. Its argument, `ctx`, describes the call in progress: `ctx.state.tool` is the tool being called, and `ctx.state.toolContext` is the running tool, with the validated `input`. The [next lesson](https://frontmcp.dev/learn/hooking-into-calls) covers every point you can hook into, and what a hook can change. Extending `DynamicPlugin` gives the class a typed `this.get()`, which reaches the plugin's providers. Its type parameter is for options, which [come later](https://frontmcp.dev/learn/extending-with-plugins#configuring-a-plugin). `object` means none. Finally, the app lists the plugin in `plugins`. That's the one line: remove it, and the tool, the provider and the hook are all gone. ### Hooks on tools and providers Hook methods also run on two other kinds of class. On a `@Tool` class, a hook runs only for that tool's calls. On a provider listed in an app's `providers`, it runs for every tool in that app. Here the app's `LegalHold` provider refuses any call about ticket T-7, and `close_ticket` refuses to close T-2 twice: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-7" } } ``` ```ts help-desk.app.ts active import { App, FlowCtxOf, Provider, PublicMcpError, Tool, ToolContext, ToolHook, z } from "@frontmcp/sdk"; type CallCtx = FlowCtxOf<"tools:call-tool">; const idOf = (ctx: CallCtx) => (ctx.state.toolContext?.input as { id?: string } | undefined)?.id; @Provider({ name: "LegalHold" }) export class LegalHold { // On an app's provider: runs for every tool in the app @ToolHook.Will("execute") async refuseHeldTickets(ctx: CallCtx) { if (idOf(ctx) === "T-7") throw new PublicMcpError("Ticket T-7 is on legal hold."); } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { // On a tool class: runs only for close_ticket @ToolHook.Will("execute") async refuseClosedTickets(ctx: CallCtx) { if (idOf(ctx) === "T-2") throw new PublicMcpError("Ticket T-2 is already closed."); } async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: id === "T-2" ? "closed" : "open" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket, GetTicket], providers: [LegalHold] }) export class HelpDeskApp {} ``` ```ts hooks.test.ts import { test, expect } from "@frontmcp/testing"; test("the provider's hook runs for every tool in the app", async ({ mcp }) => { expect(await mcp.tools.call("close_ticket", { id: "T-7" })).toHaveTextContent("legal hold"); expect(await mcp.tools.call("get_ticket", { id: "T-7" })).toHaveTextContent("legal hold"); }); test("the tool's own hook runs only for that tool", async ({ mcp }) => { expect(await mcp.tools.call("close_ticket", { id: "T-2" })).toHaveTextContent("already closed"); expect(await mcp.tools.call("get_ticket", { id: "T-2" })).toBeSuccessful(); }); ``` Both are fine for code that belongs to one tool or one app. A plugin is still the way to share hooks between apps and servers, bring along the providers and tools they need, and take options. ## Sharing a plugin's providers with the app A plugin's providers are private to it by default. When the app's own `ticket_history` tool asks for the plugin's `AuditLog`, it only finds it because the plugin lists it in **`exports`**: Initial call configuration: ```js { tool: "ticket_history", arguments: { id: "T-1" } } ``` ```ts audit.plugin.ts active import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; import { AuditLog } from "./audit-log"; @Plugin({ name: "audit", description: "Records every tool call in an audit log", providers: [AuditLog], exports: [AuditLog], // ✅ the app's tools can this.get(AuditLog) too }) export class AuditPlugin extends DynamicPlugin { @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { AuditLog } from "./audit-log"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "ticket_history", description: "List the tool calls that touched one ticket, oldest first", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, }) export class TicketHistory extends ToolContext { async execute({ id }: { id: string }) { const entries = this.get(AuditLog).entries.filter((e) => e.input.id === id); return { id, history: entries.map((e) => e.tool) }; } } ``` ```ts audit-log.ts import { Provider } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, TicketHistory } from "./tools"; import { AuditPlugin } from "./audit.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket, TicketHistory], plugins: [AuditPlugin] }) export class HelpDeskApp {} ``` ```ts history.test.ts import { test, expect } from "@frontmcp/testing"; test("the app's tool reads the plugin's log", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-1" }); await mcp.tools.call("close_ticket", { id: "T-2" }); expect((await mcp.tools.call("ticket_history", { id: "T-1" })).json()).toEqual({ id: "T-1", history: ["close_ticket"] }); }); ``` Take `exports` out and `ticket_history` fails with `Provider "AuditLog" is not available`, even though the plugin's hook keeps recording. Exporting is a choice: export what the app is meant to use, and keep the plugin's internals private. The second challenge below starts without it. ### Adding this.auditLog to every tool `contextExtensions` goes one step further: it adds a property to every tool's `this`, so tools write `this.auditLog` instead of `this.get(AuditLog)`. It's how the official plugins add helpers like `this.remember`. Each extension names the property and the key of an exported provider: Initial call configuration: ```js { tool: "ticket_history", arguments: { id: "T-1" } } ``` ```ts audit.plugin.ts active import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } export const AUDIT_LOG = Symbol.for("help-desk.audit-log"); const auditLogProvider = { provide: AUDIT_LOG, name: "AuditLog", inject: () => [] as const, useFactory: () => new AuditLog() }; // Tells TypeScript that tools have this.auditLog declare module "@frontmcp/sdk" { interface ExecutionContextBase { readonly auditLog: AuditLog; } } @Plugin({ name: "audit", providers: [auditLogProvider], exports: [auditLogProvider], contextExtensions: [{ property: "auditLog", token: AUDIT_LOG }], }) export class AuditPlugin extends DynamicPlugin { @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; this.get(AUDIT_LOG).record(tool.metadata.name, toolContext.input as Record); } } ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "ticket_history", description: "List the tool calls that touched one ticket, oldest first", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, }) export class TicketHistory extends ToolContext { async execute({ id }: { id: string }) { const entries = this.auditLog.entries.filter((e) => e.input.id === id); return { id, history: entries.map((e) => e.tool) }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, TicketHistory } from "./tools"; import { AuditPlugin } from "./audit.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket, TicketHistory], plugins: [AuditPlugin] }) export class HelpDeskApp {} ``` ```ts history.test.ts import { test, expect } from "@frontmcp/testing"; test("tools read the log through this.auditLog", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-1" }); expect((await mcp.tools.call("ticket_history", { id: "T-1" })).json()).toEqual({ id: "T-1", history: ["close_ticket"] }); }); ``` FrontMCP installs an extension once per process, on the class every tool context extends, and the first plugin to claim a property name keeps it. That's why this example uses a `Symbol.for()` key rather than the `AuditLog` class: the Playground builds your classes afresh on every run but keeps one FrontMCP, and a key made with `Symbol.for()` is the same on every run. In a project, where your files load once, a class works as the key too. ## Configuring a plugin Logging every read fills the audit log with noise. A plugin takes options through its constructor, and `init()` passes them in. Here `skipReadOnly` leaves out tools marked `readOnlyHint`: Initial call configuration: ```js { tool: "audit_log", arguments: {} } ``` ```ts audit.plugin.ts active import { DynamicPlugin, FlowCtxOf, Plugin, Tool, ToolContext, ToolHook } from "@frontmcp/sdk"; import { AuditLog } from "./audit-log"; export type AuditOptions = { skipReadOnly?: boolean }; @Tool({ name: "audit_log", description: "Show every change made so far", inputSchema: {}, annotations: { readOnlyHint: true } }) export class ShowAuditLog extends ToolContext { async execute() { return { entries: [...this.get(AuditLog).entries] }; } } @Plugin({ name: "audit", providers: [AuditLog], tools: [ShowAuditLog] }) export class AuditPlugin extends DynamicPlugin { constructor(private readonly options: AuditOptions = {}) { super(); } @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; if (this.options.skipReadOnly && tool.metadata.annotations?.readOnlyHint) return; this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, GetTicket } from "./tools"; import { AuditPlugin } from "./audit.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, CloseTicket], plugins: [AuditPlugin.init({ skipReadOnly: true })], }) export class HelpDeskApp {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } ``` ```ts audit-log.ts import { Provider } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } ``` ```ts options.test.ts import { test, expect } from "@frontmcp/testing"; test("reads are left out, changes are recorded", async ({ mcp }) => { await mcp.tools.call("get_ticket", { id: "T-1" }); await mcp.tools.call("close_ticket", { id: "T-1" }); await mcp.tools.call("audit_log", {}); expect((await mcp.tools.call("audit_log", {})).json().entries).toEqual([{ tool: "close_ticket", input: { id: "T-1" } }]); }); ``` - **`DynamicPlugin`** declares the options type, so `init()` only accepts `AuditOptions`. - **`AuditPlugin.init({ skipReadOnly: true })`** builds the plugin with those options. It goes in `plugins` where the class went. - **`plugins: [AuditPlugin]`** still works, and calls the constructor with no options, so give every option a default. The plugin now reads `annotations`, which the tools already declare for clients. A plugin can also read keys of its own from `@Tool({ ... })`: unknown keys are kept in `tool.metadata`. The official Cache plugin works that way, with `cache: true` on each tool it should cache. ## Registering a plugin on the server A plugin in an app's `plugins` belongs to that app: its tools join the app, its exported providers are visible to the app's tools only, and its hooks run for the app's tools only. To give every app the audit log, register the plugin once on the server instead: Initial call configuration: ```js { tool: "refund_invoice", arguments: { id: "INV-7" } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { BillingApp, TicketsApp } from "./apps"; import { AuditPlugin } from "./audit.plugin"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], plugins: [AuditPlugin], }) export default class HelpDeskServer {} ``` ```ts apps.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { AuditLog } from "./audit.plugin"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "refund_invoice", description: "Refund an invoice in full", inputSchema: { id: z.string() } }) export class RefundInvoice extends ToolContext { async execute({ id }: { id: string }) { const earlier = this.get(AuditLog).entries.filter((e) => e.input.id === id).length; return { id, status: "refunded", earlierCalls: earlier }; } } @App({ id: "tickets", name: "Tickets", tools: [CloseTicket] }) export class TicketsApp {} @App({ id: "billing", name: "Billing", tools: [RefundInvoice] }) export class BillingApp {} ``` ```ts audit.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, Provider, Tool, ToolContext, ToolHook } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } @Tool({ name: "audit_log", description: "Show every tool call made so far", inputSchema: {} }) export class ShowAuditLog extends ToolContext { async execute() { return { entries: [...this.get(AuditLog).entries] }; } } @Plugin({ name: "audit", providers: [AuditLog], exports: [AuditLog], tools: [ShowAuditLog] }) export class AuditPlugin extends DynamicPlugin { @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` ```ts server.test.ts import { test, expect } from "@frontmcp/testing"; test("calls to both apps are recorded", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-1" }); await mcp.tools.call("refund_invoice", { id: "INV-7" }); const tools = (await mcp.tools.call("audit_log", {})).json().entries.map((e: { tool: string }) => e.tool); expect(tools).toEqual(["close_ticket", "refund_invoice"]); }); test("every app's tools can use the exported AuditLog", async ({ mcp }) => { expect(await mcp.tools.call("refund_invoice", { id: "INV-7" })).toBeSuccessful(); }); ``` `audit_log` is listed once, the billing app's `refund_invoice` can `this.get(AuditLog)`, and the hook records calls to both apps. Server-wide concerns like auditing, tracing and policy belong here. Compare the same plugin registered on the tickets app only. Its tool is listed, but the billing app can't reach its `AuditLog`, and its hook doesn't see billing calls: Initial call configuration: ```js { tool: "refund_invoice", arguments: { id: "INV-7" } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { BillingApp, TicketsApp } from "./apps"; @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [TicketsApp, BillingApp], }) export default class HelpDeskServer {} ``` ```ts apps.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { AuditLog, AuditPlugin } from "./audit.plugin"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "refund_invoice", description: "Refund an invoice in full", inputSchema: { id: z.string() } }) export class RefundInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "refunded", canSeeAuditLog: this.tryGet(AuditLog) !== undefined }; } } @App({ id: "tickets", name: "Tickets", tools: [CloseTicket], plugins: [AuditPlugin] }) export class TicketsApp {} @App({ id: "billing", name: "Billing", tools: [RefundInvoice] }) export class BillingApp {} ``` ```ts audit.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, Provider, Tool, ToolContext, ToolHook } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } @Tool({ name: "audit_log", description: "Show every tool call made so far", inputSchema: {} }) export class ShowAuditLog extends ToolContext { async execute() { return { entries: [...this.get(AuditLog).entries] }; } } @Plugin({ name: "audit", providers: [AuditLog], exports: [AuditLog], tools: [ShowAuditLog] }) export class AuditPlugin extends DynamicPlugin { @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` ```ts scope.test.ts import { test, expect } from "@frontmcp/testing"; test("the billing app can't use the tickets app's AuditLog", async ({ mcp }) => { expect((await mcp.tools.call("refund_invoice", { id: "INV-7" })).json().canSeeAuditLog).toBe(false); }); test("the tickets app's hook records only tickets calls", async ({ mcp }) => { await mcp.tools.call("refund_invoice", { id: "INV-7" }); await mcp.tools.call("close_ticket", { id: "T-1" }); const tools = (await mcp.tools.call("audit_log", {})).json().entries.map((e: { tool: string }) => e.tool); expect(tools).toEqual(["close_ticket"]); }); ``` Register a plugin on the app whose tools it's about, and on the server only when every app needs it. ## Official plugins The FrontMCP team publishes plugins for common needs, each as its own npm package. They're installed and registered like the plugin above, with `plugins: [SomePlugin.init({ ... })]`: | Package | What it does | Lesson | | --- | --- | --- | | [`@frontmcp/plugin-cache`](https://frontmcp.dev/reference/plugins/cache) | Caches tool results, keyed by tool, input and caller, in memory or Redis. Tools opt in with `cache` in `@Tool`. | [Caching Results](https://frontmcp.dev/learn/caching-results) | | [`@frontmcp/plugin-remember`](https://frontmcp.dev/reference/plugins/remember) | Encrypted memory that tools read and write through `this.remember`, per session, user or tool. | [Remembering Across Calls](https://frontmcp.dev/learn/remembering-across-calls) | | [`@frontmcp/plugin-approval`](https://frontmcp.dev/reference/plugins/approval) | Requires approval before sensitive tools run. | [Asking for Approval](https://frontmcp.dev/learn/asking-for-approval) | | [`@frontmcp/plugin-feature-flags`](https://frontmcp.dev/reference/plugins/feature-flags) | Hides and blocks tools, resources and prompts behind feature flags from Split.io, LaunchDarkly, Unleash or your own source. | [Turning Features On and Off](https://frontmcp.dev/learn/turning-features-on-and-off) | | [`@frontmcp/plugin-codecall`](https://frontmcp.dev/reference/plugins/codecall) | Puts a large set of tools behind a few meta-tools, so the model searches for tools and runs short scripts that call them. | [Letting the Model Write Code with CodeCall](https://frontmcp.dev/learn/letting-the-model-write-code-with-codecall) | | [`@frontmcp/plugin-skilled-openapi`](https://frontmcp.dev/reference/plugins/skilled-openapi) | Serves a REST API described by OpenAPI as a small set of skills instead of one tool per endpoint. | [An API too big to list](https://frontmcp.dev/learn/wrapping-an-openapi-service#an-api-too-big-to-list) | `@frontmcp/plugins` bundles four of them, Cache, CodeCall, Remember and a dashboard; install the others on their own. The [Built-in Plugins and Adapters](https://frontmcp.dev/learn/built-in-plugins-and-adapters) chapter teaches them one lesson at a time, and [Plugins](https://frontmcp.dev/reference/plugins) covers each one, with examples that run on this site. For example, with the Cache plugin: ```ts src/tickets.app.ts import { App } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { GetTicket, SearchTickets } from "./tools"; @App({ id: "tickets", name: "Tickets", tools: [GetTicket, SearchTickets], plugins: [CachePlugin.init({ type: "memory" })], }) export class TicketsApp {} ``` [Each plugin's page](https://frontmcp.dev/reference/plugins) lists its options, and which tools it applies to. Before writing a plugin of your own, check whether one of these already does the job. ## Recap - A plugin (`@Plugin`) packages behaviour that belongs around every tool rather than in one: providers, tools, resources, prompts, hooks and context extensions. - Hooks are methods on the plugin class, like `@ToolHook.Did("execute")`. The same hooks also run on a tool class, for that tool, and on an app's provider, for that app. - A plugin's providers are private to it. List them in `exports` for the app's tools to use them, or add a `this.` property with `contextExtensions`. - Extend `DynamicPlugin` for a typed `this.get()` and options, and register a configured plugin with `MyPlugin.init({ ... })`. - Register a plugin on an app for that app's tools, or on `@FrontMcp` for every app's. - Every `@Plugin` option, and what each place you register a plugin affects, is in the [`@Plugin` reference](https://frontmcp.dev/reference/sdk/plugin). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Turn the plugin on The audit plugin is written, but nothing is recorded and clients can't see `audit_log`. Register the plugin on the help desk app. ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { AssignTicket, CloseTicket } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket, AssignTicket] }) export class HelpDeskApp {} ``` **Solution file (alternative to the starter):** ```ts help-desk.app.ts solution import { App } from "@frontmcp/sdk"; import { AssignTicket, CloseTicket } from "./tools"; import { AuditPlugin } from "./audit.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket, AssignTicket], plugins: [AuditPlugin] }) export class HelpDeskApp {} ``` ```ts audit.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, Provider, Tool, ToolContext, ToolHook } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } @Tool({ name: "audit_log", description: "Show every tool call made so far", inputSchema: {} }) export class ShowAuditLog extends ToolContext { async execute() { return { entries: [...this.get(AuditLog).entries] }; } } @Plugin({ name: "audit", providers: [AuditLog], tools: [ShowAuditLog] }) export class AuditPlugin extends DynamicPlugin { @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "assign_ticket", description: "Assign a support ticket to an agent", inputSchema: { id: z.string(), agent: z.string() }, }) export class AssignTicket extends ToolContext { async execute({ id, agent }: { id: string; agent: string }) { return { id, agent }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts audit.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`audit_log` is listed", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("audit_log"); }); test("the app's own tools are still listed", async ({ mcp }) => { const tools = await mcp.tools.list(); expect(tools).toContainTool("close_ticket"); expect(tools).toContainTool("assign_ticket"); }); test("calls are recorded in order", async ({ mcp }) => { await mcp.tools.call("assign_ticket", { id: "T-1", agent: "nour" }); await mcp.tools.call("close_ticket", { id: "T-1" }); const log = await mcp.tools.call("audit_log", {}); expect(log).toBeSuccessful(); expect(log.json().entries.map((e: { tool: string }) => e.tool)).toEqual(["assign_ticket", "close_ticket"]); }); ``` **Hint:** Plugins go in their own list on `@App`, next to `tools`. **Solution:** `plugins: [AuditPlugin]` turns on everything the plugin declares: the `audit_log` tool joins the app, the `AuditLog` provider is created, and the hook starts recording. Nothing in the tools had to change. ### Challenge: Share the audit log with the app `ticket_history` belongs to the app and reads the plugin's `AuditLog`, but every call fails with `Provider "AuditLog" is not available`. Let the app's tools use the audit log, without moving it out of the plugin. Initial call configuration: ```js { tool: "ticket_history", arguments: { id: "T-1" } } ``` ```ts audit.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, Provider, ToolHook } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } @Plugin({ name: "audit", providers: [AuditLog] }) export class AuditPlugin extends DynamicPlugin { @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` **Solution file (alternative to the starter):** ```ts audit.plugin.ts solution import { DynamicPlugin, FlowCtxOf, Plugin, Provider, ToolHook } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } @Plugin({ name: "audit", providers: [AuditLog], exports: [AuditLog] }) export class AuditPlugin extends DynamicPlugin { @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { AuditLog } from "./audit.plugin"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "ticket_history", description: "List the tool calls that touched one ticket, oldest first", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, }) export class TicketHistory extends ToolContext { async execute({ id }: { id: string }) { const entries = this.get(AuditLog).entries.filter((e) => e.input.id === id); return { id, history: entries.map((e) => e.tool) }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, TicketHistory } from "./tools"; import { AuditPlugin } from "./audit.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket, TicketHistory], plugins: [AuditPlugin] }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts history.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`ticket_history` works", async ({ mcp }) => { expect(await mcp.tools.call("ticket_history", { id: "T-9" })).toBeSuccessful(); }); test("it sees what the plugin recorded", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-1" }); await mcp.tools.call("close_ticket", { id: "T-2" }); const result = await mcp.tools.call("ticket_history", { id: "T-1" }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ id: "T-1", history: ["close_ticket"] }); }); ``` **Hint:** Registering `AuditLog` in the app as well would give the app a second, empty log. Look for the plugin option that shares a provider. **Solution:** `exports: [AuditLog]` makes the plugin's own instance visible to the app's tools, so `ticket_history` reads the same log the hook writes to. Adding `AuditLog` to the app's `providers` instead would have made the error go away, but the app would get its own empty copy. ### Challenge: Make the plugin skip reads Every `get_ticket` call ends up in the audit log. Give the plugin a `skipReadOnly` option that leaves out tools marked `readOnlyHint`, and turn it on for the app. ```ts audit.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, Provider, Tool, ToolContext, ToolHook } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } @Tool({ name: "audit_log", description: "Show every change made so far", inputSchema: {}, annotations: { readOnlyHint: true } }) export class ShowAuditLog extends ToolContext { async execute() { return { entries: [...this.get(AuditLog).entries] }; } } @Plugin({ name: "audit", providers: [AuditLog], tools: [ShowAuditLog] }) export class AuditPlugin extends DynamicPlugin { @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` **Solution file (alternative to the starter):** ```ts audit.plugin.ts solution import { DynamicPlugin, FlowCtxOf, Plugin, Provider, Tool, ToolContext, ToolHook } from "@frontmcp/sdk"; @Provider({ name: "AuditLog" }) export class AuditLog { entries: { tool: string; input: Record }[] = []; record(tool: string, input: Record) { this.entries.push({ tool, input }); } } @Tool({ name: "audit_log", description: "Show every change made so far", inputSchema: {}, annotations: { readOnlyHint: true } }) export class ShowAuditLog extends ToolContext { async execute() { return { entries: [...this.get(AuditLog).entries] }; } } export type AuditOptions = { skipReadOnly?: boolean }; @Plugin({ name: "audit", providers: [AuditLog], tools: [ShowAuditLog] }) export class AuditPlugin extends DynamicPlugin { constructor(private readonly options: AuditOptions = {}) { super(); } @ToolHook.Did("execute") async record(ctx: FlowCtxOf<"tools:call-tool">) { const { tool, toolContext } = ctx.state; if (!tool || !toolContext) return; if (this.options.skipReadOnly && tool.metadata.annotations?.readOnlyHint) return; this.get(AuditLog).record(tool.metadata.name, toolContext.input as Record); } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, GetTicket } from "./tools"; import { AuditPlugin } from "./audit.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, CloseTicket], plugins: [AuditPlugin] }) export class HelpDeskApp {} ``` **Solution file (alternative to the starter):** ```ts help-desk.app.ts solution import { App } from "@frontmcp/sdk"; import { CloseTicket, GetTicket } from "./tools"; import { AuditPlugin } from "./audit.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, CloseTicket], plugins: [AuditPlugin.init({ skipReadOnly: true })], }) export class HelpDeskApp {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts options.test.ts hidden import { test, expect } from "@frontmcp/testing"; const logged = async (mcp: any) => (await mcp.tools.call("audit_log", {})).json().entries.map((e: { tool: string }) => e.tool); test("`get_ticket` isn't recorded", async ({ mcp }) => { await mcp.tools.call("get_ticket", { id: "T-1" }); expect(await logged(mcp)).not.toContain("get_ticket"); }); test("`close_ticket` still is", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-1" }); expect(await logged(mcp)).toEqual(["close_ticket"]); }); ``` **Hint:** Take the options in the constructor, with a default so `plugins: [AuditPlugin]` still works, and change `DynamicPlugin` to your options type. Then register it with `AuditPlugin.init({ ... })`. **Solution:** `init({ skipReadOnly: true })` creates the plugin with those options, and the hook returns early for tools whose `annotations` say they're read-only. The log also stops recording `audit_log` itself, since it's marked read-only too. --- # Hooking into Calls > How FrontMCP runs a tool call as a flow of stages, and how plugin hooks run before and after them to log calls, normalize input, block calls and change results. Which order hooks run in, and what they can change. Source: https://frontmcp.dev/learn/hooking-into-calls [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every `tools/call` that FrontMCP receives runs through a **flow**: a fixed list of named stages, from finding the tool to formatting its result. A **hook** is a method that runs just before or just after one of those stages, on every call. The [previous lesson](https://frontmcp.dev/learn/extending-with-plugins) used one to fill an audit log. This one shows the stages, what a hook can read and change at each of them, and the order hooks run in. **You will learn** - Which stages a tool call goes through - How `Will`, `Did`, `Finally` and `Around` hooks run around a stage, and what they can read - How to use hooks to log calls, normalize input, block calls and change results - Which order hooks run in ## The stages of a tool call This plugin traces three stages of every call: `Will` runs before a stage, `Did` after success, and `Finally` after any outcome. Call `get_ticket`, then `show_trace`: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts trace.plugin.ts active import { DynamicPlugin, FlowCtxOf, Plugin, Provider, Tool, ToolContext, ToolHook } from "@frontmcp/sdk"; type CallCtx = FlowCtxOf<"tools:call-tool">; @Provider({ name: "Trace" }) export class Trace { lines: string[] = []; } @Tool({ name: "show_trace", description: "Show the stages traced since the last call to show_trace", inputSchema: {} }) export class ShowTrace extends ToolContext { async execute() { return { trace: this.get(Trace).lines.splice(0) }; } } @Plugin({ name: "trace", providers: [Trace], tools: [ShowTrace] }) export class TracePlugin extends DynamicPlugin { private note(ctx: CallCtx, line: string) { if (ctx.state.tool?.metadata.name !== "show_trace") this.get(Trace).lines.push(line); } @ToolHook.Will("validateInput") async willValidate(ctx: CallCtx) { this.note(ctx, "will validateInput"); } @ToolHook.Did("validateInput") async didValidate(ctx: CallCtx) { this.note(ctx, "did validateInput"); } @ToolHook.Will("execute") async willExecute(ctx: CallCtx) { this.note(ctx, "will execute"); } @ToolHook.Did("execute") async didExecute(ctx: CallCtx) { this.note(ctx, "did execute"); } @ToolHook.Will("finalize") async willFinalize(ctx: CallCtx) { this.note(ctx, "will finalize"); } @ToolHook.Finally("finalize") async finallyFinalize(ctx: CallCtx) { this.note(ctx, "finally finalize"); } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket } from "./get-ticket.tool"; import { TracePlugin } from "./trace.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], plugins: [TracePlugin] }) export class HelpDeskApp {} ``` ```ts trace.test.ts import { test, expect } from "@frontmcp/testing"; test("a call that works passes through every stage", async ({ mcp }) => { await mcp.tools.call("get_ticket", { id: "T-1" }); expect((await mcp.tools.call("show_trace", {})).json().trace).toEqual([ "will validateInput", "did validateInput", "will execute", "did execute", "will finalize", "finally finalize", ]); }); test("a call with bad input stops at validateInput, then finalizes", async ({ mcp }) => { await mcp.tools.call("get_ticket", { id: "ticket one" }); expect((await mcp.tools.call("show_trace", {})).json().trace).toEqual([ "will validateInput", "will finalize", "finally finalize", ]); }); ``` The **Tests** tab shows two calls. The first passes every stage, and each stage's `Will` hook runs before it and its `Did` hook after it. The second has an id that doesn't match the pattern, so `validateInput` fails: its `Did` hook doesn't run, `execute` is skipped entirely, and the flow jumps to its closing stages, which run whether the call worked or not. These are the stages of `tools:call-tool`, the flow behind `tools/call`, in order: | Group | Stages | Runs | | --- | --- | --- | | Before | `parseInput`, `ensureRemoteCapabilities`, `findTool`, `checkPublicAccess`, `checkToolAuthorization`, `checkEntryAuthorities`, `createTaskIfRequested`, `createToolCallContext`, `checkToolCredentials`, `acquireQuota`, `acquireSemaphore` | Until one fails | | Execute | `validateInput`, `execute`, `validateOutput` | Until one fails | | Finally | `releaseSemaphore`, `releaseQuota`, `applyUI`, `finalize` | Always | Most hooks need only a few of them: `validateInput` (the arguments are checked against `inputSchema`), `execute` (your tool's `execute()` runs), and `finalize` (the result is put together for the client). The hooks in this lesson are on plugins, so they run for every tool. A tool class can also declare hooks for its own calls, `static` ones included for the stages before its instance exists, like `parseInput`: see [Hook decorators](https://frontmcp.dev/reference/sdk/hooks#hooking-the-stages-before-an-entrys-instance). ## What a hook can read A hook method gets one argument, `ctx`, which describes the call in progress. Type it as `FlowCtxOf<"tools:call-tool">`. What's in `ctx.state` depends on how far the call has got: | Field | What it is | From | | --- | --- | --- | | `ctx.state.input` | The raw `tools/call` params: the tool `name`, the `arguments` as the client sent them, and `_meta` | `parseInput` | | `ctx.state.tool` | The tool being called. `metadata` holds everything from `@Tool({ ... })`, and `owner.id` is its app's `id` | `findTool` | | `ctx.state.toolContext` | This call's tool instance: `input` (checked against the schema once `validateInput` is done), `output` (once `execute` is done) and `get()` for providers | `createToolCallContext` | `@frontmcp/sdk` exports hook decorators for other flows too, with the same `Will` and `Did`: `ListToolsHook` for `tools/list`, `ResourceHook` for `resources/read`, `ListResourcesHook`, `ListResourceTemplatesHook` and `HttpHook`, among others. You'll use `ListToolsHook` below. ## Logging every call A log of every call with how long it took and whether it worked is a common first plugin. It needs code on both sides of `execute`, including when `execute` fails, and a `Did` hook doesn't run for a failed stage. That's what `@ToolHook.Around(stage)` is for. Its method gets a second argument, `next`, which runs the stage: code before `await next()` runs just before the stage, code after it just after, and if the stage fails, `next()` throws: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts call-log.plugin.ts active import { DynamicPlugin, FlowCtxOf, Plugin, Provider, Tool, ToolContext, ToolHook } from "@frontmcp/sdk"; type CallCtx = FlowCtxOf<"tools:call-tool">; type Entry = { tool: string; outcome: "ok" | "failed"; ms: number }; @Provider({ name: "CallLog" }) export class CallLog { entries: Entry[] = []; } @Tool({ name: "recent_calls", description: "Show recent tool calls, how long each took, and whether it worked", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class RecentCalls extends ToolContext { async execute() { return { calls: [...this.get(CallLog).entries] }; } } @Plugin({ name: "call-log", providers: [CallLog], tools: [RecentCalls] }) export class CallLogPlugin extends DynamicPlugin { @ToolHook.Around("execute") async time(ctx: CallCtx, next: () => Promise) { const startedAt = Date.now(); const record = (outcome: Entry["outcome"]) => this.get(CallLog).entries.push({ tool: ctx.state.tool?.metadata.name ?? "?", outcome, ms: Date.now() - startedAt }); try { await next(); // runs execute() record("ok"); } catch (error) { record("failed"); throw error; // the client still gets the tool's own error } } } ``` ```ts get-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket } from "./get-ticket.tool"; import { CallLogPlugin } from "./call-log.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], plugins: [CallLogPlugin] }) export class HelpDeskApp {} ``` ```ts call-log.test.ts import { test, expect } from "@frontmcp/testing"; test("calls are logged with their outcome and duration", async ({ mcp }) => { await mcp.tools.call("get_ticket", { id: "T-1" }); // works await mcp.tools.call("get_ticket", { id: "T-9" }); // execute() fails await mcp.tools.call("get_ticket", { id: "ticket one" }); // rejected before execute() expect((await mcp.tools.call("recent_calls", {})).json().calls).toEqual([ { tool: "get_ticket", outcome: "ok", ms: expect.any(Number) }, { tool: "get_ticket", outcome: "failed", ms: expect.any(Number) }, ]); }); test("a failed call still gets the tool's error", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-9" }); expect(result.raw._meta?.code).toBe("PUBLIC_ERROR"); expect(result.text()).toBe("There's no ticket T-9."); }); ``` Call `get_ticket` with `T-9`, then `recent_calls`, to see a failure logged. The hook rethrows what `next()` threw, so the client gets the same error it would have without the plugin. Take out `throw error` and call `T-9` again: with the error swallowed, the call ends with no result at all, and FrontMCP answers with `FLOW_EXITED_WITHOUT_OUTPUT`. A call rejected before `execute()` never reaches the stage, so the hook doesn't run for it: the test's third call, with a malformed id, isn't logged. (`recent_calls` is a tool like any other, so it logs itself too: each call to it shows the one before.) ## Normalizing input Models are loose with ids. Asked about "ticket t-2", a model may well send `" t-2 "`, and the schema's pattern rejects it. One hook can clean up ticket ids for every tool, before FrontMCP checks them: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: " t-2 " } } ``` ```ts ticket-ids.plugin.ts active import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; @Plugin({ name: "ticket-ids", description: "Accepts ticket ids in any case, with stray spaces" }) export class TicketIdsPlugin extends DynamicPlugin { @ToolHook.Will("validateInput") async normalizeTicketId(ctx: FlowCtxOf<"tools:call-tool">) { const args = ctx.state.input?.arguments; if (typeof args?.id === "string") args.id = args.id.trim().toUpperCase(); } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Invoice total is wrong", status: "closed" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket } from "./get-ticket.tool"; import { TicketIdsPlugin } from "./ticket-ids.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], plugins: [TicketIdsPlugin] }) export class HelpDeskApp {} ``` ```ts ids.test.ts import { test, expect } from "@frontmcp/testing"; test("\" t-2 \" is read as T-2", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: " t-2 " }); expect(result).toBeSuccessful(); expect(result.json().id).toBe("T-2"); }); test("the schema still rejects ids that aren't ticket ids", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "ticket two" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); ``` The hook changes `ctx.state.input.arguments`, the arguments as the client sent them, in `Will("validateInput")`: just before they're checked. So the schema still has the last word, and `"ticket two"` is still rejected. By `Will("execute")` it's too late for this: validation is over, a malformed id has already been turned away, and anything you change there skips the schema altogether. For a single tool, you can do the same in its schema with `z.string().trim().toUpperCase()` ([Schemas Are Contracts](https://frontmcp.dev/learn/schemas-are-contracts#what-reaches-execute) covers it). The hook's advantage is reach: it cleans up every tool's `id`, including tools added later or by other plugins. ## Blocking a call During a data migration, the help desk has to stay read-only. A hook in `Will("execute")` runs right before the tool, and can stop it by throwing. The same plugin hides the tools that would change something from `tools/list`, so the model doesn't try them in the first place: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts read-only.plugin.ts active import { DynamicPlugin, FlowCtxOf, ListToolsHook, Plugin, PublicMcpError, ToolHook } from "@frontmcp/sdk"; type ReadOnlyOptions = { enabled: boolean }; @Plugin({ name: "read-only", description: "Turns off every tool that isn't marked read-only" }) export class ReadOnlyPlugin extends DynamicPlugin { constructor(private readonly options: ReadOnlyOptions = { enabled: false }) { super(); } // Refuse calls, even from a client that never listed the tools @ToolHook.Will("execute", { filter: (ctx) => !ctx.state.tool?.metadata.annotations?.readOnlyHint }) async refuse(ctx: FlowCtxOf<"tools:call-tool">) { if (!this.options.enabled) return; throw new PublicMcpError( `The help desk is read-only during maintenance, so ${ctx.state.tool?.metadata.name} is unavailable. Try again after 18:00 UTC.`, ); } // Leave them out of tools/list @ListToolsHook.Did("findTools") async hide(ctx: FlowCtxOf<"tools:list-tools">) { if (!this.options.enabled) return; const tools = ctx.state.tools ?? []; ctx.state.set("tools", tools.filter(({ tool }) => tool.metadata.annotations?.readOnlyHint)); } } ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, GetTicket } from "./tools"; import { ReadOnlyPlugin } from "./read-only.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, CloseTicket], plugins: [ReadOnlyPlugin.init({ enabled: true })], }) export class HelpDeskApp {} ``` ```ts read-only.test.ts import { test, expect } from "@frontmcp/testing"; test("close_ticket is left out of tools/list", async ({ mcp }) => { expect(await mcp.tools.list()).not.toContainTool("close_ticket"); }); test("calling it anyway is refused with the hook's message", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result).toBeError(); expect(result).toHaveTextContent("read-only during maintenance"); expect(result.raw._meta?.code).toBe("PUBLIC_ERROR"); }); test("read-only tools still work", async ({ mcp }) => { expect(await mcp.tools.call("get_ticket", { id: "T-1" })).toBeSuccessful(); }); ``` A few things to notice: - **The error reaches the model word for word.** A `PublicMcpError` thrown from a `Will` hook arrives as an `isError` result with its message and `_meta.code: "PUBLIC_ERROR"`. Say why the call was refused and what to do instead, because the model will pass it on. Any other error a `Will` hook throws fails the call too, but as a `SERVER_ERROR` whose message is hidden in production. Throws from `Finally` hooks are logged and ignored. - **`filter`** decides per call whether the hook runs at all. It gets the same `ctx`. It's a plain function in the decorator, so it can't see the plugin's options; those are checked inside. - **Hiding isn't blocking.** The `ListToolsHook` only changes what `tools/list` returns. A client that calls `close_ticket` by name still reaches it, which is why the `ToolHook` refuses the call as well. ## Changing the result `Did("execute")` runs after the tool returns and before FrontMCP turns its return value into `content` and `structuredContent`. Assign a new value to `ctx.state.toolContext.output`, and that's what the client gets. Here a plugin keeps customer email addresses out of every result, so they never reach the model: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts redact.plugin.ts active import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; function redactEmails(value: unknown): unknown { if (Array.isArray(value)) return value.map(redactEmails); if (value && typeof value === "object") { return Object.fromEntries( Object.entries(value).map(([key, v]) => [key, key === "email" ? "[redacted]" : redactEmails(v)]), ); } return value; } @Plugin({ name: "redact", description: "Removes email addresses from tool results" }) export class RedactPlugin extends DynamicPlugin { @ToolHook.Did("execute") async redact(ctx: FlowCtxOf<"tools:call-tool">) { const { toolContext } = ctx.state; if (toolContext) toolContext.output = redactEmails(toolContext.output); } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", customer: { name: "Dana Levi", email: "dana@acme.com" } }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket } from "./get-ticket.tool"; import { RedactPlugin } from "./redact.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], plugins: [RedactPlugin] }) export class HelpDeskApp {} ``` ```ts redact.test.ts import { test, expect } from "@frontmcp/testing"; test("the email is redacted in the structured result", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result.raw.structuredContent).toEqual({ id: "T-1", title: "Cannot log in", customer: { name: "Dana Levi", email: "[redacted]" }, }); }); test("and in the text the model reads", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result).not.toHaveTextContent("dana@acme.com"); }); ``` Because the hook runs before the result is formatted, the text block and `structuredContent` both come from the redacted value. The tool doesn't know it happened, and new tools get the same treatment without any change. ### Answering without running the tool A `Will("execute")` hook can also answer the call itself, and the tool never runs. That's how a cache works. `ctx.respond()` takes a complete `tools/call` result, with `content` and, for objects, `structuredContent`: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts cache.plugin.ts active import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; type CallCtx = FlowCtxOf<"tools:call-tool">; const readOnly = (ctx: CallCtx) => ctx.state.tool?.metadata.annotations?.readOnlyHint === true; @Plugin({ name: "cache", description: "Answers repeated read-only calls from memory" }) export class CachePlugin extends DynamicPlugin { private results = new Map>(); private key(ctx: CallCtx) { return `${ctx.state.tool?.metadata.name}:${JSON.stringify(ctx.state.toolContext?.input)}`; } @ToolHook.Will("execute", { filter: readOnly }) async answerFromCache(ctx: CallCtx) { const cached = this.results.get(this.key(ctx)); if (cached) ctx.respond({ content: [{ type: "text", text: JSON.stringify(cached) }], structuredContent: cached }); } @ToolHook.Did("execute", { filter: readOnly }) async store(ctx: CallCtx) { this.results.set(this.key(ctx), ctx.state.toolContext?.output as Record); } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { Database } from "./database"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return this.get(Database).loadTicket(id); } } ``` ```ts database.ts import { Provider } from "@frontmcp/sdk"; @Provider({ name: "Database" }) export class Database { private queries = 0; loadTicket(id: string) { this.queries += 1; return { id, title: "Cannot log in", query: this.queries }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket } from "./get-ticket.tool"; import { Database } from "./database"; import { CachePlugin } from "./cache.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], providers: [Database], plugins: [CachePlugin] }) export class HelpDeskApp {} ``` ```ts cache.test.ts import { test, expect } from "@frontmcp/testing"; test("asking for T-1 twice queries the database once", async ({ mcp }) => { const first = await mcp.tools.call("get_ticket", { id: "T-1" }); const second = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(first.json()).toEqual({ id: "T-1", title: "Cannot log in", query: 1 }); expect(second.json()).toEqual({ id: "T-1", title: "Cannot log in", query: 1 }); }); test("a different ticket is a different entry", async ({ mcp }) => { expect((await mcp.tools.call("get_ticket", { id: "T-2" })).json().query).toBe(2); }); ``` `ctx.respond()` ends the call on the spot: the tool, the `Did("execute")` hooks and the result formatting are all skipped, so the value you pass has to be a finished result. For real use, the official [Cache plugin](https://frontmcp.dev/reference/plugins/cache), `@frontmcp/plugin-cache`, adds expiry, Redis, and keys that include the caller, so one user's cached answer is never served to another. What `respond()` sends, from a hook and from a tool, and where it doesn't work, is in the [`this.respond()` reference](https://frontmcp.dev/reference/sdk/respond). ## The order hooks run in When several hooks share a stage, FrontMCP runs them by `priority`, a number you pass next to `filter`. **Lower numbers run first**, for `Will` and `Did` hooks alike, and the default is `0`. Hooks with the same priority run in the order their plugins are listed in `plugins`: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts plugins.ts active import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; import { Trace } from "./trace"; type CallCtx = FlowCtxOf<"tools:call-tool">; // Trace is a CONTEXT provider: one per call, reached through the call's toolContext const trace = (ctx: CallCtx, line: string) => ctx.state.toolContext?.get(Trace).lines.push(line); @Plugin({ name: "first" }) export class FirstPlugin extends DynamicPlugin { @ToolHook.Will("execute") async will(ctx: CallCtx) { trace(ctx, "first: will, priority 0"); } @ToolHook.Did("execute", { priority: 10 }) async did(ctx: CallCtx) { trace(ctx, "first: did, priority 10"); } } @Plugin({ name: "second" }) export class SecondPlugin extends DynamicPlugin { @ToolHook.Will("execute", { priority: -10 }) async will(ctx: CallCtx) { trace(ctx, "second: will, priority -10"); } @ToolHook.Did("execute") async did(ctx: CallCtx) { trace(ctx, "second: did, priority 0"); } // Wraps the stage: its first half runs after the Will hooks, its second half before the Did hooks @ToolHook.Around("execute") async around(ctx: CallCtx, next: () => Promise) { trace(ctx, "second: around, before next()"); await next(); trace(ctx, "second: around, after next()"); } } ``` ```ts trace.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "Trace", scope: ProviderScope.CONTEXT }) export class Trace { lines: string[] = []; } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { Trace } from "./trace"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { this.get(Trace).lines.push("get_ticket runs"); return { id, trace: this.get(Trace).lines }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket } from "./get-ticket.tool"; import { Trace } from "./trace"; import { FirstPlugin, SecondPlugin } from "./plugins"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], providers: [Trace], plugins: [FirstPlugin, SecondPlugin], }) export class HelpDeskApp {} ``` ```ts order.test.ts import { test, expect } from "@frontmcp/testing"; test("hooks run by priority, lowest first", async ({ mcp }) => { const trace = (await mcp.tools.call("get_ticket", { id: "T-1" })).json().trace; expect(trace).toEqual([ "second: will, priority -10", "first: will, priority 0", "second: around, before next()", "get_ticket runs", "second: around, after next()", "second: did, priority 0", "first: did, priority 10", ]); }); ``` The result shows the whole call: the `Will` hooks from lowest priority to highest, the first half of the `Around` hook, the tool, the second half, then the `Did` hooks, again from lowest to highest. (The `Did` lines show up in the result because they're added to the same array after the tool returns it and before it's formatted.) Give a hook a priority when its order matters: a check that must see the cleaned-up input needs a higher number than the hook that cleans it up. The last challenge below is about exactly that. ## Recap - A tool call runs through the `tools:call-tool` flow: stages before, `validateInput` → `execute` → `validateOutput`, then closing stages that always run. - `@ToolHook.Will(stage)` runs before a stage and `@ToolHook.Did(stage)` after it. `Did` hooks only run if the stage worked; `Finally("finalize")` runs for every call, including when output validation fails. `@ToolHook.Around(stage)` wraps the stage: `await next()` runs it, and throws if it fails. - `ctx.state.input.arguments` is what the client sent, `ctx.state.tool` is the tool, and `ctx.state.toolContext` has the validated `input` and, after `execute`, the `output`. - Time and log calls with `Around("execute")`, normalize arguments in `Will("validateInput")`, refuse calls by throwing a `PublicMcpError` in `Will("execute")`, change results in `Did("execute")`, and answer from a cache with `ctx.respond()`. - Hooks on a stage run by `priority`, lowest first, for `Will` and `Did` alike. `filter` skips a hook for some calls. - Every hook decorator, flow and stage, and the full run order, are in the [hook decorators reference](https://frontmcp.dev/reference/sdk/hooks). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Accept lowercase ticket ids This plugin is meant to accept ids like `" t-2 "`, but they're still rejected with `INVALID_INPUT`. Fix the hook so they reach the tool as `T-2`, while ids that aren't ticket ids are still rejected. Initial call configuration: ```js { tool: "get_ticket", arguments: { id: " t-2 " } } ``` ```ts ticket-ids.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; @Plugin({ name: "ticket-ids" }) export class TicketIdsPlugin extends DynamicPlugin { @ToolHook.Will("execute") async normalizeTicketId(ctx: FlowCtxOf<"tools:call-tool">) { const input = ctx.state.toolContext?.input as { id?: unknown } | undefined; if (typeof input?.id === "string") input.id = input.id.trim().toUpperCase(); } } ``` **Solution file (alternative to the starter):** ```ts ticket-ids.plugin.ts solution import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; @Plugin({ name: "ticket-ids" }) export class TicketIdsPlugin extends DynamicPlugin { @ToolHook.Will("validateInput") async normalizeTicketId(ctx: FlowCtxOf<"tools:call-tool">) { const args = ctx.state.input?.arguments; if (typeof args?.id === "string") args.id = args.id.trim().toUpperCase(); } } ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const ticketId = z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1"); @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: ticketId } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Invoice total is wrong" }; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: ticketId } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, GetTicket } from "./tools"; import { TicketIdsPlugin } from "./ticket-ids.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, CloseTicket], plugins: [TicketIdsPlugin] }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts ids.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`get_ticket` reads \" t-2 \" as T-2", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: " t-2 " }); expect(result).toBeSuccessful(); expect(result.json().id).toBe("T-2"); }); test("it works for every tool, like `close_ticket`", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "t-4" }); expect(result).toBeSuccessful(); expect(result.json().id).toBe("T-4"); }); test("\"ticket two\" is still rejected", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "ticket two" }); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); ``` **Hint:** Look at the stage table. Which stage rejects `" t-2 "`, and does it run before or after `execute`? **Solution:** `validateInput` runs before `execute`, so a hook in `Will("execute")` never sees an id the schema rejected. In `Will("validateInput")` the arguments haven't been checked yet, so the hook edits `ctx.state.input.arguments`, the raw arguments, and the schema then checks the cleaned-up value. ### Challenge: Freeze changes over the weekend Add a hook to `FreezePlugin` that refuses every tool not marked `readOnlyHint`, with a `PublicMcpError` whose message mentions the freeze. The refused tool must not run. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts freeze.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, PublicMcpError, ToolHook } from "@frontmcp/sdk"; @Plugin({ name: "freeze", description: "Refuses changes during the weekend freeze" }) export class FreezePlugin extends DynamicPlugin {} ``` **Solution file (alternative to the starter):** ```ts freeze.plugin.ts solution import { DynamicPlugin, FlowCtxOf, Plugin, PublicMcpError, ToolHook } from "@frontmcp/sdk"; @Plugin({ name: "freeze", description: "Refuses changes during the weekend freeze" }) export class FreezePlugin extends DynamicPlugin { @ToolHook.Will("execute", { filter: (ctx) => !ctx.state.tool?.metadata.annotations?.readOnlyHint }) async refuse(ctx: FlowCtxOf<"tools:call-tool">) { throw new PublicMcpError( `Changes are paused for the weekend freeze, so ${ctx.state.tool?.metadata.name} is unavailable until Monday.`, ); } } ``` ```ts tools.ts import { Provider, Tool, ToolContext, z } from "@frontmcp/sdk"; @Provider({ name: "TicketStore" }) export class TicketStore { status: Record = { "T-1": "open", "T-2": "open" }; } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: this.get(TicketStore).status[id] }; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { this.get(TicketStore).status[id] = "closed"; return { id, status: "closed" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, GetTicket, TicketStore } from "./tools"; import { FreezePlugin } from "./freeze.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, CloseTicket], providers: [TicketStore], plugins: [FreezePlugin], }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts freeze.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`close_ticket` is refused with a message about the freeze", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result).toBeError(); expect(result.text()).toMatch(/freeze/i); expect(result.raw._meta?.code).toBe("PUBLIC_ERROR"); }); test("the ticket stays open, because the tool never ran", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-2" }); expect((await mcp.tools.call("get_ticket", { id: "T-2" })).json().status).toBe("open"); }); test("`get_ticket` still works", async ({ mcp }) => { expect(await mcp.tools.call("get_ticket", { id: "T-1" })).toBeSuccessful(); }); ``` **Hint:** `@ToolHook.Will("execute", { filter })` runs right before a tool, only for calls where `filter` returns `true`. Throw from the hook to stop the call. **Solution:** The hook runs before `execute()`, so throwing there stops the call before `close_ticket` can change anything, and the `filter` leaves read-only tools alone. Because the error is a `PublicMcpError` thrown from a hook, the model gets the message as written, with the code `PUBLIC_ERROR`. A good message says why the call was refused and when to try again. ### Challenge: Redact every email Customer emails must never reach the model, and `list_tickets` returns several customers. Add a hook to `RedactPlugin` that replaces the value of every `email` field in a tool's result, however deeply nested, with `"[redacted]"`. Initial call configuration: ```js { tool: "list_tickets", arguments: {} } ``` ```ts redact.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; @Plugin({ name: "redact", description: "Removes email addresses from tool results" }) export class RedactPlugin extends DynamicPlugin {} ``` **Solution file (alternative to the starter):** ```ts redact.plugin.ts solution import { DynamicPlugin, FlowCtxOf, Plugin, ToolHook } from "@frontmcp/sdk"; function redactEmails(value: unknown): unknown { if (Array.isArray(value)) return value.map(redactEmails); if (value && typeof value === "object") { return Object.fromEntries( Object.entries(value).map(([key, v]) => [key, key === "email" ? "[redacted]" : redactEmails(v)]), ); } return value; } @Plugin({ name: "redact", description: "Removes email addresses from tool results" }) export class RedactPlugin extends DynamicPlugin { @ToolHook.Did("execute") async redact(ctx: FlowCtxOf<"tools:call-tool">) { const { toolContext } = ctx.state; if (toolContext) toolContext.output = redactEmails(toolContext.output); } } ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", customer: { name: "Dana Levi", email: "dana@acme.com" } }, { id: "T-2", title: "Invoice total is wrong", customer: { name: "Omar Aziz", email: "omar@globex.com" } }, ]; @Tool({ name: "list_tickets", description: "List every support ticket with its customer", inputSchema: {} }) export class ListTickets extends ToolContext { async execute() { return { tickets }; } } @Tool({ name: "get_customer", description: "Get the customer of one ticket", inputSchema: { id: z.string() } }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return tickets.find((t) => t.id === id)?.customer ?? { name: "unknown" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { GetCustomer, ListTickets } from "./tools"; import { RedactPlugin } from "./redact.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [ListTickets, GetCustomer], plugins: [RedactPlugin] }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts redact.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("no email address appears in `list_tickets`", async ({ mcp }) => { const result = await mcp.tools.call("list_tickets", {}); expect(JSON.stringify(result.raw)).not.toContain("@"); }); test("each customer's `email` is \"[redacted]\"", async ({ mcp }) => { const result = await mcp.tools.call("list_tickets", {}); expect(result.json().tickets.map((t: any) => t.customer.email)).toEqual(["[redacted]", "[redacted]"]); }); test("`get_customer` is redacted too, and names are kept", async ({ mcp }) => { const result = await mcp.tools.call("get_customer", { id: "T-2" }); expect(result.json()).toEqual({ name: "Omar Aziz", email: "[redacted]" }); }); ``` **Hint:** `Did("execute")` sees the tool's return value as `ctx.state.toolContext.output`. Build a redacted copy and assign it back; a small recursive function handles arrays and nested objects. **Solution:** The hook replaces `output` after every tool returns and before FrontMCP formats it, so both the text block and `structuredContent` are built from the redacted copy. Returning a copy instead of editing in place also keeps the tool's own data intact: `tickets` still has the real addresses for the next call. ### Challenge: Clean up before checking the lock Ticket T-7 is locked for a legal hold, and `LockPlugin` refuses any call for it. But a model that sends `" t-7 "` gets through and closes it. Change the order of the two hooks so the lock check sees the cleaned-up id. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: " t-7 " } } ``` ```ts lock.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, PublicMcpError, ToolHook } from "@frontmcp/sdk"; type CallCtx = FlowCtxOf<"tools:call-tool">; const locked = ["T-7"]; @Plugin({ name: "lock", description: "Normalizes ticket ids and refuses calls for locked tickets" }) export class LockPlugin extends DynamicPlugin { @ToolHook.Will("validateInput") async checkLock(ctx: CallCtx) { const id = ctx.state.input?.arguments?.id; if (typeof id === "string" && locked.includes(id)) { throw new PublicMcpError(`Ticket ${id} is locked for a legal hold and can't be changed.`); } } @ToolHook.Will("validateInput", { priority: 10 }) async normalizeTicketId(ctx: CallCtx) { const args = ctx.state.input?.arguments; if (typeof args?.id === "string") args.id = args.id.trim().toUpperCase(); } } ``` **Solution file (alternative to the starter):** ```ts lock.plugin.ts solution import { DynamicPlugin, FlowCtxOf, Plugin, PublicMcpError, ToolHook } from "@frontmcp/sdk"; type CallCtx = FlowCtxOf<"tools:call-tool">; const locked = ["T-7"]; @Plugin({ name: "lock", description: "Normalizes ticket ids and refuses calls for locked tickets" }) export class LockPlugin extends DynamicPlugin { @ToolHook.Will("validateInput", { priority: 10 }) async checkLock(ctx: CallCtx) { const id = ctx.state.input?.arguments?.id; if (typeof id === "string" && locked.includes(id)) { throw new PublicMcpError(`Ticket ${id} is locked for a legal hold and can't be changed.`); } } @ToolHook.Will("validateInput") async normalizeTicketId(ctx: CallCtx) { const args = ctx.state.input?.arguments; if (typeof args?.id === "string") args.id = args.id.trim().toUpperCase(); } } ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket } from "./tools"; import { LockPlugin } from "./lock.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], plugins: [LockPlugin] }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts lock.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("\" t-7 \" is refused as locked", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: " t-7 " }); expect(result).toBeError(); expect(result).toHaveTextContent("T-7 is locked"); }); test("\"T-7\" is refused as locked", async ({ mcp }) => { expect(await mcp.tools.call("close_ticket", { id: "T-7" })).toHaveTextContent("locked"); }); test("other tickets still close, in any case", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: " t-1 " }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ id: "T-1", status: "closed" }); }); ``` **Hint:** Both hooks are on `Will("validateInput")`, so `priority` decides. Which one runs first now? **Solution:** Lower priorities run first. With `normalizeTicketId` at the default `0` and `checkLock` at `10`, the id is cleaned up before the lock check reads it, so `" t-7 "` is refused like `"T-7"`. Moving the methods around in the class wouldn't have helped: the order in the class only breaks ties between equal priorities. --- # Securing a Server > Who may connect to a FrontMCP server, what each caller may do, and how often and how long a tool may run. Authentication, authorization, rate limits and timeouts. Source: https://frontmcp.dev/learn/securing-a-server [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every server so far in this course has let anyone call any tool, as often as they liked, for as long as the tool took. That's fine on your laptop. Once a server is reachable over a network, you need answers to three questions: who is calling, what may they do, and how much of it. This chapter answers each one with FrontMCP. **In this chapter** - [How clients prove who they are, and which auth mode to choose](https://frontmcp.dev/learn/authenticating-clients) - [How to decide who can call which tool, and refuse the rest](https://frontmcp.dev/learn/authorizing-calls) - [How to limit how often a tool runs, how many run at once, and for how long](https://frontmcp.dev/learn/limiting-calls) ## Authenticating clients A client proves who it is with a credential in the `Authorization` header of every request, and the server's `auth` mode decides which credentials count. With no `auth` at all, a server is public: every request gets in, as an anonymous caller. Initial call configuration: ```js { tool: "whoami", arguments: {} } ``` ```ts whoami.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "whoami", description: "Say who the server thinks is calling, and with which scopes.", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class WhoAmI extends ToolContext { async execute() { return { caller: this.auth.user.sub, scopes: this.auth.scopes }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts whoami.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("each call is a new anonymous caller", async ({ mcp }) => { const first = (await mcp.tools.call("whoami", {})).json(); const second = (await mcp.tools.call("whoami", {})).json(); expect(first).toMatchObject({ caller: expect.stringMatching(/^anon:/), scopes: ["anonymous"] }); expect(second.caller).not.toBe(first.caller); }); ``` Call it again and the id changes: under MCP 2026-07-28, each anonymous request is a new caller. One line of configuration requires a shared key instead, and other modes accept tokens from your identity provider or sign users in themselves: ```ts auth: { mode: "static", tokens: [process.env.DESK_API_KEY!] }, ``` ### [Authenticating Clients](https://frontmcp.dev/learn/authenticating-clients) Learn where credentials travel, how the `public`, `static`, `transparent`, `local` and `remote` modes differ, what a client gets back when it isn't let in, and how to choose. ## Deciding who can call what Knowing who is calling isn't the same as deciding what they may do. A tool can read the caller from `this.auth` and refuse, with a message the model can pass on to the user. Here only callers with the `tickets:write` scope may close tickets, and an anonymous caller doesn't have it: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket. Only signed-in support agents can close tickets.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { if (!this.auth.hasScope("tickets:write")) { this.fail(new PublicMcpError("Only signed-in support agents can close tickets. Tell the user to sign in as an agent.", "FORBIDDEN")); } return { id, closed: true }; } } ``` A tool can also declare who may use it with `authorities`. FrontMCP then refuses other callers before `execute()` runs, and leaves the tool out of their `tools/list`. ### [Deciding Who Can Call What](https://frontmcp.dev/learn/authorizing-calls) Learn what `this.auth` holds in each auth mode, how to refuse a call well, how to declare roles and permissions with `authorities`, and why `visibility: "hidden"` doesn't protect a tool. ## Limiting and timing out calls A model can call a tool in a loop. `rateLimit`, `concurrency` and `timeout` on `@Tool` cap how often it runs, how many calls run at once, and how long one may take. This export runs at most twice an hour: it ran once when the example started, so press **Call** twice more. Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts main.ts import { App, FrontMcp, Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "export_tickets", description: "Export every support ticket as CSV. At most 2 exports an hour.", inputSchema: {}, annotations: { readOnlyHint: true }, rateLimit: { maxRequests: 2, windowMs: 60 * 60_000 }, }) class ExportTickets extends ToolContext { async execute() { return { csv: "id,title,status\nT-1,Cannot log in,open\nT-2,Invoice total is wrong,closed" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ExportTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts limit.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the third export in an hour is refused", async ({ mcp }) => { await mcp.tools.call("export_tickets", {}); await mcp.tools.call("export_tickets", {}); const third = await mcp.tools.call("export_tickets", {}); expect(third.raw._meta?.code).toBe("RATE_LIMIT_EXCEEDED"); expect(third.text()).toMatch(/Retry after \d+ seconds/); }); ``` The third call is refused with `RATE_LIMIT_EXCEEDED` and says when to retry. ### [Limiting and Timing Out Calls](https://frontmcp.dev/learn/limiting-calls) Learn what callers get back when a limit trips, whose calls a limit counts, how to stop a tool's runs overlapping, what happens when a call runs out of time, and how to choose limits for expensive and destructive tools. ## What's next? Start the chapter with [Authenticating Clients](https://frontmcp.dev/learn/authenticating-clients). After it, [Doing Work in the Background](https://frontmcp.dev/learn/background-work) covers work that's too slow, too flaky or too long for a single tool call. --- # Authenticating Clients > How MCP clients prove who they are to a FrontMCP server: the five auth modes, how each maps to the MCP authorization spec's OAuth 2.1 roles, and how to choose. Source: https://frontmcp.dev/learn/authenticating-clients [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Authentication answers one question: who is calling? An MCP client answers it with a credential in the `Authorization` header of every request, and FrontMCP checks that credential before any tool runs. Which credentials count, and what happens to a request without one, depend on the server's `auth` mode. FrontMCP has five: `public`, `static`, `transparent`, `local` and `remote`. **You will learn** - Who is calling when a request carries no credentials - Where credentials travel, and why they never go in tool arguments - How to protect a server with a shared key (`static`) - How to accept tokens from your identity provider (`transparent`) - What a client gets back when it isn't let in, and how to choose a mode ## A server anyone can call Every server so far in this course has had no `auth` option, which means `mode: "public"`: every request is let in. Here the mode is spelled out, and `whoami` reports who FrontMCP thinks is calling: Initial call configuration: ```js { tool: "whoami", arguments: {} } ``` ```ts whoami.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "whoami", description: "Say who the server thinks is calling, and with which scopes.", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class WhoAmI extends ToolContext { async execute() { return { caller: this.auth.user.sub, scopes: this.auth.scopes }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { WhoAmI } from "./whoami.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [WhoAmI] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "public" }, }) export default class Server {} ``` ```ts whoami.test.ts import { test, expect } from "@frontmcp/testing"; test("every request is a new anonymous caller", async ({ mcp }) => { const first = (await mcp.tools.call("whoami", {})).json(); const second = (await mcp.tools.call("whoami", {})).json(); expect(first.caller).toMatch(/^anon:/); expect(second.caller).toMatch(/^anon:/); expect(second.caller).not.toBe(first.caller); expect(first.scopes).toEqual(["anonymous"]); }); ``` The caller is `anon:` followed by a random id, with one scope, `anonymous`. `this.auth` is where a tool finds out who is calling; the [next lesson](https://frontmcp.dev/learn/authorizing-calls) covers what's in it. Now open the **Tests** tab. Call `whoami` twice and you get two different ids. Under MCP 2026-07-28 there are no sessions: each request is authenticated on its own, and a request without credentials is a new stranger every time. Your server can't tell that two anonymous calls came from the same client. That matters for anything that counts per caller: the [rate limits](https://frontmcp.dev/learn/limiting-calls) later in this chapter count all anonymous callers together, as one. It matters for anything kept per caller too: by default, the [Cache plugin](https://frontmcp.dev/learn/caching-results#turning-the-cache-on) never answers an anonymous caller from its cache. Public mode is right on your laptop and for a server that only exposes public data. On a server that can reach your tickets, anyone who finds the URL can call every tool. ## Where credentials travel A client sends its credential in the HTTP `Authorization` header, on every request, including `tools/list`: ```text POST / HTTP/1.1 Host: desk.example.com Authorization: Bearer 9c1f4e7a… Content-Type: application/json MCP-Protocol-Version: 2026-07-28 Mcp-Method: tools/call Mcp-Name: close_ticket {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"close_ticket","arguments":{"id":"T-1"}}} ``` The header is set by the client application, from what the user configured or signed in with. The model never sees it and can't change it. Tool arguments are the opposite: the model writes them, and it can write anything. So a tool should never learn who is calling from an argument like `agent` or `userId`. It reads the identity FrontMCP established from the header. The first challenge below fixes a tool that gets this wrong. > **Note** > > The Playground's client doesn't send an `Authorization` header, so a server that requires one refuses every request the Playground makes, including the `tools/list` it needs to start. The examples below that need credentials are plain code, with the responses FrontMCP sends. Run them in your own project to try them. ## Requiring a shared key: static mode The smallest step up from public is one secret that every legitimate client sends. Many MCP hosts have a setting for exactly this, often labelled "API key" or "access token", that adds a fixed `Authorization: Bearer …` header to every request. `mode: "static"` checks it: ```ts main.ts @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static", tokens: [process.env.DESK_API_KEY!] }, }) export default class Server {} ``` A request without the header, or with a key that isn't in `tokens`, doesn't reach any tool: ```text HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer realm="mcp" Content-Type: application/json; charset=utf-8 {"error":"Unauthorized"} ``` A wrong key gets the same status, with the reason in the challenge: ```text WWW-Authenticate: Bearer realm="mcp", error="invalid_token", error_description="The access token is invalid" ``` This is an HTTP response, not a JSON-RPC error or a tool result. The model never sees it; the client does, and the fix is in the client's settings. A request with the right key gets through, and its caller is `static:` followed by 12 hex characters derived from the key, with the scope `static`. The key itself never reaches your tools: it's in neither `this.auth` nor `this.context.authInfo`. | Option | Default | What it does | | --- | --- | --- | | `tokens` | required | The accepted keys. Compared in constant time. | | `header` | `"authorization"` | The request header that carries the key, like `"x-api-key"`. | | `scheme` | `"Bearer"` | The prefix before the key, matched without regard to case. `""` for a header that holds the bare key. | | `scopes` | `["static"]` | The scopes an accepted request gets. | | `realm` | `"mcp"` | The realm in the `WWW-Authenticate` challenge. | > **Pitfall: A shared key identifies a key, not a person** > > Everyone with the same key is the same caller: one `static:…` id, the same scopes. There's no way to tell users apart or to revoke one of them. To rotate a key, deploy with both the old and the new key in `tokens`; each gets its own id. Then remove the old one. When you need to know which person is calling, use tokens from an identity provider. ## Accepting tokens from your identity provider If your users already sign in with an identity provider, like Auth0, Okta or Keycloak, the client can get an access token (a signed JWT) from it and send that. `mode: "transparent"` checks those tokens and doesn't issue any of its own: ```ts main.ts @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "transparent", provider: "https://auth.example.com", expectedAudience: "https://desk.example.com", requiredScopes: ["tickets:read"], }, }) export default class Server {} ``` For each request, FrontMCP checks that the token is signed by one of the provider's keys, that its issuer (`iss`) is `provider`, that it hasn't expired, and, if it names an audience (`aud`), that the audience is `expectedAudience`. The caller is then the token's `sub`, its scopes come from the token's `scope` claim (or `scp`, which some providers use instead), and the rest of its claims are available to your tools. A request that fails gets a 401 or 403 that says why: | Request | Status | `WWW-Authenticate` | | --- | --- | --- | | No token | `401` | `Bearer resource_metadata="https://desk.example.com/.well-known/oauth-protected-resource"` | | Not a JWT | `401` | The same, plus `error="invalid_token", error_description="Token is not a valid JWT"` | | Expired, wrong issuer, or a signature the provider's keys don't match | `401` | The same, plus `error="invalid_token", error_description="no_provider_verified (kid=…)"` | | No `sub`, `client_id` or `azp`: it doesn't say who is calling | `401` | The same, plus `error="invalid_token"` and a description naming the missing claims | | Issued for another audience | `401` | The same, plus `error="invalid_token"` and a description naming both audiences | | Missing a scope in `requiredScopes` | `403` | The same, plus `error="insufficient_scope"` and `scope="tickets:read"` | The URLs in these headers start with the server's address. FrontMCP's Node server builds it from `http://` and the request's `Host` header, so behind a proxy that terminates TLS they say `http://`; set `FRONTMCP_PUBLIC_URL=https://desk.example.com` to get the addresses above. [The server's public address](https://frontmcp.dev/reference/auth/modes#the-servers-public-address) has the details. `resource_metadata` points at a document FrontMCP serves, which tells an MCP client where to get a token. That's how a client that has never seen your server knows to start a sign-in instead of just failing. > **Note** > > FrontMCP finds the provider's signing keys by itself. It tries `/.well-known/jwks.json`, then the `jwks_uri` that the provider lists in its `/.well-known/oauth-authorization-server` or OpenID `/.well-known/openid-configuration` metadata. If your provider keeps its keys somewhere else, set `providerConfig.jwksUri` to its JWKS URL, or write the keys into your config as `providerConfig.jwks`. A server that finds no keys refuses every token with `no_provider_verified`. [Tokens and sessions](https://frontmcp.dev/reference/auth/tokens#where-the-keys-come-from) shows each request FrontMCP makes. ### Letting anonymous callers in, with less A token-only server shuts out everyone who hasn't signed in. `allowAnonymous: true` lets requests without a token in, as anonymous callers with the scopes in `anonymousScopes`. Requests that do carry a token are still checked, and a bad token is still refused. Because an anonymous request needs no header, this one runs in the Playground: Initial call configuration: ```js { tool: "whoami", arguments: {} } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { WhoAmI } from "./whoami.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [WhoAmI] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "transparent", provider: "https://auth.example.com", allowAnonymous: true, anonymousScopes: ["tickets:read"], }, }) export default class Server {} ``` ```ts whoami.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "whoami", description: "Say who the server thinks is calling, and with which scopes.", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class WhoAmI extends ToolContext { async execute() { return { caller: this.auth.user.sub, scopes: this.auth.scopes }; } } ``` The caller is still `anon:…`, now with the scope `tickets:read`. A signed-in support agent would arrive with the scopes in their token, like `tickets:read tickets:write`. Letting each tool decide what those scopes allow is the subject of the [next lesson](https://frontmcp.dev/learn/authorizing-calls). > **Note** > > `anonymousScopes` works in `public` mode too, in place of the scope `anonymous`. And every mode accepts `publicAccess`, which limits what anonymous callers may use. With `publicAccess: { tools: ["search_tickets"] }`, every other tool is left out of an anonymous caller's `tools/list` and refused when called by name; `prompts` does the same for prompts, and anonymous calls are limited to `rateLimit` a minute per IP address, 60 by default. Signed-in callers aren't affected, and `publicAccess` doesn't let anyone in: a `static` server still refuses requests without a key. [Auth modes](https://frontmcp.dev/reference/auth/modes#limiting-what-anonymous-callers-can-use) shows both. ## Letting FrontMCP run the sign-in `transparent` assumes someone else issues the tokens. In the other two modes, FrontMCP is itself an OAuth 2.1 authorization server: MCP clients register with it, send the user to sign in, and get tokens FrontMCP signed. - **`local`**: FrontMCP shows its own sign-in page and issues tokens for the users who complete it. For a server with no identity provider behind it. - **`remote`**: FrontMCP sends the user to an upstream provider (`provider`, with your `clientId` and `clientSecret` there) to sign in, then issues its own token for that identity. For providers that MCP clients can't register with directly, or when you want FrontMCP's consent screen between the user and your tools. ```ts main.ts @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "remote", provider: "https://auth.example.com", clientId: process.env.DESK_CLIENT_ID!, clientSecret: process.env.DESK_CLIENT_SECRET!, }, }) export default class Server {} ``` To a client without a token, both answer like `transparent`: a `401` with `resource_metadata`, except that the document it points to names FrontMCP itself as the place to get a token. The tokens they issue are kept in memory by default (`tokenStorage: "memory"`), so they're lost on restart and not shared between instances; `tokenStorage` also takes `{ redis }` or `{ sqlite }`. Their sign-in pages, consent screens and storage have many options of their own, beyond this lesson: see [Local auth](https://frontmcp.dev/reference/auth/local), [Custom login UI](https://frontmcp.dev/reference/auth/login-ui), [Remote and proxied auth](https://frontmcp.dev/reference/auth/remote), and [Client ID metadata](https://frontmcp.dev/reference/auth/cimd) for clients that identify themselves by a URL. ## How the modes map to MCP authorization In the terms of the [MCP authorization specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) (revision 2026-07-28, the newest of the [revisions FrontMCP speaks](https://frontmcp.dev/reference/server/protocol-versions#supported-revisions)), a FrontMCP server in `transparent` mode is an OAuth 2.1 resource server only: your identity provider is the authorization server, and FrontMCP verifies the JWTs it issues. In `local` and `remote` mode, FrontMCP is both the resource server and the authorization server: it publishes authorization server metadata ([RFC 8414](https://www.rfc-editor.org/rfc/rfc8414)), registers clients ([RFC 7591](https://www.rfc-editor.org/rfc/rfc7591)) or accepts [Client ID Metadata Documents](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00), advertises PKCE ([RFC 7636](https://www.rfc-editor.org/rfc/rfc7636)) with `S256`, and issues the tokens it then checks. In all three, a request without a token gets a `401` that points to the server's Protected Resource Metadata ([RFC 9728](https://www.rfc-editor.org/rfc/rfc9728)), unless `transparent` mode's `allowAnonymous` lets it in. `public` and `static` mode don't use OAuth. The specification [lets the authorization server be the MCP server itself or a separate service](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#roles). That choice is what separates `transparent` from `local` and `remote`: | Mode | Role in MCP authorization | What it serves | PKCE | How it checks tokens | Details | | --- | --- | --- | --- | --- | --- | | `public` | None: every request gets in | Protected Resource Metadata without `authorization_servers`. Authorization server metadata is `404` | None | No token needed. A bearer JWT must be one this server signed | [What the server advertises](https://frontmcp.dev/reference/auth/modes#what-the-server-advertises), [requests without credentials](https://frontmcp.dev/reference/auth/modes#what-a-request-without-credentials-gets) | | `static` | None: a shared key, not OAuth | The same as `public`. Its `401` has no `resource_metadata`, since a client can't get a key by itself | None | Compares the key with `tokens`, in constant time | [Static keys](https://frontmcp.dev/reference/auth/tokens#static-keys), [requests without credentials](https://frontmcp.dev/reference/auth/modes#what-a-request-without-credentials-gets) | | `transparent` | Resource server only. Your identity provider is the authorization server | Protected Resource Metadata, naming this server. `/.well-known/oauth-authorization-server` redirects to your provider's. Registration and CIMD are up to your provider | At your provider: FrontMCP serves no OAuth endpoints | Signature against your provider's keys, `iss`, `exp`, `nbf`, `requiredScopes`, and `aud` against `expectedAudience`. A token without `aud` passes unless `requireAudience` is `true` | [What the server advertises](https://frontmcp.dev/reference/auth/modes#what-the-server-advertises), [What's checked](https://frontmcp.dev/reference/auth/tokens#whats-checked), [CIMD caveats](https://frontmcp.dev/reference/auth/cimd#caveats) | | `local` | Resource server and authorization server. Users sign in on FrontMCP's page | Protected Resource Metadata, authorization server metadata, dynamic client registration (off in production unless `dcr.enabled`), and CIMD | Required, `S256` only: `plain` is refused | Its own HS256 JWTs: signature, `exp`, `iss`, and `aud`, which must be this server's URL or one of `expectedAudience`. An authorization request's `resource` ([RFC 8707](https://www.rfc-editor.org/rfc/rfc8707)) must be this server's URL | [Endpoints](https://frontmcp.dev/reference/auth/local#endpoints), [`/oauth/authorize` parameters](https://frontmcp.dev/reference/auth/local#oauthauthorize-parameters), [Tokens](https://frontmcp.dev/reference/auth/local#tokens) | | `remote` | Resource server and authorization server. Users sign in at your provider, through FrontMCP | The same as `local`, with registration outside production only, for loopback redirect URIs | `S256`, from the client. FrontMCP uses PKCE of its own with your provider | The same as `local`. FrontMCP never asks your provider to check its tokens | [What FrontMCP serves](https://frontmcp.dev/reference/auth/remote#what-frontmcp-serves), [How a sign-in works](https://frontmcp.dev/reference/auth/remote#how-a-sign-in-works) | The specification [requires an MCP server to accept only tokens issued for it](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#token-handling). Tokens from `local` and `remote` mode name the server's address in `aud`, and the server refuses a token whose `aud` is another address, unless `expectedAudience` lists it. In `transparent` mode, set `expectedAudience` to your server's public URL, and `requireAudience: true` so that a token with no `aud` is refused too: by default it's accepted. [Auth in production](https://frontmcp.dev/reference/auth/production#token-checks) lists the checks to tighten. MCP 2026-07-28 [deprecates dynamic client registration](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration#dynamic-client-registration) in favour of Client ID Metadata Documents. In production, registration is off in `remote` mode, and in `local` mode unless you set `dcr.enabled`, so a client your server has never seen signs in with a metadata URL as its `client_id`: see [Client ID metadata (CIMD)](https://frontmcp.dev/reference/auth/cimd#cimd-registration-and-requireregisteredclients). The Playground's client can't sign in, so the tests play a client that has no token yet. They start a server in each mode, send the request a client sends first, and read the documents the `401` points to: Initial call configuration: ```js { tool: "whoami", arguments: {} } ``` ```ts discovery.test.ts active import { test, expect } from "@frontmcp/testing"; import { listTools, request } from "./client"; const transparent = { mode: "transparent", provider: "https://auth.example.com", expectedAudience: "https://desk.example.com" }; const local = { mode: "local" }; const remote = { mode: "remote", provider: "https://auth.example.com", clientId: "help-desk-mcp" }; const withoutOAuth = [{ mode: "public" }, { mode: "static", tokens: ["desk-key-1"] }]; test("a request without a token is refused, and pointed at the Protected Resource Metadata", async () => { for (const auth of [transparent, local]) { const response = await request(auth, "/", listTools); expect(response.status).toBe(401); expect(response.headers.get("www-authenticate")).toContain('resource_metadata="https://desk.example.com/.well-known/oauth-protected-resource"'); } }); test("transparent: a resource server that sends clients to the provider's metadata", async () => { const metadata = await (await request(transparent, "/.well-known/oauth-protected-resource")).json(); expect(metadata).toMatchObject({ resource: "https://desk.example.com", authorization_servers: ["https://auth.example.com"] }); const response = await request(transparent, "/.well-known/oauth-authorization-server"); expect(response.status).toBe(302); expect(response.headers.get("location")).toBe("https://auth.example.com/.well-known/oauth-authorization-server"); }); test("local and remote: the authorization server too, with PKCE, registration and CIMD", async () => { for (const auth of [local, remote]) { const response = await request(auth, "/.well-known/oauth-authorization-server"); expect(response.status).toBe(200); expect(await response.json()).toMatchObject({ issuer: "https://desk.example.com", registration_endpoint: "https://desk.example.com/oauth/register", code_challenge_methods_supported: ["S256"], client_id_metadata_document_supported: true, }); } }); test("public and static: no authorization server", async () => { for (const auth of withoutOAuth) { const metadata = await (await request(auth, "/.well-known/oauth-protected-resource")).json(); expect(metadata).not.toHaveProperty("authorization_servers"); expect((await request(auth, "/.well-known/oauth-authorization-server")).status).toBe(404); } }); ``` ```ts client.ts import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { WhoAmI } from "./whoami.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [WhoAmI] }) class HelpDeskApp {} /** A tools/list request from an MCP 2026-07-28 client, with no Authorization header. */ export const listTools = { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/list" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } } }), }; /** Sends one request to a new server with this auth. */ export async function request(auth: object, path: string, init?: RequestInit) { const handler = await FrontMcpInstance.createFetchHandler({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth }); return handler(new Request(`https://desk.example.com${path}`, init)); } ``` ```ts whoami.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "whoami", description: "Say who the server thinks is calling, and with which scopes.", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class WhoAmI extends ToolContext { async execute() { return { caller: this.auth.user.sub, scopes: this.auth.scopes }; } } ``` Under `createFetchHandler()`, the URLs in these documents start with the address the request was sent to, here `https://desk.example.com`. On FrontMCP's Node server, set `FRONTMCP_PUBLIC_URL` so they name your public address: see [The server's public address](https://frontmcp.dev/reference/auth/modes#the-servers-public-address). ## Choosing a mode | Mode | Who gets in | Who your tools see | Use it when | | --- | --- | --- | --- | | `public` | Everyone | `anon:…`, new on every request, scope `anonymous` | Local development, or only public data | | `static` | Clients that send one of your keys | `static:…`, one id per key | You configure every client yourself: an internal agent, a host's "API key" setting | | `transparent` | Clients with a valid token from your identity provider | The token's `sub`, scopes and claims | Your users already sign in with a provider that issues JWTs | | `local` | Users who sign in on FrontMCP's own page | The signed-in user | There's no identity provider, and each user should have an identity | | `remote` | Users who sign in with an upstream provider, through FrontMCP | The signed-in user | Your provider doesn't work with MCP clients directly, or you want FrontMCP's consent screen | Start with the simplest mode that tells you what your tools need to know. If a tool only needs to know "one of ours", a shared key is enough. If it needs to know which agent is closing a ticket, it needs tokens. ## Recap - Without `auth`, a server is `public`: every request gets in as `anon:…`, with a new id each time under 2026-07-28. - Credentials travel in the `Authorization` header of every request, set by the client. Never take identity from tool arguments. - `static` checks a shared key from `tokens`. Every caller with the same key is the same `static:…` caller. - `transparent` verifies JWTs from `provider`: signature, issuer, expiry and audience, plus `requiredScopes`. `allowAnonymous` lets requests without a token in with `anonymousScopes`. - A refused request gets `401` (or `403` for missing scopes) with a `WWW-Authenticate` header, before any tool runs. The model never sees it. - `local` and `remote` make FrontMCP an OAuth server that signs users in, on its own page or through an upstream provider. - In MCP authorization terms, `transparent` makes FrontMCP a resource server only; `local` and `remote` make it the authorization server too, with its own metadata, registration or CIMD, and PKCE. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Take the author from the credentials `add_note` records who wrote a note from an `author` argument, so the model can sign a note with any name it likes: the call below signs it "Nour". Remove the argument, and record the caller FrontMCP authenticated instead. In the Playground, that's an `anon:` id. Initial call configuration: ```js { tool: "add_note", arguments: { ticket: "T-1", text: "Called the customer back", author: "Nour" } } ``` ```ts add-note.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const notes: { ticket: string; text: string; author: string }[] = []; @Tool({ name: "add_note", description: "Add an internal note to a support ticket.", inputSchema: { ticket: z.string().describe("Ticket id, like T-1"), text: z.string().min(1), author: z.string().describe("Who is writing the note"), }, }) export class AddNote extends ToolContext { async execute({ ticket, text, author }: { ticket: string; text: string; author: string }) { const note = { ticket, text, author }; notes.push(note); return { note }; } } ``` **Solution file (alternative to the starter):** ```ts add-note.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const notes: { ticket: string; text: string; author: string }[] = []; @Tool({ name: "add_note", description: "Add an internal note to a support ticket. The note is signed with the caller's identity.", inputSchema: { ticket: z.string().describe("Ticket id, like T-1"), text: z.string().min(1), }, }) export class AddNote extends ToolContext { async execute({ ticket, text }: { ticket: string; text: string }) { const note = { ticket, text, author: this.auth.user.sub }; notes.push(note); return { note }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts add-note.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`add_note` has no `author` argument", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "add_note"); expect(tool?.inputSchema.properties ?? {}).not.toHaveProperty("author"); }); test("the note is signed with the caller's identity", async ({ mcp }) => { const result = await mcp.tools.call("add_note", { ticket: "T-1", text: "Called the customer back" }); expect(result).toBeSuccessful(); expect(result.json().note.author).toMatch(/^anon:/); }); test("a name in the arguments doesn't change the author", async ({ mcp }) => { const result = await mcp.tools.call("add_note", { ticket: "T-1", text: "Refund approved", author: "Nour" }); expect(result).toBeSuccessful(); expect(result.json().note.author).not.toBe("Nour"); }); ``` **Hint:** `this.auth.user.sub` is the caller FrontMCP authenticated from the request's header. **Solution:** With `author` gone from `inputSchema`, the model has no way to name an author, and FrontMCP drops an `author` argument if one is sent anyway. The author now comes from `this.auth.user.sub`: `anon:…` here, `static:…` with a shared key, or the token's `sub` behind an identity provider. Only the credentials in the header decide it. ### Challenge: Let anonymous callers read The help desk wants signed-in agents to use tokens from `https://auth.example.com`, and everyone else to be able to search tickets without signing in. `search_tickets` already requires the `tickets:read` scope, and `close_ticket` requires `tickets:write`. Don't change the tools: change the server's `auth` so that requests without a token get in with `tickets:read`, and nothing more. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { CloseTicket, SearchTickets } from "./tickets.tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, CloseTicket] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "public" }, }) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { App, FrontMcp } from "@frontmcp/sdk"; import { CloseTicket, SearchTickets } from "./tickets.tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, CloseTicket] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "transparent", provider: "https://auth.example.com", allowAnonymous: true, anonymousScopes: ["tickets:read"], }, }) export default class Server {} ``` ```ts tickets.tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "open" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title. Needs the tickets:read scope.", inputSchema: { query: z.string().min(1) }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { if (!this.auth.hasScope("tickets:read")) { this.fail(new PublicMcpError("Searching tickets needs the tickets:read scope.", "FORBIDDEN")); } const q = query.toLowerCase(); return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(q)) }; } } @Tool({ name: "close_ticket", description: "Close a support ticket. Needs the tickets:write scope, which signed-in agents have.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { if (!this.auth.hasScope("tickets:write")) { this.fail(new PublicMcpError("Closing tickets needs the tickets:write scope. Ask the user to sign in as an agent.", "FORBIDDEN")); } const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "closed"; return { id, closed: true }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts auth.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("anyone can search without a token", async ({ mcp }) => { const result = await mcp.tools.call("search_tickets", { query: "log" }); expect(result).toBeSuccessful(); expect(result.json().tickets.map((t: { id: string }) => t.id)).toEqual(["T-1", "T-3"]); }); test("anonymous callers still can't close tickets", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("FORBIDDEN"); }); ``` **Hint:** Public mode can give anonymous callers `tickets:read` with `anonymousScopes`, but it refuses the agents' tokens: it only accepts tokens it issued itself. The mode that checks tokens from a provider can also let requests without a token in, with the scopes you choose. **Solution:** `mode: "transparent"` with `provider` checks agents' tokens against `https://auth.example.com`. `allowAnonymous: true` lets requests without a token in, and `anonymousScopes: ["tickets:read"]` gives them exactly the scope `search_tickets` needs and not the one `close_ticket` needs. Public mode with `anonymousScopes: ["tickets:read"]` passes these checks too, but it refuses every JWT it didn't sign, so the agents couldn't use their tokens. --- # Deciding Who Can Call What > How a FrontMCP tool finds out who is calling, refuses calls it shouldn't make with an error the model can act on, and declares who may use it with authorities. Source: https://frontmcp.dev/learn/authorizing-calls [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 [Authentication](https://frontmcp.dev/learn/authenticating-clients) tells your server who is calling. Authorization decides what they may do: anyone may search tickets, only support agents may close them, only admins may delete them. FrontMCP gives you two places to decide. A tool can check the caller inside `execute()`, and a tool can declare who may use it with `authorities`, so FrontMCP refuses the call, and hides the tool, before your code runs. **You will learn** - How to read who is calling inside `execute()` - How to refuse a call with an error the model can act on - How to declare who may call a tool with `authorities` - How to hide tools from callers who can't use them - Why `visibility: "hidden"` doesn't protect a tool ## A tool anyone can call This `close_ticket` does its job. But in the Playground you're an anonymous caller, and it closed the ticket anyway: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "open" }], ]); @Tool({ name: "close_ticket", description: "Close a support ticket.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "closed"; return { id, closed: true }; } } ``` Putting the server behind [a shared key or an identity provider](https://frontmcp.dev/learn/authenticating-clients) keeps strangers out, but everyone who gets in can still call every tool. A customer who signs in to check on their own ticket could close anyone's. The tool has to know who is calling, and decide. ## Reading who's calling Inside `execute()`, `this.auth` describes the caller FrontMCP authenticated for this request: Initial call configuration: ```js { tool: "whoami", arguments: {} } ``` ```ts whoami.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "whoami", description: "Say who the server thinks is calling.", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class WhoAmI extends ToolContext { async execute() { const { user, isAnonymous, scopes, roles } = this.auth; return { caller: user.sub, anonymous: isAnonymous, scopes, roles }; } } ``` ```ts whoami.test.ts import { test, expect } from "@frontmcp/testing"; import { create } from "@frontmcp/sdk"; import { WhoAmI } from "./whoami.tool"; test("the Playground's caller is anonymous", async ({ mcp }) => { const me = (await mcp.tools.call("whoami", {})).json(); expect(me).toMatchObject({ caller: expect.stringMatching(/^anon:/), anonymous: true, scopes: ["anonymous"], roles: [] }); }); test("a signed-in agent has their id and roles", async () => { // create() runs the tool in-process, as the user you name, with the claims you give it. const server = await create({ info: { name: "help-desk", version: "1.0.0" }, tools: [WhoAmI] }); const result = await server.callTool("whoami", {}, { authContext: { user: { sub: "nour", roles: ["agent"] } } }); await server.dispose(); expect(result.structuredContent).toMatchObject({ caller: "nour", anonymous: false, roles: ["agent"] }); }); ``` What each field holds depends on the server's [auth mode](https://frontmcp.dev/learn/authenticating-clients#choosing-a-mode): | Field | `public` | `static` | `transparent`, with a token | | --- | --- | --- | --- | | `user.sub` | `anon:` and a new id per request | `static:` and 12 hex characters | The token's `sub` | | `isAnonymous` | `true` | `false` | `false` | | `scopes` | The mode's `anonymousScopes`, `["anonymous"]` by default | The mode's `scopes`, `["static"]` by default | The token's `scope` claim, split on spaces, or its `scp` claim | | `roles` | `[]` | `[]` | The token's `roles` claim | | `claims` | `{ sub, iss: "public", name: "Anonymous", scope }` | `{ sub, iss: "static", name: "Static token", scope }` | Every claim in the token, such as `name` or `roles` | `hasScope()`, `hasRole()` and `hasPermission()` check those lists for you. `claims` holds what the token said, and nothing else: FrontMCP verified the token's signature, but a `roles` claim means what your identity provider meant by it. If your provider keeps roles in another claim, the `claimsMapping` [further down](https://frontmcp.dev/learn/authorizing-calls#declaring-who-may-call-a-tool) tells `this.auth` where to look. `this.auth` is built from `this.context.authInfo`, the raw result of authentication: `clientId`, `scopes`, the token's claims in `user`, and `token`, the token itself. It's the same for every client, whatever MCP version it speaks. (Before 1.8.7, a client that kept a session, which means every version before 2026-07-28, saw `this.auth.scopes` empty and `hasScope()` always `false`, and a tool had to read `this.context.authInfo.scopes`.) ## Refusing a call the model can act on When the caller isn't allowed to do something, stop with `this.fail()` and a `PublicMcpError` whose message tells the model what happened and what to do instead. Support agents sign in with tokens that carry the `tickets:write` scope; nobody else has it: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "open" }], ]); @Tool({ name: "close_ticket", description: "Close a support ticket. Only signed-in support agents can close tickets.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { if (!this.auth.hasScope("tickets:write")) { this.fail( new PublicMcpError( "Only signed-in support agents can close tickets. Tell the user to sign in as an agent. Don't retry this call until they have.", "FORBIDDEN", ), ); } const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "closed"; return { id, closed: true }; } } ``` The result is an ordinary tool error, with `isError: true`. Three details make it useful: 1. **The message is written for the model.** It says what the rule is and what to do next. "Forbidden" alone would leave the model guessing, and likely retrying. 2. **`PublicMcpError` keeps it readable in production.** The message reaches the model word for word. A plain `Error` would become "Internal FrontMCP error" with an error ID. 3. **The second argument is a code.** It arrives as `_meta.code: "FORBIDDEN"`, so a client or a test can tell a refusal from other failures without parsing the text. (There's also a third argument, an HTTP status, but a tool error always goes out with HTTP `200`.) Check before you change anything, so a refused call has no effects. And put the rule in the description too ("Only signed-in support agents can close tickets"), so a model can tell the user before it tries. ## Declaring who may call a tool A check in `execute()` only runs once the tool is called. The tool is still listed for everyone, and in a server with many tools it's easy to forget the check in one of them. `authorities` puts the rule on the tool itself. FrontMCP checks it before `execute()` runs, and leaves the tool out of `tools/list` for callers who wouldn't pass. Rules are usually named once, as profiles, in `@FrontMcp`: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { CloseTicket, DeleteTicket, SearchTickets } from "./tickets.tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, CloseTicket, DeleteTicket] }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], authorities: { // Where to find the caller's roles: the token's `roles` claim. claimsMapping: { roles: "roles" }, profiles: { agent: { roles: { any: ["agent", "admin"] } }, admin: { roles: { any: ["admin"] } }, }, }, }; @FrontMcp(config) export default class Server {} ``` ```ts tickets.tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "open" }], ]); @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string().min(1) }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { const q = query.toLowerCase(); return { tickets: [...tickets.values()].filter((t) => t.title.toLowerCase().includes(q)) }; } } @Tool({ name: "close_ticket", description: "Close a support ticket.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, authorities: "agent", }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "closed"; return { id, closed: true }; } } @Tool({ name: "delete_ticket", description: "Delete a support ticket for good.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, authorities: "admin", }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } ``` ```ts authorities.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; test("an anonymous caller only sees search_tickets", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).toEqual(["search_tickets"]); }); test("calling close_ticket by name is refused before execute() runs", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("AUTHORITY_DENIED"); const found = await mcp.tools.call("search_tickets", { query: "log in" }); expect(found.json().tickets[0]).toMatchObject({ id: "T-1", status: "open" }); }); test("an agent sees close_ticket and can call it", async () => { // createDirect() runs the server in-process, as the user you name. const server = await FrontMcpInstance.createDirect(config); const asNour = { authContext: { user: { sub: "nour", roles: ["agent"] } } }; const { tools } = await server.listTools(asNour); const result = await server.callTool("close_ticket", { id: "T-2" }, asNour); await server.dispose(); expect(tools.map((t) => t.name).sort()).toEqual(["close_ticket", "search_tickets"]); expect(result.structuredContent).toEqual({ id: "T-2", closed: true }); }); ``` Open the **Capabilities** tab: an anonymous caller has no roles, so only `search_tickets` is listed. Calling `close_ticket` by name is refused anyway. The last test calls the server in-process as the agent `nour`, whose claims include `roles: ["agent"]`: `close_ticket` appears and works, and `delete_ticket` stays hidden. [Running FrontMCP Anywhere](https://frontmcp.dev/learn/running-frontmcp-anywhere) covers `createDirect()`. The pieces: - **`authorities` on a tool** names the rule: a profile like `"agent"`, a list of profiles that must all pass, like `["agent", "billing"]`, or a rule written in place. - **`profiles` in `@FrontMcp({ authorities })`** names reusable rules. `roles: { any: [...] }` passes if the caller has at least one of the roles; `all` requires every one. - **`claimsMapping`** tells FrontMCP where the caller's roles are in the token's claims. `roles: "roles"` reads the `roles` claim, and a path like `"realm_access.roles"` reads a nested one. `permissions` works the same way, and `this.auth.roles` follows the same mapping. When roles have to be worked out rather than read, `claimsResolver` takes a function instead, which gets `this.context.authInfo` and returns `{ roles, permissions, claims }`; rules and `this.auth` both use what it returns. A tool with `authorities` on a server without an `authorities` option doesn't start: FrontMCP refuses, rather than leave the tool open by accident. Rules can check more than roles: | Rule | Passes when | | --- | --- | | `{ roles: { any: ["agent"] } }` | The caller has at least one of the roles. `all` requires all of them. | | `{ permissions: { all: ["tickets:export"] } }` | The caller has every permission. `any` requires one. | | `{ attributes: { conditions: [{ path: "input.id", op: "startsWith", value: "T-" }] } }` | Each condition holds. Paths start with `user.`, `claims.`, `input.` (the call's arguments) or `env.` (the server's environment variables). | | `{ guards: [(ctx) => ...] }` | Every function returns `true`. Anything else refuses, `undefined` included, and a string becomes the reason. | | `{ anyOf: [ruleA, ruleB] }` | At least one of the rules passes. `allOf` and `not` also exist. | [Authorities](https://frontmcp.dev/reference/auth/authorities) has every rule form and operator, and the settings that look like they protect a tool but don't. > **Pitfall: An authorities refusal is written for developers** > > When `authorities` refuses a call, the result has `_meta.code: "AUTHORITY_DENIED"`, so a client or a test can tell it from other failures. Its text, in production too, is the rule that failed: `Access denied to Tool "help-desk:close_ticket": profile:agent: roles.any: user has none of 'agent', 'admin'`. That tells the model the call was refused, but not what to do next, and it tells the caller which roles would have let them in. Since the tool isn't in the caller's `tools/list`, a model rarely calls it. When a caller can see a tool but may not be allowed to use it on some tickets, check in `execute()` and fail with a message, as in the previous section. You can't add a friendlier message to an `authorities` refusal from `execute()`: for a refused call, `execute()` never runs. ### Scopes as permissions Roles are one way to describe callers. Scopes are another: a token for a support agent carries `tickets:write`, and an anonymous caller in [transparent mode](https://frontmcp.dev/learn/authenticating-clients#letting-anonymous-callers-in-with-less) gets the `anonymousScopes` you set. Point `claimsMapping.permissions` at the `scope` claim, and FrontMCP splits it on spaces into permissions that rules can require: ```ts main.ts @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "transparent", provider: "https://auth.example.com", allowAnonymous: true, anonymousScopes: ["tickets:read"], }, authorities: { claimsMapping: { roles: "roles", permissions: "scope" }, profiles: { reader: { permissions: { all: ["tickets:read"] } } }, }, }) export default class Server {} ``` The last challenge on this page uses this setup. > **Note** > > A rule that reads `input.` can only be checked when there's a call. `tools/list` has no arguments to check it against, so FrontMCP counts the rule as failed there, and the tool disappears from `tools/list` for every caller, including the ones who could call it. ## Hiding a tool isn't protecting it `visibility: "hidden"` looks like a way to keep a tool away from callers. It isn't: ```ts purge.tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "purge_closed_tickets", description: "Delete every closed ticket.", inputSchema: {}, annotations: { destructiveHint: true }, visibility: "hidden", }) export class PurgeClosedTickets extends ToolContext { async execute() { return { purged: 12 }; } } @Tool({ name: "rebuild_search_index", description: "Rebuild the ticket search index.", inputSchema: {}, visibility: "internal", }) export class RebuildSearchIndex extends ToolContext { async execute() { return { rebuilt: true }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in" }; } } ``` ```ts visibility.test.ts import { test, expect } from "@frontmcp/testing"; test("neither tool is listed", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).toEqual(["get_ticket"]); }); test("a hidden tool still runs for anyone who knows its name", async ({ mcp }) => { const result = await mcp.tools.call("purge_closed_tickets", {}); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ purged: 12 }); }); test("an internal tool can't be called by clients", async ({ mcp }) => { const result = await mcp.tools.call("rebuild_search_index", {}); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("TOOL_NOT_FOUND"); }); ``` Both tools are missing from the Capabilities tab, but the **Tests** tab shows the difference. Anyone who knows the name of a hidden tool can call it, and names aren't secrets: they're in your code, your docs and old conversations. Hidden is for tools the model doesn't need to see, such as one your own client code calls by name; it keeps them out of the list, nothing more. An internal tool isn't reachable by clients at all; a call gets `Tool "rebuild_search_index" not found`. | | In `tools/list` | Callable by clients | | --- | --- | --- | | No option (`visibility: "public"`) | Yes | Yes | | `visibility: "hidden"` | No, for everyone | Yes, by anyone who knows the name | | `visibility: "internal"` | No | No | | `authorities: …` | Only for callers the rule lets through | Only by callers the rule lets through | To keep a tool from a caller, use `authorities` or a check in `execute()`. Visibility only decides what a list shows. ## Recap - `this.auth` holds the caller: `user.sub`, `isAnonymous`, `scopes`, `roles` and the token's `claims`, with checks like `hasScope()` and `hasRole()`. - To refuse a call, `this.fail(new PublicMcpError(message, "FORBIDDEN"))` before changing anything, with a message that tells the model what to do next. - `authorities` on a tool, with profiles and a `claimsMapping` in `@FrontMcp({ authorities })`, refuses calls before `execute()` and hides the tool from callers who can't use it. - An `authorities` refusal has the code `AUTHORITY_DENIED` and a message written for developers, so use `execute()` checks where the model needs an explanation. - `visibility: "hidden"` only hides a tool from `tools/list`; anyone can still call it. `internal` tools can't be called by clients. - Every property and method of `this.auth`, per auth mode and entry point, is in the [`this.auth` reference](https://frontmcp.dev/reference/sdk/auth). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Refuse anonymous callers `reopen_ticket` reopens a closed ticket for anyone. Make it refuse anonymous callers with a tool error whose code is `FORBIDDEN` and whose message tells the model to ask the user to sign in. A refused call must leave the ticket closed. Initial call configuration: ```js { tool: "reopen_ticket", arguments: { id: "T-2" } } ``` ```ts tickets.tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ]); @Tool({ name: "get_ticket", description: "Get one support ticket by id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } @Tool({ name: "reopen_ticket", description: "Reopen a closed support ticket.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class ReopenTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "open"; return { id, reopened: true }; } } ``` **Solution file (alternative to the starter):** ```ts tickets.tools.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ]); @Tool({ name: "get_ticket", description: "Get one support ticket by id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } @Tool({ name: "reopen_ticket", description: "Reopen a closed support ticket. Only signed-in users can reopen tickets.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class ReopenTicket extends ToolContext { async execute({ id }: { id: string }) { if (this.auth.isAnonymous) { this.fail(new PublicMcpError("Only signed-in users can reopen tickets. Ask the user to sign in, then try again.", "FORBIDDEN")); } const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "open"; return { id, reopened: true }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts reopen.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("an anonymous call is refused with code `FORBIDDEN`", async ({ mcp }) => { const result = await mcp.tools.call("reopen_ticket", { id: "T-2" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("FORBIDDEN"); }); test("the message tells the model to have the user sign in", async ({ mcp }) => { const result = await mcp.tools.call("reopen_ticket", { id: "T-2" }); expect(result.text()).toMatch(/sign in/i); }); test("a refused call leaves the ticket closed", async ({ mcp }) => { await mcp.tools.call("reopen_ticket", { id: "T-2" }); const ticket = await mcp.tools.call("get_ticket", { id: "T-2" }); expect(ticket.json().status).toBe("closed"); }); ``` **Hint:** `this.auth.isAnonymous` is `true` for a caller without credentials. Check it before you touch the ticket. **Solution:** The check comes first, so a refused call changes nothing, and `this.fail()` with a `PublicMcpError` sends the message word for word with `_meta.code: "FORBIDDEN"`. The description now states the rule too, so a model can mention it before calling. With a shared key or a token, `isAnonymous` would be `false`, and the call would go through. ### Challenge: Really keep the delete tool from callers Someone hid `delete_ticket` with `visibility: "hidden"`, but anyone who knows its name can still delete tickets. The server already has an `admin` profile. Make `delete_ticket` both invisible to and uncallable by anyone who isn't an admin. Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts delete-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, visibility: "hidden", }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } ``` **Solution file (alternative to the starter):** ```ts delete-ticket.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good. Admins only.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, authorities: "admin", }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { DeleteTicket } from "./delete-ticket.tool"; import { GetTicket } from "./get-ticket.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, DeleteTicket] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], authorities: { claimsMapping: { roles: "roles" }, profiles: { admin: { roles: { any: ["admin"] } } }, }, }) export default class Server {} ``` ```ts get-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "get_ticket", description: "Get one support ticket by id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ]); ``` **Hidden fixture/test file (runs with the example):** ```ts delete.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`delete_ticket` isn't listed for an anonymous caller", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).not.toContain("delete_ticket"); }); test("calling `delete_ticket` by name is refused", async ({ mcp }) => { const result = await mcp.tools.call("delete_ticket", { id: "T-1" }); expect(result).toBeError(); }); test("the ticket is still there afterwards", async ({ mcp }) => { await mcp.tools.call("delete_ticket", { id: "T-1" }); expect(await mcp.tools.call("get_ticket", { id: "T-1" })).toBeSuccessful(); }); ``` **Hint:** `visibility` only changes what `tools/list` shows. The option that checks the caller on every call names a profile. **Solution:** `authorities: "admin"` makes FrontMCP check the `admin` profile on every call, before `execute()` runs, and leave the tool out of `tools/list` for callers who fail it. `visibility: "hidden"` has to go too: with it, the tool would be hidden even from admins. The description says "Admins only", for the admins who do see it. ### Challenge: Require a scope to export Anonymous callers on this server get the scope `tickets:read`, and `main.ts` turns scopes into permissions. `search_tickets` requires `tickets:read`. Make `export_tickets` require the permission `tickets:export`, so that anonymous callers can neither see nor call it. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts tickets.tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string().min(1) }, authorities: "reader", }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { const q = query.toLowerCase(); return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(q)) }; } } @Tool({ name: "export_tickets", description: "Export every support ticket, with customer details, as CSV.", inputSchema: {}, }) export class ExportTickets extends ToolContext { async execute() { return { csv: ["id,title,status", ...tickets.map((t) => `${t.id},${t.title},${t.status}`)].join("\n") }; } } ``` **Solution file (alternative to the starter):** ```ts tickets.tools.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string().min(1) }, authorities: "reader", }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { const q = query.toLowerCase(); return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(q)) }; } } @Tool({ name: "export_tickets", description: "Export every support ticket, with customer details, as CSV. Needs the tickets:export scope.", inputSchema: {}, authorities: { permissions: { all: ["tickets:export"] } }, }) export class ExportTickets extends ToolContext { async execute() { return { csv: ["id,title,status", ...tickets.map((t) => `${t.id},${t.title},${t.status}`)].join("\n") }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { ExportTickets, SearchTickets } from "./tickets.tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, ExportTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "transparent", provider: "https://auth.example.com", allowAnonymous: true, anonymousScopes: ["tickets:read"], }, authorities: { claimsMapping: { roles: "roles", permissions: "scope" }, profiles: { reader: { permissions: { all: ["tickets:read"] } } }, }, }) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts export.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("anonymous callers don't see `export_tickets`", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).not.toContain("export_tickets"); }); test("calling `export_tickets` by name is refused", async ({ mcp }) => { expect(await mcp.tools.call("export_tickets", {})).toBeError(); }); test("anonymous callers can still search", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).toContain("search_tickets"); const result = await mcp.tools.call("search_tickets", { query: "log" }); expect(result).toBeSuccessful(); expect(result.json().tickets).toHaveLength(2); }); ``` **Hint:** `search_tickets` uses a profile from `main.ts`. For one tool, you can also write the rule in place: `{ permissions: { all: [...] } }`. **Solution:** `authorities: { permissions: { all: ["tickets:export"] } }` requires the permission that `main.ts` builds from a `tickets:export` scope. Anonymous callers only have `tickets:read`, so FrontMCP leaves the tool out of their `tools/list` and refuses it by name. An agent whose token has `scope: "tickets:read tickets:export"` sees and calls both tools. If more tools need the same rule, name it as a profile next to `reader`. --- # Limiting and Timing Out Calls > How to cap how often a FrontMCP tool runs, how many copies run at once, and how long a call may take, with rateLimit, concurrency and timeout, and what callers get back when a limit trips. Source: https://frontmcp.dev/learn/limiting-calls [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A model can call a tool as often as it likes, and nothing in MCP stops it from calling one in a loop. For most tools that's fine. For an export that reads the whole database, a merge that must never run twice at once, or a lookup that can hang on a slow service, it isn't. Three of FrontMCP's `@Tool` options set limits: `rateLimit` caps how often a tool runs, `concurrency` caps how many calls run at once, and `timeout` caps how long one call may take. **You will learn** - How to cap how often a tool runs, and what a caller gets back when a limit trips - Whose calls a limit counts, and what anonymous callers share - How to stop two runs of a tool overlapping - What a timeout stops, and how to let the work stop with it - How to choose limits for expensive and destructive tools ## Capping how often a tool runs Exporting tickets reads every ticket in the database. The help desk wants at most two exports an hour, so the tool sets `rateLimit`. Open the **Tests** tab: Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts export-tickets.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "export_tickets", description: "Export every support ticket as CSV. Reads the whole ticket database, so at most 2 exports an hour.", inputSchema: {}, annotations: { readOnlyHint: true }, rateLimit: { maxRequests: 2, windowMs: 60 * 60_000 }, }) export class ExportTickets extends ToolContext { async execute() { const rows = tickets.map((t) => `${t.id},${t.title},${t.status}`); return { csv: ["id,title,status", ...rows].join("\n") }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { ExportTickets } from "./export-tickets.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [ExportTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; ``` ```ts limit.test.ts import { test, expect } from "@frontmcp/testing"; test("the third export in an hour is refused", async ({ mcp }) => { expect(await mcp.tools.call("export_tickets", {})).toBeSuccessful(); expect(await mcp.tools.call("export_tickets", {})).toBeSuccessful(); const third = await mcp.tools.call("export_tickets", {}); expect(third).toBeError(); expect(third.raw._meta?.code).toBe("RATE_LIMIT_EXCEEDED"); expect(third.text()).toMatch(/^Rate limit exceeded\. Retry after \d+ seconds$/); }); ``` The export above ran once when the example started. Press **Call** in the Call tab twice more: the second call works, the third is refused. `rateLimit` takes: | Field | Default | Meaning | | --- | --- | --- | | `maxRequests` | required | How many calls a window allows. | | `windowMs` | `60_000` | The window's length, in milliseconds. | | `partitionBy` | `"global"` | Whose calls share a count. See [below](https://frontmcp.dev/learn/limiting-calls#whose-calls-a-limit-counts). | ## What the caller gets back A call over the limit doesn't reach `execute()`. The client gets an ordinary tool error: ```json { "content": [{ "type": "text", "text": "Rate limit exceeded. Retry after 2274 seconds" }], "isError": true, "_meta": { "errorId": "err_…", "code": "RATE_LIMIT_EXCEEDED" } } ``` - **The retry hint is in the text, for the model.** The HTTP status is still `200` and there's no `Retry-After` header, so the model is the one that reads when to try again. The message survives in production too. - **The wait is until the window ends.** Windows line up with the clock, not with the first call: an hour-long window runs from one full hour (in UTC) to the next, and a minute-long one from one full minute to the next. The number is the time left in the current window, so it can be anything from a second up to the whole `windowMs`. Refused at 10:40 UTC by an hourly limit, a caller is told to retry in about 1200 seconds. Say the limit in the description as well, as `export_tickets` does ("at most 2 exports an hour"). A model that knows the rule can plan around it, or tell the user, instead of finding out from an error. ## Whose calls a limit counts `partitionBy` decides which calls share a count: | `partitionBy` | One count per | Under MCP 2026-07-28 | | --- | --- | --- | | `"global"` | The whole server | Every caller shares one limit. | | `"userId"` | Signed-in caller, by `authInfo.clientId` | Each caller with a key or token has a count of their own. All anonymous callers share one. | | `"ip"` | Client IP address | Works on a real server. The Playground has no IP, so there it behaves like `"userId"`. | | `"session"` | MCP session | There are no sessions, so it behaves like `"userId"`. | | `(ctx) => string` | Whatever key you return | `ctx` has `sessionId`, plus `userId` for a signed-in caller and `clientIp` when there is one. | `"userId"` is the natural choice for "two exports per person", and for signed-in callers it does exactly that. Anonymous callers have no user id, so they all share one count: Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts export-tickets.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "export_tickets", description: "Export every support ticket as CSV. At most 2 exports an hour per signed-in caller, and 2 an hour for all anonymous callers together.", inputSchema: {}, annotations: { readOnlyHint: true }, rateLimit: { maxRequests: 2, windowMs: 60 * 60_000, partitionBy: "userId" }, }) export class ExportTickets extends ToolContext { async execute() { return { csv: "id,title,status\nT-1,Cannot log in,open" }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { ExportTickets } from "./export-tickets.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [ExportTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts limit.test.ts import { test, expect } from "@frontmcp/testing"; test("anonymous callers share one count", async ({ mcp }) => { expect(await mcp.tools.call("export_tickets", {})).toBeSuccessful(); expect(await mcp.tools.call("export_tickets", {})).toBeSuccessful(); const third = await mcp.tools.call("export_tickets", {}); expect(third.raw._meta?.code).toBe("RATE_LIMIT_EXCEEDED"); }); ``` Each of these calls arrives as a [new anonymous caller](https://frontmcp.dev/learn/authenticating-clients#a-server-anyone-can-call) with a new id, but FrontMCP doesn't count anonymous callers by those ids, so the third one is refused like the third call from a single person. That's the safe choice: nobody gets around a limit by not signing in. It also means one busy anonymous client can use up the exports for every other anonymous client. If that matters, have callers sign in, so each gets a count of their own, or, on a real server, count anonymous callers by address with a function: `partitionBy: (ctx) => ctx.userId ?? ctx.clientIp ?? "anonymous"`. Counts are kept in the server's memory unless you say otherwise, so each instance of a server counts on its own: two instances behind a load balancer let through four exports an hour, not two. With `throttle.storage` on one Redis, the instances share a count: five exports sent to two instances in turn let two through. [Running Several Instances](https://frontmcp.dev/learn/running-several-instances#what-else-lives-in-one-instances-memory) sets that up. If that Redis can't be reached, a production server doesn't start, unless `throttle.storage` has `fallback: "memory"`, which starts it with each instance counting on its own. When Redis goes away while the server runs, a call to a tool with a limit fails with `GUARD_STORAGE_UNAVAILABLE`, or, with the fallback, is counted in the instance's memory until Redis answers again: [the guard reference](https://frontmcp.dev/reference/sdk/guard#calls-fail-with-guard_storage_unavailable-while-the-server-runs) shows what a caller gets, and [what happens at startup](https://frontmcp.dev/reference/sdk/guard#the-server-doesnt-start-throttlestorage-redis-is-unavailable). ## One at a time Merging two customer records moves all their tickets from one record to the other. Two merges running at once can move the same tickets twice. `concurrency` caps how many calls of a tool run at the same moment: Initial call configuration: ```js { tool: "merge_customers", arguments: { from: "C-7", into: "C-2" } } ``` ```ts merge-customers.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; export const merges: string[] = []; @Tool({ name: "merge_customers", description: "Merge one customer record into another, moving all its tickets. One merge runs at a time; if another is running, wait a minute and try again.", inputSchema: { from: z.string().describe("Customer to merge away, like C-7"), into: z.string().describe("Customer to keep") }, annotations: { destructiveHint: true }, concurrency: { maxConcurrent: 1 }, }) export class MergeCustomers extends ToolContext { async execute({ from, into }: { from: string; into: string }) { await new Promise((resolve) => setTimeout(resolve, 300)); // moving tickets takes a while merges.push(`${from} → ${into}`); return { merged: from, into }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { MergeCustomers } from "./merge-customers.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [MergeCustomers] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts merge.test.ts import { test, expect } from "@frontmcp/testing"; test("a second merge while one is running is refused", async ({ mcp }) => { const [first, second] = await Promise.all([ mcp.tools.call("merge_customers", { from: "C-7", into: "C-2" }), mcp.tools.call("merge_customers", { from: "C-8", into: "C-2" }), ]); expect(first).toBeSuccessful(); expect(second).toBeError(); expect(second.raw._meta?.code).toBe("CONCURRENCY_LIMIT"); expect(second.text()).toBe('Concurrency limit reached for "merge_customers" (max: 1)'); }); test("once it's done, the next merge runs", async ({ mcp }) => { expect(await mcp.tools.call("merge_customers", { from: "C-8", into: "C-2" })).toBeSuccessful(); }); ``` The slot is taken when a call starts and given back when its `execute()` ends, whether it succeeded or failed. `concurrency` takes `maxConcurrent`, `partitionBy` (the same choices as for `rateLimit`, `"global"` by default), and `queueTimeoutMs`. By default, a call that finds no free slot is refused at once. With a queue, it waits for a slot, and is only refused if none frees up in time: ```ts concurrency: { maxConcurrent: 1, queueTimeoutMs: 5_000 }, ``` A queued call that runs out of time gets `Queue timeout for "merge_customers" after waiting 5000ms for a concurrency slot`. For a tool a model is likely to call twice in a row, a short queue is kinder than a refusal. Every limit answers the same way: an `isError` tool result, over HTTP `200`, with a code of its own in `_meta.code` and a message that is kept in production too: | Limit | `_meta.code` | Message | | --- | --- | --- | | `rateLimit` | `RATE_LIMIT_EXCEEDED` | `Rate limit exceeded. Retry after 1200 seconds` | | `concurrency` | `CONCURRENCY_LIMIT` | `Concurrency limit reached for "merge_customers" (max: 1)` | | `concurrency` with a queue | `QUEUE_TIMEOUT` | `Queue timeout for "merge_customers" after waiting 5000ms for a concurrency slot` | | `timeout` | `EXECUTION_TIMEOUT` | `Execution of "lookup_customer" timed out after 500ms` | So the model can tell "busy, try again soon" from "broken". It still helps to put the rule in the tool's description, as `merge_customers` does, so the model knows what to do about it. ## Deadlines A tool that calls another service waits as long as that service takes. `timeout: { executeMs }` puts a limit on it. Customer `C-9` sends the CRM into a slow path: Initial call configuration: ```js { tool: "lookup_customer", arguments: { id: "C-9" } } ``` ```ts lookup-customer.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; // Stands in for a CRM that is sometimes very slow to answer. async function crmLookup(id: string) { await new Promise((resolve) => setTimeout(resolve, id === "C-9" ? 2_000 : 50)); return { id, name: id === "C-9" ? "Globex" : "Initech", plan: "business" }; } @Tool({ name: "lookup_customer", description: "Look up a customer in the CRM by id. Gives up after half a second if the CRM is slow.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, timeout: { executeMs: 500 }, }) export class LookupCustomer extends ToolContext { async execute({ id }: { id: string }) { return crmLookup(id); } } ``` ```ts lookup.test.ts import { test, expect } from "@frontmcp/testing"; test("a slow lookup fails after half a second", async ({ mcp }) => { const result = await mcp.tools.call("lookup_customer", { id: "C-9" }); expect(result.raw._meta?.code).toBe("EXECUTION_TIMEOUT"); expect(result.durationMs).toBeLessThan(1_000); }); test("a fast one answers", async ({ mcp }) => { expect(await mcp.tools.call("lookup_customer", { id: "C-1" })).toBeSuccessful(); }); ``` After half a second the call fails with `Execution of "lookup_customer" timed out after 500ms`. Try `C-1`: it answers in time. ## A timeout ends the call, not the work When a call times out, FrontMCP stops waiting for `execute()` and answers the client. `execute()` itself carries on unless it's written to stop (the [next section](https://frontmcp.dev/learn/limiting-calls#stopping-the-work) shows how), side effects and all. Its `concurrency` slot stays taken until it really ends, so runs never overlap, and a call that arrives in the meantime is refused: ```ts merge-customers.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; const merges: string[] = []; let running = 0; let mostAtOnce = 0; @Tool({ name: "merge_customers", description: "Merge one customer record into another, moving all its tickets. One merge runs at a time.", inputSchema: { from: z.string(), into: z.string() }, annotations: { destructiveHint: true }, concurrency: { maxConcurrent: 1 }, timeout: { executeMs: 200 }, }) export class MergeCustomers extends ToolContext { async execute({ from, into }: { from: string; into: string }) { running++; mostAtOnce = Math.max(mostAtOnce, running); await new Promise((resolve) => setTimeout(resolve, 500)); // takes longer than the timeout merges.push(`${from} → ${into}`); running--; return { merged: from, into }; } } @Tool({ name: "merge_log", description: "List finished merges.", inputSchema: {} }) export class MergeLog extends ToolContext { async execute() { return { merges, mostAtOnce }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { MergeCustomers, MergeLog } from "./merge-customers.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [MergeCustomers, MergeLog] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts timeout.test.ts import { test, expect } from "@frontmcp/testing"; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("the merge still happens after its call times out", async ({ mcp }) => { const result = await mcp.tools.call("merge_customers", { from: "C-7", into: "C-2" }); expect(result.raw._meta?.code).toBe("EXECUTION_TIMEOUT"); await wait(500); const log = (await mcp.tools.call("merge_log", {})).json(); expect(log.merges).toContain("C-7 → C-2"); }); test("a merge sent while a timed-out one is still running is refused", async ({ mcp }) => { await mcp.tools.call("merge_customers", { from: "C-8", into: "C-2" }); // times out, keeps running const second = await mcp.tools.call("merge_customers", { from: "C-9", into: "C-2" }); expect(second.raw._meta?.code).toBe("CONCURRENCY_LIMIT"); await wait(600); const log = (await mcp.tools.call("merge_log", {})).json(); expect(log.merges).toContain("C-8 → C-2"); expect(log.merges).not.toContain("C-9 → C-2"); expect(log.mostAtOnce).toBe(1); }); ``` For a tool that changes things, a timeout shorter than the work is worse than none. The model is told the merge failed while it's still going, then that merges are busy, and it may well run the same merge again once the first one is done. Give such tools no timeout, or one comfortably longer than the work can take, and make them safe to repeat, for example by checking whether the merge already happened before starting it. ## Stopping the work A timeout also aborts `this.signal`, the call's [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). Work that listens to it stops with the call. `fetch()` and most clients for databases and other services take a `signal` option, and a loop can call `this.signal?.throwIfAborted()` between steps. (The type says `signal` may be missing, hence the `?.`.) This export reads the ticket database a page at a time, and a slow database makes it take longer than its timeout: Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts export-tickets.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; export const pagesRead: number[] = []; export const stops: string[] = []; // Stands in for a slow database: 10 pages, a tenth of a second each. async function readPage(page: number) { await new Promise((resolve) => setTimeout(resolve, 100)); pagesRead.push(page); return [`T-${page},Ticket ${page},open`]; } @Tool({ name: "export_tickets", description: "Export every support ticket as CSV. Gives up after 350 ms.", inputSchema: {}, annotations: { readOnlyHint: true }, timeout: { executeMs: 350 }, }) export class ExportTickets extends ToolContext { async execute() { const rows: string[] = []; try { for (let page = 1; page <= 10; page++) { this.signal?.throwIfAborted(); // ✅ stop between pages once the call has timed out rows.push(...(await readPage(page))); } } catch (error) { stops.push(String(this.signal?.reason?.message ?? error)); throw error; } return { csv: ["id,title,status", ...rows].join("\n") }; } } @Tool({ name: "export_stats", description: "How many database pages exports have read, and why they stopped.", inputSchema: {} }) export class ExportStats extends ToolContext { async execute() { return { pagesRead: pagesRead.length, stops }; } } ``` ```ts export.test.ts import { test, expect } from "@frontmcp/testing"; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("the export stops reading when its call times out", async ({ mcp }) => { const result = await mcp.tools.call("export_tickets", {}); expect(result.raw._meta?.code).toBe("EXECUTION_TIMEOUT"); await wait(1_200); // long enough to read all 10 pages, had it kept going const stats = (await mcp.tools.call("export_stats", {})).json(); expect(stats.pagesRead).toBeLessThan(10); expect(stats.stops).toContain('Execution of "export_tickets" timed out after 350ms'); }); ``` Take out the `throwIfAborted()` line and run the test again: the call still times out after 350 ms, but the export goes on to read all ten pages that nobody will see. `this.signal.reason` is the same timeout error the client got. Stopping is right for work that only reads. For work that changes things, stopping halfway can be worse than finishing, which is why the merge above doesn't listen to the signal. ## Turning limits off The limits in `@Tool` are enforced by FrontMCP's guard, which starts by itself when a tool declares `rateLimit` or `concurrency`. `@FrontMcp`'s `throttle` option configures the guard, and `throttle: { enabled: false }` turns it off: every `rateLimit` and `concurrency` on the server is ignored. That can be what you want for a local test run that calls the same tool many times: Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { ExportTickets } from "./export-tickets.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [ExportTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], throttle: { enabled: false }, // 🚩 for local testing only }) export default class Server {} ``` ```ts export-tickets.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "export_tickets", description: "Export every support ticket as CSV. Reads the whole ticket database, so at most 2 exports an hour.", inputSchema: {}, annotations: { readOnlyHint: true }, rateLimit: { maxRequests: 2, windowMs: 60 * 60_000 }, }) export class ExportTickets extends ToolContext { async execute() { const rows = tickets.map((t) => `${t.id},${t.title},${t.status}`); return { csv: ["id,title,status", ...rows].join("\n") }; } } ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; ``` ```ts limit.test.ts import { test, expect } from "@frontmcp/testing"; test("with the guard off, five exports in a row all succeed", async ({ mcp }) => { for (let i = 0; i < 5; i++) { expect(await mcp.tools.call("export_tickets", {})).toBeSuccessful(); } }); ``` The description still says "at most 2 exports an hour", and nothing enforces it, so keep `enabled: false` out of anything a real client can reach. `timeout` is the one limit it doesn't turn off. ## Limits for every tool `throttle` can also set defaults, for tools that don't set their own. Unlike a tool's own limits, `throttle` needs `enabled: true`: ```ts main.ts @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], throttle: { enabled: true, defaultRateLimit: { maxRequests: 60, windowMs: 60_000, partitionBy: "ip" }, defaultConcurrency: { maxConcurrent: 5 }, defaultTimeout: { executeMs: 30_000 }, }, }) export default class Server {} ``` A tool's own `rateLimit`, `concurrency` or `timeout` replaces the default. The [`@FrontMcp` reference](https://frontmcp.dev/reference/sdk/frontmcp#setting-defaults-for-every-tool) shows `defaultRateLimit` running. > **Note** > > Two more `throttle` options apply to the server as a whole. `globalConcurrency: { maxConcurrent }` caps how many tool calls run at once across every tool; a call over it is refused with `Concurrency limit reached for "global"`. `global: { maxRequests, windowMs }` is one rate limit for every request the server gets. It's checked when a request arrives, before any tool runs, so a request over it gets HTTP `429` with a `Retry-After` header and JSON-RPC error `-32029`, not a tool error. ## Choosing limits | Kind of tool | Example | Limits | | --- | --- | --- | | Cheap and read-only | `search_tickets` | Usually none of its own. A server-wide `defaultRateLimit` if strangers can reach the server. | | Expensive to run | `export_tickets` | A `rateLimit` per caller (`"userId"`), and a `timeout` whose `this.signal` stops the work. | | Waits on another service | `lookup_customer` | A `timeout` shorter than the client is willing to wait, so the model gets an error it can explain, with `this.signal` passed on to the request. | | Changes shared state | `merge_customers` | `concurrency: { maxConcurrent: 1 }`, with a short queue. No timeout shorter than the work. | | Sends email or spends money | `email_customer`, `refund_order` | A low `rateLimit` per caller. A model stuck in a loop shouldn't be able to send a hundred emails. A limit doesn't ask anyone: to have the user agree first, add [approval](https://frontmcp.dev/learn/asking-for-approval). | Whatever you choose, write it in the description. Limits the model knows about are limits it can work with. ## Recap - `rateLimit`, `concurrency` and `timeout` on `@Tool` work as soon as a tool sets them. `throttle` in `@FrontMcp` adds defaults for every tool, and `throttle: { enabled: false }` turns rate limits and concurrency off. - A call over a limit gets an `isError` result, over HTTP `200`, with its own `_meta.code` (`RATE_LIMIT_EXCEEDED`, `CONCURRENCY_LIMIT`, `QUEUE_TIMEOUT`, `EXECUTION_TIMEOUT`) and a message kept in production. "Retry after N seconds" counts down to the end of a clock-aligned window. - `partitionBy` picks whose calls share a count. With `"userId"`, each signed-in caller has a count of their own, and all anonymous callers share one. - `concurrency: { maxConcurrent, queueTimeoutMs }` stops calls overlapping, and a timed-out call keeps its slot until `execute()` really ends. - `timeout: { executeMs }` ends the call and aborts `this.signal`. Pass the signal on so read-only work stops too, and don't give tools that change things a timeout shorter than their work. - Every guard option, and what each error looks like to a caller, is in the [Guard options reference](https://frontmcp.dev/reference/sdk/guard). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Cap the export Nothing stops a model from exporting the ticket database over and over. Allow at most 3 exports an hour, for the whole server. Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts main.ts import { App, FrontMcp, Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "export_tickets", description: "Export every support ticket as CSV.", inputSchema: {}, annotations: { readOnlyHint: true }, }) class ExportTickets extends ToolContext { async execute() { return { csv: "id,title,status\nT-1,Cannot log in,open\nT-2,Invoice total is wrong,closed" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ExportTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { App, FrontMcp, Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "export_tickets", description: "Export every support ticket as CSV. At most 3 exports an hour.", inputSchema: {}, annotations: { readOnlyHint: true }, rateLimit: { maxRequests: 3, windowMs: 60 * 60_000 }, }) class ExportTickets extends ToolContext { async execute() { return { csv: "id,title,status\nT-1,Cannot log in,open\nT-2,Invoice total is wrong,closed" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ExportTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts export.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("three exports in an hour work, and the fourth is refused", async ({ mcp }) => { for (let i = 0; i < 3; i++) { expect(await mcp.tools.call("export_tickets", {})).toBeSuccessful(); } const fourth = await mcp.tools.call("export_tickets", {}); expect(fourth).toBeError(); expect(fourth.raw._meta?.code).toBe("RATE_LIMIT_EXCEEDED"); }); test("the refusal tells the model when to retry", async ({ mcp }) => { const result = await mcp.tools.call("export_tickets", {}); expect(result.text()).toMatch(/Retry after \d+ seconds/); }); ``` **Hint:** One option on `@Tool` does it. `windowMs` is in milliseconds. **Solution:** `rateLimit: { maxRequests: 3, windowMs: 60 * 60_000 }` counts calls per hour, and the default `partitionBy: "global"` shares that count across every caller. The server needs no change: a tool that declares a limit is enough to start the guard. The description now says the rule, for the model. ### Challenge: Let the second merge wait its turn `merge_customers` runs one merge at a time, and refuses a second merge that arrives while one is running. A merge takes a fraction of a second, so make a second merge wait for the first one instead, for up to 5 seconds. Merges must still never run at the same time. Initial call configuration: ```js { tool: "merge_customers", arguments: { from: "C-7", into: "C-2" } } ``` ```ts merge-customers.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; const merges: string[] = []; let running = 0; let mostAtOnce = 0; @Tool({ name: "merge_customers", description: "Merge one customer record into another, moving all its tickets. One merge runs at a time.", inputSchema: { from: z.string(), into: z.string() }, annotations: { destructiveHint: true }, concurrency: { maxConcurrent: 1 }, }) export class MergeCustomers extends ToolContext { async execute({ from, into }: { from: string; into: string }) { running++; mostAtOnce = Math.max(mostAtOnce, running); await new Promise((resolve) => setTimeout(resolve, 300)); merges.push(`${from} → ${into}`); running--; return { merged: from, into }; } } @Tool({ name: "merge_log", description: "List finished merges.", inputSchema: {} }) export class MergeLog extends ToolContext { async execute() { return { merges, mostAtOnce }; } } ``` **Solution file (alternative to the starter):** ```ts merge-customers.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const merges: string[] = []; let running = 0; let mostAtOnce = 0; @Tool({ name: "merge_customers", description: "Merge one customer record into another, moving all its tickets. One merge runs at a time; a second merge waits up to 5 seconds for its turn.", inputSchema: { from: z.string(), into: z.string() }, annotations: { destructiveHint: true }, concurrency: { maxConcurrent: 1, queueTimeoutMs: 5_000 }, }) export class MergeCustomers extends ToolContext { async execute({ from, into }: { from: string; into: string }) { running++; mostAtOnce = Math.max(mostAtOnce, running); await new Promise((resolve) => setTimeout(resolve, 300)); merges.push(`${from} → ${into}`); running--; return { merged: from, into }; } } @Tool({ name: "merge_log", description: "List finished merges.", inputSchema: {} }) export class MergeLog extends ToolContext { async execute() { return { merges, mostAtOnce }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { MergeCustomers, MergeLog } from "./merge-customers.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [MergeCustomers, MergeLog] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts merge.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("two merges started together both succeed", async ({ mcp }) => { const results = await Promise.all([ mcp.tools.call("merge_customers", { from: "C-7", into: "C-2" }), mcp.tools.call("merge_customers", { from: "C-8", into: "C-2" }), ]); for (const result of results) expect(result).toBeSuccessful(); }); test("they ran one after the other", async ({ mcp }) => { const log = (await mcp.tools.call("merge_log", {})).json(); expect(log.merges).toHaveLength(2); expect(log.mostAtOnce).toBe(1); }); ``` **Hint:** `concurrency` has an option for how long a call may wait for a free slot. Its default, `0`, means not at all. **Solution:** `queueTimeoutMs: 5_000` makes a call that finds the slot taken wait for it, for up to 5 seconds, instead of failing at once. `maxConcurrent: 1` still holds, so the second merge starts when the first ends: both succeed, and `mostAtOnce` stays `1`. If a merge ever took longer than 5 seconds, the waiting call would fail with `QUEUE_TIMEOUT`, so the description says how long it waits. ### Challenge: Give up on a slow CRM `lookup_customer` waits as long as the CRM takes, and for `C-9` that's two seconds. Make the tool give up after 500 milliseconds, so the model hears back quickly. Lookups that answer in time must still work. Initial call configuration: ```js { tool: "lookup_customer", arguments: { id: "C-1" } } ``` ```ts lookup-customer.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; async function crmLookup(id: string) { await new Promise((resolve) => setTimeout(resolve, id === "C-9" ? 2_000 : 50)); return { id, name: id === "C-9" ? "Globex" : "Initech", plan: "business" }; } @Tool({ name: "lookup_customer", description: "Look up a customer in the CRM by id.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class LookupCustomer extends ToolContext { async execute({ id }: { id: string }) { return crmLookup(id); } } ``` **Solution file (alternative to the starter):** ```ts lookup-customer.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; async function crmLookup(id: string) { await new Promise((resolve) => setTimeout(resolve, id === "C-9" ? 2_000 : 50)); return { id, name: id === "C-9" ? "Globex" : "Initech", plan: "business" }; } @Tool({ name: "lookup_customer", description: "Look up a customer in the CRM by id. Gives up after half a second if the CRM is slow; if it does, try again later.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, timeout: { executeMs: 500 }, }) export class LookupCustomer extends ToolContext { async execute({ id }: { id: string }) { return crmLookup(id); } } ``` **Hidden fixture/test file (runs with the example):** ```ts lookup.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("a fast lookup still works", async ({ mcp }) => { const result = await mcp.tools.call("lookup_customer", { id: "C-1" }); expect(result).toBeSuccessful(); expect(result.json().name).toBe("Initech"); }); test("a slow lookup fails within a second", async ({ mcp }) => { const result = await mcp.tools.call("lookup_customer", { id: "C-9" }); expect(result).toBeError(); expect(result.text()).toContain("timed out"); expect(result.durationMs).toBeLessThan(1_000); }); ``` **Hint:** One of the three `@Tool` limits is about time. Its value is in milliseconds. **Solution:** `timeout: { executeMs: 500 }` makes FrontMCP answer with `Execution of "lookup_customer" timed out after 500ms` once half a second has passed. The lookup itself keeps running until the CRM answers, because it doesn't listen to `this.signal`; the next challenge fixes that. The description tells the model what a failure means and what to do about it. ### Challenge: Cancel the CRM request `lookup_customer` gives up after half a second, but its request to the CRM doesn't: for `C-9` it keeps a CRM connection busy for two whole seconds, for an answer nobody reads. Make the request stop when the call times out. `crmLookup` takes a `signal`, like `fetch()` does. Initial call configuration: ```js { tool: "lookup_customer", arguments: { id: "C-1" } } ``` ```ts lookup-customer.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { crmLookup } from "./crm"; @Tool({ name: "lookup_customer", description: "Look up a customer in the CRM by id. Gives up after half a second if the CRM is slow; if it does, try again later.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, timeout: { executeMs: 500 }, }) export class LookupCustomer extends ToolContext { async execute({ id }: { id: string }) { return crmLookup(id); } } ``` **Solution file (alternative to the starter):** ```ts lookup-customer.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { crmLookup } from "./crm"; @Tool({ name: "lookup_customer", description: "Look up a customer in the CRM by id. Gives up after half a second if the CRM is slow; if it does, try again later.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, timeout: { executeMs: 500 }, }) export class LookupCustomer extends ToolContext { async execute({ id }: { id: string }) { return crmLookup(id, { signal: this.signal }); } } ``` ```ts crm.ts import { Tool, ToolContext } from "@frontmcp/sdk"; // Stands in for the CRM's client library, and counts what happens to its requests. const requests = { answered: 0, cancelled: 0 }; export async function crmLookup(id: string, options: { signal?: AbortSignal } = {}) { await new Promise((resolve, reject) => { const timer = setTimeout(resolve, id === "C-9" ? 2_000 : 50); options.signal?.addEventListener("abort", () => { clearTimeout(timer); requests.cancelled += 1; reject(options.signal?.reason); }); }); requests.answered += 1; return { id, name: id === "C-9" ? "Globex" : "Initech", plan: "business" }; } @Tool({ name: "crm_requests", description: "How many CRM requests were answered and cancelled.", inputSchema: {} }) export class CrmRequests extends ToolContext { async execute() { return { ...requests }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts lookup.test.ts hidden import { test, expect } from "@frontmcp/testing"; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("a fast lookup still works", async ({ mcp }) => { const result = await mcp.tools.call("lookup_customer", { id: "C-1" }); expect(result).toBeSuccessful(); expect(result.json().name).toBe("Initech"); }); test("a slow lookup still times out", async ({ mcp }) => { const result = await mcp.tools.call("lookup_customer", { id: "C-9" }); expect(result.raw._meta?.code).toBe("EXECUTION_TIMEOUT"); }); test("its CRM request is cancelled", async ({ mcp }) => { await wait(100); expect((await mcp.tools.call("crm_requests", {})).json().cancelled).toBe(1); }); ``` **Hint:** When a call times out, FrontMCP aborts the call's `AbortSignal`. Where does a tool find it? **Solution:** `this.signal` is aborted when the call times out, and `crmLookup(id, { signal: this.signal })` hands it to the CRM client, which drops the request as soon as that happens. The model hears back after half a second either way; the difference is that the CRM stops working on an answer nobody will read. Pass `this.signal` on the same way to `fetch()` and to any client that takes one. --- # Doing Work in the Background > When a tool isn't enough. FrontMCP jobs for slow, flaky and long-running work, the tools clients run them with, background runs and retries, workflows that chain jobs, and duties, schedules and workers for work no client asks for. Source: https://frontmcp.dev/learn/background-work [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every tool in this course so far does its work while the client waits, and answers in the same call. That's right for most tools. Some work doesn't fit: an export that takes minutes, a sync with a CRM that fails now and then and should just be tried again, a nightly report made of several steps, or anything that should keep going after the call has returned. FrontMCP has **jobs** and **workflows** for this. This chapter covers jobs and workflows, including retries, background runs and deployment limits, and points out where 1.8 behaves differently from its docs. It ends with work that no client starts: **duties** and schedules for work at fixed times, and **workers** for work that never ends. **In this chapter** - [How to write a job, run it, and read what comes back](https://frontmcp.dev/learn/your-first-job) - [How to run a job in the background, retry it, and check on it](https://frontmcp.dev/learn/running-jobs-in-the-background) - [How to chain jobs into a workflow](https://frontmcp.dev/learn/chaining-jobs-into-workflows) - [How to run work on a schedule, and keep a long-running process supervised](https://frontmcp.dev/learn/scheduling-work-and-running-workers) - [How to tell a client that something happened, without being asked](https://frontmcp.dev/learn/telling-clients-something-happened) ## Your first job A job is written like a tool: a class with an input schema, an output schema and an `execute()` method. What's different is how it runs. A client doesn't call a job directly. It calls `execute_job` with the job's name, and FrontMCP runs the job, records the run, and returns the result with the job's logs: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "find-sla-breaches", input: { priority: "high" } } } ``` ```ts main.ts active import { App, FrontMcp, Job, JobContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", priority: "high", status: "open", hoursOpen: 6 }, { id: "T-2", priority: "normal", status: "open", hoursOpen: 30 }, { id: "T-3", priority: "high", status: "open", hoursOpen: 2 }, ]; @Job({ name: "find-sla-breaches", description: "Find the open tickets of one priority that have waited longer than their SLA allows.", inputSchema: { priority: z.enum(["high", "normal"]) }, outputSchema: { breaches: z.array(z.string()) }, }) class FindSlaBreaches extends JobContext { async execute({ priority }: { priority: "high" | "normal" }) { const limit = priority === "high" ? 4 : 24; const breaches = tickets.filter((t) => t.priority === priority && t.hoursOpen > limit).map((t) => t.id); this.log(`${breaches.length} ${priority}-priority tickets are past their SLA`); return { breaches }; } } @App({ id: "help-desk", name: "Help Desk", jobs: [FindSlaBreaches] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts job.test.ts import { test, expect } from "@frontmcp/testing"; test("registering a job adds FrontMCP's job tools", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name).sort(); expect(names).toEqual(["cancel_job", "execute_job", "execute_workflow", "get_job_status", "get_workflow_status"]); }); test("execute_job runs the job and returns the run", async ({ mcp }) => { const run = (await mcp.tools.call("execute_job", { name: "find-sla-breaches", input: { priority: "high" } })).json(); expect(run).toEqual({ runId: expect.any(String), uri: expect.stringMatching(/^job:\/\/runs\//), state: "completed", result: { breaches: ["T-1"] }, logs: [expect.stringMatching(/\] 1 high-priority tickets are past their SLA$/)], }); }); ``` Open the **Capabilities** tab: the job isn't a tool. Registering it with `@App({ jobs })` added five tools of FrontMCP's own, the same five for any server with jobs or workflows: | Tool | What it does | | --- | --- | | `execute_job` | Runs a job by name, and returns the run: at the end of the call, or, with `background: true`, at once. | | `get_job_status` | Reads a run by its id: its state, and its result or error. | | `cancel_job` | Cancels an unfinished job run and aborts its signal. | | `execute_workflow` | Runs a workflow, the same way. | | `get_workflow_status` | Reads a workflow's run. | Nothing in `tools/list` says which jobs exist, so a server has to tell the model, for example in its `instructions`. ### [Your First Job](https://frontmcp.dev/learn/your-first-job) Learn how to write and register a job, how a model finds out which jobs there are, what `execute_job` returns, what happens when the input is wrong or the job throws, and when to write a job instead of a tool. ## Running jobs in the background With `background: true`, `execute_job` answers straight away with a run id, and the job carries on. `get_job_status` reads the run later, for the caller who started it or one passing the job's explicit `read` rule, and under MCP 2026-07-28 an anonymous caller is a new caller on every request. The Playground's calls are anonymous, so they can start a run but never read it: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "export-tickets", background: true } } ``` ```ts main.ts active import { App, FrontMcp, Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "export-tickets", description: "Export every support ticket as CSV. Takes a while.", inputSchema: {}, outputSchema: { csv: z.string() }, }) class ExportTickets extends JobContext { async execute() { await new Promise((resolve) => setTimeout(resolve, 1_000)); // reading the whole database return { csv: "id,title,status\nT-1,Cannot log in,open" }; } } @App({ id: "help-desk", name: "Help Desk", jobs: [ExportTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts background.test.ts import { test, expect } from "@frontmcp/testing"; test("a background run starts at once", async ({ mcp }) => { const started = await mcp.tools.call("execute_job", { name: "export-tickets", background: true }); expect(started.json()).toEqual({ runId: expect.any(String), state: "pending", uri: expect.stringMatching(/^job:\/\/runs\//) }); expect(started.durationMs).toBeLessThan(200); }); test("an anonymous caller can't read it afterwards", async ({ mcp }) => { const { runId } = (await mcp.tools.call("execute_job", { name: "export-tickets", background: true })).json(); const status = await mcp.tools.call("get_job_status", { runId }); expect(status).toBeError("INVALID_INPUT"); expect(status.text()).toBe(`Run "${runId}" not found`); }); ``` Call `get_job_status` with the `runId` from the Call tab to see it for yourself. The run is there, and a caller who signed in could read it. ### [Running Jobs in the Background](https://frontmcp.dev/learn/running-jobs-in-the-background) Learn what states a run goes through, how to retry a flaky job and what gets retried, who can read a run and how to get results to anonymous callers anyway, and how to keep runs in Redis. ## Chaining jobs into workflows A workflow chains jobs. Each step names a job, the steps it depends on, and its input, which can be built from the outputs of earlier steps. FrontMCP runs the steps in order, and steps that don't depend on each other at the same time: Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: { priority: "high" } } } ``` ```ts main.ts active import { App, FrontMcp, Job, JobContext, Workflow, z } from "@frontmcp/sdk"; @Job({ name: "find-sla-breaches", inputSchema: { priority: z.enum(["high", "normal"]) }, outputSchema: { breaches: z.array(z.string()) }, }) class FindSlaBreaches extends JobContext { async execute({ priority }: { priority: "high" | "normal" }) { return { breaches: priority === "high" ? ["T-1"] : ["T-2"] }; } } @Job({ name: "write-report", inputSchema: { breaches: z.array(z.string()) }, outputSchema: { report: z.string() }, }) class WriteReport extends JobContext { async execute({ breaches }: { breaches: string[] }) { return { report: `${breaches.length} tickets broke their SLA: ${breaches.join(", ")}.` }; } } @Workflow({ name: "nightly-ticket-report", steps: [ { id: "breaches", jobName: "find-sla-breaches" }, { id: "report", jobName: "write-report", dependsOn: ["breaches"], input: (steps) => ({ breaches: steps.get("breaches").outputs.breaches }), }, ], }) class NightlyTicketReport {} @App({ id: "help-desk", name: "Help Desk", jobs: [FindSlaBreaches, WriteReport], workflows: [NightlyTicketReport] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts workflow.test.ts import { test, expect } from "@frontmcp/testing"; test("each step's output is in the result", async ({ mcp }) => { const run = (await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: { priority: "high" } })).json(); expect(run).toMatchObject({ state: "completed", result: { stepResults: { breaches: { state: "completed", outputs: { breaches: ["T-1"] } }, report: { state: "completed", outputs: { report: "1 tickets broke their SLA: T-1." } }, }, }, }); }); ``` The first step has no `input` of its own, so it gets the workflow's, `{ priority: "high" }`. The second waits for it, and builds its input from its output. ### [Chaining Jobs into Workflows](https://frontmcp.dev/learn/chaining-jobs-into-workflows) Learn how to pass data between steps, which steps run at the same time, what a failing step does to the others, how to make a step optional, and how to read a workflow that ran in the background. ## Scheduling work and running workers Everything above runs when a client asks. A nightly report, a cleanup every ten minutes and a mailbox to watch have no client. A **duty** runs a provider's `run()` every interval or on a cron schedule, a workflow can carry a schedule of its own, and a **worker** keeps a `run()` that never ends alive, running it again when it fails: ```ts background.ts import { Duty, Worker, Workflow, type DutyRunContext, type WorkerRunContext } from "@frontmcp/sdk"; @Duty({ name: "sweep-sessions", every: "10m", scope: "machine" }) export class SessionSweeper { async run({ signal }: DutyRunContext) { /* remove the expired sessions */ } } @Workflow({ name: "nightly-ticket-report", trigger: "schedule", schedule: { cron: "0 2 * * *", timezone: "Europe/Berlin", input: { priority: "high" } }, steps: [/* the steps above */], }) export class NightlyTicketReport {} @Worker({ name: "inbox-watcher", scope: "machine" }) export class InboxWatcher { async run({ signal }: WorkerRunContext) { /* stay connected to the mailbox until signal aborts */ } } ``` The duty and the worker go in an app's `providers`, the workflow in its `workflows`. When several copies of the server run, one of them does each piece of work, the one that holds its lease, and another takes over when that one stops: ```text Duty "sweep-sessions" runs in this process every 600000 ms The schedule of workflow "nightly-ticket-report" runs in this process on cron "0 2 * * *" (Europe/Berlin) Worker "inbox-watcher" runs in this process ``` All three need a server process that stays up, so nothing here starts in the Playground, or in a serverless deployment. ### [Scheduling Work and Running Workers](https://frontmcp.dev/learn/scheduling-work-and-running-workers) Learn why a timer runs once per copy of the server, how to schedule a duty or a workflow and who a scheduled run runs as, how a worker is started, restarted and stopped, how it publishes what it sees, and what happens across several instances and at a restart. ## Telling clients something happened A job runs when a client starts it. Some things happen with no client asking at all: a ticket passes its SLA at night, or another system opens one. An **event** lets the server say so. It declares what can happen, a client subscribes once, and the server tells it each time, also when no conversation is open. ### [Telling Clients Something Happened](https://frontmcp.dev/learn/telling-clients-something-happened) Learn how to declare an event and publish it from a tool and from background code, how a client receives it and what a cursor is for, how to let subscribers filter, and how to decide who hears each occurrence. ## Tool, job or workflow? | If the work… | Write | | --- | --- | | Answers the model right away, like a search or closing a ticket | A tool | | Takes a while, should be retried when it fails, or should keep going after the call | A job | | Is several jobs, where some need what others produce | A workflow of jobs | | Runs at fixed times with nobody asking, like a cleanup every ten minutes | A duty, or a workflow with a schedule when it is several jobs | | Never ends by itself, like a connection to keep open or a folder to watch | A worker | ## What's next? Start the chapter with [Your First Job](https://frontmcp.dev/learn/your-first-job). To see the first three lessons in one server, read the [Nightly Ticket Report](https://frontmcp.dev/examples/nightly-ticket-report) example, and look up every option in the [`@Job`](https://frontmcp.dev/reference/sdk/job) and [`@Workflow`](https://frontmcp.dev/reference/sdk/workflow) references. After this chapter, [Delegating to Agents](https://frontmcp.dev/learn/delegating-to-agents) covers handing a whole task to a model of your own, with its own tools and instructions. --- # Your First Job > How to write a FrontMCP job with @Job and JobContext, register it on an app, run it with the execute_job tool, and read the result, logs and errors that come back. Source: https://frontmcp.dev/learn/your-first-job [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every tool so far has done its work inside one call and answered. A **job** is work you hand to FrontMCP instead: a named piece of work with an input schema and an output schema, which FrontMCP runs when a client asks, records as a *run*, and can retry, run in the background, or chain with other jobs. This lesson writes one, runs it the way a client would, and looks at everything that comes back, including what happens when the input is wrong or the job fails. **You will learn** - How to write a job with `@Job` and `JobContext`, and register it on an app - Which tools FrontMCP adds for jobs, and how a client runs one with `execute_job` - What a run's result holds: `runId`, `state`, `result` and `logs` - What the caller gets back when the input is wrong or the job throws - When to write a job, and when a tool is the better choice ## Writing a job The help desk promises to answer high-priority tickets within 4 hours and normal ones within a day. Finding the open tickets that broke that promise reads every open ticket, it should run every night whether or not anyone is chatting with a model, and later in this chapter it becomes one step of a nightly report. That's work for a job. Open the **Tests** tab: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "find-sla-breaches", input: { priority: "high" } } } ``` ```ts find-sla-breaches.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; const SLA_HOURS = { high: 4, normal: 24 }; @Job({ name: "find-sla-breaches", description: "Find the open tickets of one priority that have waited longer than their SLA allows.", inputSchema: { priority: z.enum(["high", "normal"]).describe("Which tickets to check"), }, outputSchema: { priority: z.enum(["high", "normal"]), breaches: z.array(z.object({ id: z.string(), hoursOpen: z.number() })), }, }) export class FindSlaBreaches extends JobContext { async execute({ priority }: { priority: "high" | "normal" }) { const open = tickets.filter((t) => t.status === "open" && t.priority === priority); this.log(`Checking ${open.length} open ${priority}-priority tickets`); const breaches = open .filter((t) => t.hoursOpen > SLA_HOURS[priority]) .map((t) => ({ id: t.id, hoursOpen: t.hoursOpen })); this.log(`Found ${breaches.length} past the ${SLA_HOURS[priority]}-hour SLA`); return { priority, breaches }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { FindSlaBreaches } from "./find-sla-breaches.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [FindSlaBreaches] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in", priority: "high", status: "open", hoursOpen: 6 }, { id: "T-2", title: "Invoice total is wrong", priority: "normal", status: "open", hoursOpen: 30 }, { id: "T-3", title: "Login link expired", priority: "high", status: "open", hoursOpen: 2 }, { id: "T-4", title: "Refund not received", priority: "normal", status: "closed", hoursOpen: 50 }, ]; ``` ```ts sla.test.ts import { test, expect } from "@frontmcp/testing"; test("finds the high-priority ticket past its SLA", async ({ mcp }) => { const run = await mcp.tools.call("execute_job", { name: "find-sla-breaches", input: { priority: "high" } }); expect(run).toBeSuccessful(); expect(run.json()).toMatchObject({ runId: expect.any(String), uri: expect.stringMatching(/^job:\/\/runs\//), state: "completed", result: { priority: "high", breaches: [{ id: "T-1", hoursOpen: 6 }] }, }); }); test("each log line starts with the time it was written", async ({ mcp }) => { const run = (await mcp.tools.call("execute_job", { name: "find-sla-breaches", input: { priority: "normal" } })).json(); expect(run.logs).toEqual([ expect.stringMatching(/^\[\d{4}-\d\d-\d\dT[\d:.]+Z\] Checking 1 open normal-priority tickets$/), expect.stringMatching(/\] Found 1 past the 24-hour SLA$/), ]); }); test("every run gets its own id", async ({ mcp }) => { const first = (await mcp.tools.call("execute_job", { name: "find-sla-breaches", input: { priority: "high" } })).json(); const second = (await mcp.tools.call("execute_job", { name: "find-sla-breaches", input: { priority: "high" } })).json(); expect(second.runId).not.toBe(first.runId); }); ``` A job looks a lot like a tool: - **`@Job({ name, description, inputSchema, outputSchema })`** describes it. `name` is what a client asks for. `inputSchema` and `outputSchema` are Zod shapes, as on a tool, and both are required: a job without an `outputSchema` fails as soon as its class is decorated. - **`JobContext`** is the base class, and **`execute(input)`** does the work. It gets the input already checked against `inputSchema`, and what it returns is the job's result. - **`this.log(message)`** adds a line to the run's logs, with the time in front. - **`jobs: [FindSlaBreaches]`** on `@App` registers it. That's all it takes: FrontMCP turns jobs on for any server with an app that has jobs or workflows. ## How a client runs a job The job isn't a tool, and it doesn't show up in `tools/list`. Open the **Capabilities** tab of the example above: registering one job added five tools of FrontMCP's own, and the call in the Call tab went through the first of them. | Tool | What it does | | --- | --- | | `execute_job` | Runs the job called `name` with `input`, and returns the run. `background: true` starts it and returns at once, which the [next lesson](https://frontmcp.dev/learn/running-jobs-in-the-background) covers. | | `get_job_status` | Reads a run by its `runId`. | | `cancel_job` | Cancels an unfinished job run and aborts its signal. | | `execute_workflow` | Runs a workflow, a chain of jobs. See [Chaining Jobs into Workflows](https://frontmcp.dev/learn/chaining-jobs-into-workflows). | | `get_workflow_status` | Reads a workflow's run. | All five appear as soon as one app has a job, even if there are no workflows. FrontMCP also adds `list_jobs`, `list_workflows`, `remove_job` and `remove_workflow`, but leaves them out of `tools/list`. They still answer when a client calls them by name. That leaves a model with a problem. It sees `execute_job`, described as "Execute a registered job by name", and nothing that says which names exist or what input they take. Tell it, in the server's [`instructions`](https://frontmcp.dev/reference/sdk/frontmcp#giving-the-model-instructions): Initial call configuration: ```js { tool: "execute_job", arguments: { name: "find-sla-breaches", input: { priority: "high" } } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { FindSlaBreaches } from "./find-sla-breaches.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [FindSlaBreaches] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], instructions: "Help desk jobs, run with execute_job. " + 'find-sla-breaches, input { priority: "high" | "normal" }: lists open tickets that have waited longer than their SLA.', }) export default class Server {} ``` ```ts find-sla-breaches.job.ts import { Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "find-sla-breaches", description: "Find the open tickets of one priority that have waited longer than their SLA allows.", inputSchema: { priority: z.enum(["high", "normal"]).describe("Which tickets to check") }, outputSchema: { priority: z.enum(["high", "normal"]), breaches: z.array(z.object({ id: z.string(), hoursOpen: z.number() })) }, }) export class FindSlaBreaches extends JobContext { async execute({ priority }: { priority: "high" | "normal" }) { return { priority, breaches: priority === "high" ? [{ id: "T-1", hoursOpen: 6 }] : [] }; } } ``` ```ts discovery.test.ts import { test, expect } from "@frontmcp/testing"; test("tools/list has FrontMCP's five job tools, not the job", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name).sort(); expect(names).toEqual(["cancel_job", "execute_job", "execute_workflow", "get_job_status", "get_workflow_status"]); }); test("the instructions name the job and its input", async ({ mcp }) => { const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "server/discover" }); expect(response.result.instructions).toContain('find-sla-breaches, input { priority: "high" | "normal" }'); }); test("list_jobs isn't listed, but answers when called", async ({ mcp }) => { const result = await mcp.tools.call("list_jobs", {}); expect(result.json()).toMatchObject({ count: 1, jobs: [{ name: "find-sla-breaches" }] }); }); ``` Clients read `instructions` from `server/discover` and usually add them to the model's context. `list_jobs` returns each job's name, description and input schema, but a model only calls a tool it has heard of, so don't rely on it. From here on, examples that don't need a server of their own leave out `main.ts`. When an example exports jobs but no app, the Playground registers them in one for you, as it does tools. ## What comes back `execute_job` runs the job and answers when it's finished, with the run as `structuredContent` and as JSON text: ```json { "runId": "5b0e3c1e-8a47-4c1e-9d0a-1f6c2e7b9a30", "state": "completed", "result": { "priority": "high", "breaches": [{ "id": "T-1", "hoursOpen": 6 }] }, "logs": [ "[2026-09-27T09:00:00.123Z] Checking 2 open high-priority tickets", "[2026-09-27T09:00:00.124Z] Found 1 past the 4-hour SLA" ] } ``` - **`runId`** names this run, and it's new every time. It's what `get_job_status` takes. - **`state`** is `"completed"`. A run that fails doesn't come back as a run at all, but as an error, [below](https://frontmcp.dev/learn/your-first-job#when-a-job-fails). - **`result`** is what `execute()` returned, checked against `outputSchema`. - **`logs`** are the `this.log()` lines, each starting with the time it was written in ISO format. > **Pitfall: Outside data has to match the output schema** > > `@Job`'s types make TypeScript check that `execute()` returns what `outputSchema` describes, and FrontMCP checks the result again when the job runs. That matters when the data comes from somewhere TypeScript can't see, like a response from another service: > > Initial call configuration: > > ```js > { tool: "execute_job", arguments: { name: "find-sla-breaches", input: { priority: "high" } } } > ``` > > ```ts find-sla-breaches.job.ts active > import { Job, JobContext, z } from "@frontmcp/sdk"; > > // Stands in for a reporting service. It renamed two fields in its last release, but > // only for high-priority tickets, and it sends each customer's email address along. > async function fetchBreaches(priority: string): Promise { > if (priority === "high") return [{ ticket: "T-1", hours: 6 }]; > return [{ id: "T-2", hoursOpen: 30, customerEmail: "ap@globex.example" }]; > } > > @Job({ > name: "find-sla-breaches", > inputSchema: { priority: z.enum(["high", "normal"]) }, > outputSchema: { priority: z.enum(["high", "normal"]), breaches: z.array(z.object({ id: z.string(), hoursOpen: z.number() })) }, > }) > export class FindSlaBreaches extends JobContext { > async execute({ priority }: { priority: "high" | "normal" }) { > return { priority, breaches: await fetchBreaches(priority) }; // 🚩 not always what outputSchema says > } > } > ``` > > ```ts output.test.ts > import { test, expect } from "@frontmcp/testing"; > > test("a result that doesn't match outputSchema fails the call", async ({ mcp }) => { > const result = await mcp.tools.call("execute_job", { name: "find-sla-breaches", input: { priority: "high" } }); > expect(result).toBeError("INVALID_OUTPUT"); > expect(result.text()).toBe("Tool output validation failed (output does not match outputSchema at breaches.0.id)"); > }); > > test("a field outputSchema doesn't declare is dropped", async ({ mcp }) => { > const run = (await mcp.tools.call("execute_job", { name: "find-sla-breaches", input: { priority: "normal" } })).json(); > expect(run.result.breaches).toEqual([{ id: "T-2", hoursOpen: 30 }]); > }); > ``` > > A result that doesn't match fails the call with `INVALID_OUTPUT`, and the message names the first field that's wrong. That tells the model the job broke, but not what it could do about it. Fields that `outputSchema` doesn't declare are dropped, so the customer's email never reaches the client. Parse outside data yourself, for example with the same Zod schema, and fail with a [`PublicMcpError`](https://frontmcp.dev/learn/your-first-job#when-a-job-fails) that says what went wrong. (Changed in 1.9.2: before, FrontMCP didn't check the result at run time, and sent it as it was.) ## When the input is wrong `execute_job`'s own input schema takes any object as `input`. FrontMCP checks it against the job's `inputSchema` when it runs the job, and a mismatch fails the call. Here the model asked for a priority that doesn't exist, and a job name that doesn't either: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "find-sla-breaches", input: { priority: "urgent" } } } ``` ```ts find-sla-breaches.job.ts import { Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "find-sla-breaches", inputSchema: { priority: z.enum(["high", "normal"]).describe("Which tickets to check") }, outputSchema: { priority: z.enum(["high", "normal"]), breaches: z.array(z.object({ id: z.string(), hoursOpen: z.number() })) }, }) export class FindSlaBreaches extends JobContext { async execute({ priority }: { priority: "high" | "normal" }) { return { priority, breaches: [] }; } } ``` ```ts input.test.ts active import { test, expect } from "@frontmcp/testing"; test("input that doesn't match the job's schema fails the call", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "find-sla-breaches", input: { priority: "urgent" } }); expect(result).toBeError("INVALID_INPUT"); expect(result.text()).toMatch(/^Invalid input for job /); expect(result.text()).toContain('"path": [\n "priority"\n ]'); }); test("leaving out `input` is the same as sending {}", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "find-sla-breaches" }); expect(result).toBeError("INVALID_INPUT"); expect(result.text()).toContain("expected one of"); }); test("an unknown job name is refused", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "find-breaches", input: { priority: "high" } }); expect(result).toBeError("JOB_NOT_AUTHORIZED"); expect(result.text()).toBe('Job or workflow "find-breaches" not found or not permitted'); }); ``` A job refuses `"urgent"` with `INVALID_INPUT`: `Invalid input for job "find-sla-breaches"`, followed by Zod's list of problems. The message reaches production clients too. Changed in 1.11.3: before, this was `TOOL_EXECUTION_ERROR`, whose message production hid. An unknown name gets `JOB_NOT_AUTHORIZED`: `Job or workflow "find-breaches" not found or not permitted`. A job the caller isn't allowed to run, because of the job's [`permissions`](https://frontmcp.dev/reference/sdk/job#restricting-who-can-run-a-job), gets exactly the same answer, so a caller can't find out which jobs exist by guessing. This message is kept in production. So the model has to get the name and the input right the first time. Say both in `instructions`, as in the [previous section](https://frontmcp.dev/learn/your-first-job#how-a-client-runs-a-job), with the allowed values spelled out. ## When a job fails A job that throws fails the call. What the caller reads depends on what you throw, just as it does for a [tool](https://frontmcp.dev/learn/calling-other-services). This job copies a customer's plan from the CRM: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "sync-customer", input: { customerId: "C-404" } } } ``` ```ts sync-customer.job.ts active import { Job, JobContext, PublicMcpError, z } from "@frontmcp/sdk"; import { crm } from "./crm"; @Job({ name: "sync-customer", description: "Copy a customer's plan from the CRM into the help desk.", inputSchema: { customerId: z.string().describe("Customer id, like C-1") }, outputSchema: { customerId: z.string(), plan: z.string() }, }) export class SyncCustomer extends JobContext { async execute({ customerId }: { customerId: string }) { const customer = await crm.find(customerId); if (!customer) { // ✅ A message the model can act on, kept in production throw new PublicMcpError(`There's no customer ${customerId} in the CRM. Check the id with the user.`); } return { customerId, plan: customer.plan }; } } ``` ```ts crm.ts // Stands in for the CRM's client. C-500 makes it fail the way a service does when it's down. export const crm = { async find(id: string) { if (id === "C-500") throw new Error("connect ECONNREFUSED 10.0.4.7:5432"); return id === "C-1" ? { id, plan: "business" } : undefined; }, }; ``` ```ts failures.test.ts import { test, expect } from "@frontmcp/testing"; test("a PublicMcpError reaches the caller word for word", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-404" } }); expect(result).toBeError("PUBLIC_ERROR"); expect(result.text()).toBe("There's no customer C-404 in the CRM. Check the id with the user."); }); test("any other error is a TOOL_EXECUTION_ERROR", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-500" } }); expect(result).toBeError("TOOL_EXECUTION_ERROR"); expect(result.text()).toMatch(/^Tool "execute_job" execution failed: connect ECONNREFUSED/); }); test("a customer the CRM knows is synced", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-1" } }); expect(result.json().result).toEqual({ customerId: "C-1", plan: "business" }); }); ``` - **`PublicMcpError`**, thrown or passed to `this.fail()`, fails the call with your message, in production too, and code `PUBLIC_ERROR` unless you pass it a code of your own. Use it when the model can do something about the failure, like asking the user for the right id. - **Any other error** fails it with `TOOL_EXECUTION_ERROR`. In development the text is `Tool "execute_job" execution failed:` with the error's message and stack; in production it's `Internal FrontMCP error. Please contact support with error ID: …`, which keeps the address of your database out of the model's context. Either way, the caller gets an error, not a run with `state: "failed"`. Failed runs are recorded too, and the [next lesson](https://frontmcp.dev/learn/running-jobs-in-the-background#what-a-failed-run-looks-like) shows how to read one. ## A job as a function A job with no state of its own can be a function. `job({...})` takes the same options as `@Job` and returns a function that takes the handler; register what it returns, as you would a class: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "format-ticket-id", input: { number: 42 } } } ``` ```ts main.ts active import { App, FrontMcp, job, z } from "@frontmcp/sdk"; const FormatTicketId = job({ name: "format-ticket-id", description: "Turn a ticket number into the id customers see, like T-0042.", inputSchema: { number: z.number().int().positive() }, outputSchema: { id: z.string() }, })(({ number }, ctx) => { const id = `T-${String(number).padStart(4, "0")}`; ctx.log(`Formatted ${number} as ${id}`); return { id }; }); @App({ id: "help-desk", name: "Help Desk", jobs: [FormatTicketId] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts format.test.ts import { test, expect } from "@frontmcp/testing"; test("a function-style job runs like a class", async ({ mcp }) => { const run = (await mcp.tools.call("execute_job", { name: "format-ticket-id", input: { number: 42 } })).json(); expect(run).toMatchObject({ state: "completed", result: { id: "T-0042" } }); expect(run.logs).toEqual([expect.stringMatching(/\] Formatted 42 as T-0042$/)]); }); ``` The handler gets the job's context as its second argument, so `ctx.log()` writes to the run's logs, as `this.log()` does in a class. (Changed in 1.9.1: before, `log()` was `protected`, so `ctx.log()` didn't compile.) ## Jobs or tools? A job can do anything a tool can, so which should you write? | | Tool | Job | | --- | --- | --- | | How the model finds it | In `tools/list`, with its own description and schema | By a name you have to tell it, through `execute_job` | | When it runs | When called, and the answer comes back in the same call | When `execute_job` is called, in the call or [in the background](https://frontmcp.dev/learn/running-jobs-in-the-background) | | If it fails | The call fails | The call fails, or FrontMCP [retries](https://frontmcp.dev/learn/running-jobs-in-the-background#retrying-a-flaky-job) it first | | Afterwards | Nothing is kept | A run with an id, a state and logs | | In a workflow | No | Yes, as a [step](https://frontmcp.dev/learn/chaining-jobs-into-workflows) | If the model should call it and use the answer right away, like searching tickets or closing one, write a tool: it gets a proper description and schema in `tools/list`, and errors the model can read. Write a job for work that takes a while, that should be retried when it fails, that should keep going after the call returns, or that is one step of something bigger. A nightly report is all four. A job doesn't start by itself: it runs when something calls `execute_job`. Running the report every night with nobody asking takes a schedule, which is the last lesson of this chapter: [Scheduling Work and Running Workers](https://frontmcp.dev/learn/scheduling-work-and-running-workers). ## Recap - A job is a class that extends `JobContext`, decorated with `@Job({ name, inputSchema, outputSchema })`, or a function made with `job({...})`. Register it with `@App({ jobs: [...] })`. - Jobs aren't in `tools/list`. FrontMCP adds `execute_job`, `get_job_status`, `execute_workflow` and `get_workflow_status`, and the model has to be told which job names exist, for example in `instructions`. - `execute_job { name, input }` runs the job and returns `{ runId, state: "completed", result, logs }`. `this.log()` lines start with the time. - A result that doesn't match `outputSchema` fails with `INVALID_OUTPUT`, and fields it doesn't declare are dropped. Bad input fails with `INVALID_INPUT` and its issues, without retrying. An unknown name is `JOB_NOT_AUTHORIZED`. - Throw `PublicMcpError` for failures the model can act on. Anything else becomes `Internal FrontMCP error` in production. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Register the job `count-open-tickets` is written, but `execute_job` can't find it, and it doesn't log anything yet. Register it, and make it log how many open tickets it counted, like `Counted 2 open tickets for Acme`. ```ts main.ts active import { App, FrontMcp, Job, JobContext, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; @Job({ name: "count-open-tickets", description: "Count a customer's open tickets.", inputSchema: { customer: z.string().describe("Customer name, like Acme") }, outputSchema: { customer: z.string(), open: z.number() }, }) class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { const open = tickets.filter((t) => t.customer === customer && t.status === "open").length; return { customer, open }; } } @Tool({ name: "search_tickets", description: "Search tickets by title", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { App, FrontMcp, Job, JobContext, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; @Job({ name: "count-open-tickets", description: "Count a customer's open tickets.", inputSchema: { customer: z.string().describe("Customer name, like Acme") }, outputSchema: { customer: z.string(), open: z.number() }, }) class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { const open = tickets.filter((t) => t.customer === customer && t.status === "open").length; this.log(`Counted ${open} open tickets for ${customer}`); return { customer, open }; } } @Tool({ name: "search_tickets", description: "Search tickets by title", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets], jobs: [CountOpenTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in", customer: "Acme", status: "open" }, { id: "T-2", title: "Invoice total is wrong", customer: "Globex", status: "open" }, { id: "T-3", title: "Login link expired", customer: "Acme", status: "open" }, { id: "T-4", title: "Refund not received", customer: "Acme", status: "closed" }, ]; ``` **Hidden fixture/test file (runs with the example):** ```ts count.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`execute_job` is listed", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("execute_job"); }); test("`count-open-tickets` counts Acme's open tickets", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Acme" } }); expect(result).toBeSuccessful(); expect(result.json()).toMatchObject({ state: "completed", result: { customer: "Acme", open: 2 } }); }); test("it logs the count", async ({ mcp }) => { const run = (await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Globex" } })).json(); expect(run.logs).toEqual([expect.stringMatching(/\] Counted 1 open tickets for Globex$/)]); }); ``` **Hint:** `@App` has a list for jobs next to `tools`. Inside `execute()`, a job writes to its logs with a method it inherits from `JobContext`. **Solution:** `jobs: [CountOpenTickets]` on `@App` registers the job, and with it FrontMCP adds `execute_job` and the other job tools. `this.log()` adds a line to the run's `logs`, and FrontMCP puts the time in front of it. ### Challenge: Say which customer is missing `sync-customer` throws a plain `Error` when the CRM doesn't know the customer. In production, the model would only read "Internal FrontMCP error". Make the call fail with a message the model can act on, one that names the customer id, in production too. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "sync-customer", input: { customerId: "C-1" } } } ``` ```ts sync-customer.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; const crm = new Map([["C-1", { plan: "business" }]]); @Job({ name: "sync-customer", description: "Copy a customer's plan from the CRM into the help desk.", inputSchema: { customerId: z.string() }, outputSchema: { customerId: z.string(), plan: z.string() }, }) export class SyncCustomer extends JobContext { async execute({ customerId }: { customerId: string }) { const customer = crm.get(customerId); if (!customer) throw new Error(`customer lookup returned null for ${customerId}`); return { customerId, plan: customer.plan }; } } ``` **Solution file (alternative to the starter):** ```ts sync-customer.job.ts solution import { Job, JobContext, PublicMcpError, z } from "@frontmcp/sdk"; const crm = new Map([["C-1", { plan: "business" }]]); @Job({ name: "sync-customer", description: "Copy a customer's plan from the CRM into the help desk.", inputSchema: { customerId: z.string() }, outputSchema: { customerId: z.string(), plan: z.string() }, }) export class SyncCustomer extends JobContext { async execute({ customerId }: { customerId: string }) { const customer = crm.get(customerId); if (!customer) throw new PublicMcpError(`There's no customer ${customerId} in the CRM. Check the id with the user.`); return { customerId, plan: customer.plan }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts sync.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("an unknown customer fails with `PUBLIC_ERROR`", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-9" } }); expect(result).toBeError("PUBLIC_ERROR"); }); test("the message names the customer", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-9" } }); expect(result.text()).toContain("C-9"); expect(result.text()).not.toContain("execution failed"); }); test("a known customer still syncs", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-1" } }); expect(result.json().result).toEqual({ customerId: "C-1", plan: "business" }); }); ``` **Hint:** FrontMCP keeps the message of one kind of error in production. It's the same one tools use. **Solution:** A `PublicMcpError` fails `execute_job` with code `PUBLIC_ERROR` and exactly your message, in development and production alike. Any other error becomes `TOOL_EXECUTION_ERROR`, whose message production replaces with "Internal FrontMCP error". The new message also tells the model what to do next: check the id with the user. ### Challenge: Tell the model which jobs exist This server has two jobs, but a model connected to it only sees `execute_job` and four other tools, with nothing that names the jobs. Add `instructions` that say to run jobs with `execute_job`, and name both jobs with the input each one takes. ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { CountOpenTickets, FindSlaBreaches } from "./jobs"; @App({ id: "help-desk", name: "Help Desk", jobs: [FindSlaBreaches, CountOpenTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { App, FrontMcp } from "@frontmcp/sdk"; import { CountOpenTickets, FindSlaBreaches } from "./jobs"; @App({ id: "help-desk", name: "Help Desk", jobs: [FindSlaBreaches, CountOpenTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], instructions: "Help desk jobs, run with execute_job. " + 'find-sla-breaches, input { priority: "high" | "normal" }: lists open tickets past their SLA. ' + "count-open-tickets, input { customer: string }: counts a customer's open tickets.", }) export default class Server {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "find-sla-breaches", inputSchema: { priority: z.enum(["high", "normal"]) }, outputSchema: { breaches: z.array(z.string()) }, }) export class FindSlaBreaches extends JobContext { async execute({ priority }: { priority: "high" | "normal" }) { return { breaches: priority === "high" ? ["T-1"] : [] }; } } @Job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { open: z.number() }, }) export class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { return { open: customer === "Acme" ? 2 : 0 }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts instructions.test.ts hidden import { test, expect } from "@frontmcp/testing"; async function instructions(mcp: any): Promise { const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "server/discover" }); return response.result.instructions ?? ""; } test("the instructions say to use `execute_job`", async ({ mcp }) => { expect(await instructions(mcp)).toContain("execute_job"); }); test("they name `find-sla-breaches` and its `priority`", async ({ mcp }) => { const text = await instructions(mcp); expect(text).toContain("find-sla-breaches"); expect(text).toContain("priority"); }); test("they name `count-open-tickets` and its `customer`", async ({ mcp }) => { const text = await instructions(mcp); expect(text).toContain("count-open-tickets"); expect(text).toContain("customer"); }); ``` **Hint:** `@FrontMcp` has an option for text that describes the server as a whole. Clients read it from `server/discover`. **Solution:** `instructions` is sent with `server/discover`, and clients usually add it to the model's context. It's the one place a model reads about jobs before it calls anything: `tools/list` only shows FrontMCP's generic job tools, and `list_jobs` is hidden from it. Spelling out the allowed values, like `"high" | "normal"`, matters because a job's input errors are hidden in production. --- # Running Jobs in the Background > How to start a FrontMCP job in the background and check on it with get_job_status, what states a run goes through, how to retry a flaky job with backoff, who may read a run, and where runs are stored. Source: https://frontmcp.dev/learn/running-jobs-in-the-background [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Run inline, a job holds its call open until it's done, and a model waits the whole time. With `background: true`, FrontMCP's `execute_job` tool answers at once with a run id, the job keeps working on the server, and `get_job_status` reports on it later. This lesson starts jobs that way, retries the ones that fail now and then, and shows who can read a run afterwards. Under MCP 2026-07-28, that rules out anonymous callers, so the lesson also shows how to get results to them another way. **You will learn** - How to start a job in the background, and read its run with `get_job_status` - What states a run goes through, and what a failed run looks like - How to retry a flaky job with backoff, and what gets retried - Who can read a run, and how to hand results to anonymous callers - Where runs are stored, and how to keep them in Redis > **Note** > > Jobs aren't MCP tasks. A job is FrontMCP's own unit of work, which clients start with the `execute_job` tool and read with `get_job_status`. An MCP task is a protocol feature: a client asks for an ordinary tool call to run as a task, and checks back on it later. FrontMCP supports both; tasks are in [Background tasks](https://frontmcp.dev/reference/server/tasks). ## A job that takes a while Exporting the ticket database reads it a page at a time, and each page takes a fifth of a second. Run inline, the call takes as long as the export. The call in this example starts it in the background instead. Open the **Tests** tab: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "export-tickets", background: true } } ``` ```ts export-tickets.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; import { readPage } from "./database"; @Job({ name: "export-tickets", description: "Export every support ticket as CSV. Reads the database a page at a time, so it takes a while.", inputSchema: {}, outputSchema: { rows: z.number(), csv: z.string() }, }) export class ExportTickets extends JobContext { async execute() { const rows: string[] = []; for (let page = 1; page <= 5; page++) { rows.push(...(await readPage(page))); this.log(`Read page ${page} of 5`); } return { rows: rows.length, csv: ["id,title,status", ...rows].join("\n") }; } } ``` ```ts database.ts // Stands in for a slow database: 5 pages, a fifth of a second each. export async function readPage(page: number) { await new Promise((resolve) => setTimeout(resolve, 200)); return [`T-${page},Ticket ${page},open`]; } ``` ```ts background.test.ts import { test, expect } from "@frontmcp/testing"; test("inline, the call waits for the whole export", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "export-tickets" }); expect(result.json()).toMatchObject({ state: "completed", result: { rows: 5 } }); expect(result.durationMs).toBeGreaterThanOrEqual(1_000); }); test("in the background, the call answers at once with a run id", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "export-tickets", background: true }); expect(result.json()).toEqual({ runId: expect.any(String), state: "pending", uri: expect.stringMatching(/^job:\/\/runs\//) }); expect(result.durationMs).toBeLessThan(200); }); ``` With `background: true`, `execute_job` returns `{ runId, state: "pending", uri }`: no result or logs yet. `uri` names the run resource, `job://runs/{runId}`. The job carries on after the call has returned. A client reads the run later by passing that `runId` to `get_job_status`. ## Who can read a run Copy the `runId` from the Call tab, and call `get_job_status` with it. It fails with `Run "…" not found`, although the run is right there. Open the **Tests** tab: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "export-tickets", background: true } } ``` ```ts status.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; const asNour = { authContext: { user: { sub: "nour" } } }; const asSam = { authContext: { user: { sub: "sam" } } }; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("an anonymous caller can't read the run it started", async ({ mcp }) => { const { runId } = (await mcp.tools.call("execute_job", { name: "export-tickets", background: true })).json(); const status = await mcp.tools.call("get_job_status", { runId }); expect(status).toBeError("INVALID_INPUT"); expect(status.text()).toBe(`Run "${runId}" not found`); }); test("a signed-in caller can read their own run, and nobody else can", async () => { // createDirect() calls the server in-process, as the user you name. const server = await FrontMcpInstance.createDirect(config); const started = await server.callTool("execute_job", { name: "export-tickets", background: true }, asNour); const { runId } = started.structuredContent as { runId: string }; const mine = await server.callTool("get_job_status", { runId }, asNour); await expect(server.callTool("get_job_status", { runId }, asSam)).rejects.toThrow(`Run "${runId}" not found`); await wait(1_200); await server.dispose(); expect(mine.structuredContent).toMatchObject({ runId, jobName: "export-tickets", state: "running" }); }); ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { ExportTickets } from "./export-tickets.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [ExportTickets] }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }; @FrontMcp(config) export default class Server {} ``` ```ts export-tickets.job.ts import { Job, JobContext, z } from "@frontmcp/sdk"; const readPage = async (page: number) => { await new Promise((resolve) => setTimeout(resolve, 200)); return [`T-${page},Ticket ${page},open`]; }; @Job({ name: "export-tickets", description: "Export every support ticket as CSV.", inputSchema: {}, outputSchema: { rows: z.number(), csv: z.string() }, }) export class ExportTickets extends JobContext { async execute() { const rows: string[] = []; for (let page = 1; page <= 5; page++) { rows.push(...(await readPage(page))); this.log(`Read page ${page} of 5`); } return { rows: rows.length, csv: ["id,title,status", ...rows].join("\n") }; } } ``` A run holds the job's input and result, which can be anybody's data, so FrontMCP lets its owner read it, or a caller passing the job's explicit `read` permission rule. It records the caller's token issuer and `sub` with the run, and without an explicit `read` rule, `get_job_status` answers only a caller with both the same issuer and `sub`. Anyone else gets `Run "…" not found` with code `INVALID_INPUT`, exactly what they'd get for a run that doesn't exist, so a run id that leaks tells a stranger nothing. Changed in 1.12.1: before, ownership matched only the subject. Runs stored without an issuer belong only to callers whose tokens have no issuer. See [run ownership](https://frontmcp.dev/reference/sdk/job#who-can-read-a-run). That's where anonymous callers lose out. Under MCP 2026-07-28 [each anonymous request is a new caller](https://frontmcp.dev/learn/authenticating-clients#a-server-anyone-can-call), with a new `anon:` id, so the request that asks for the status is never the one that started the run. The Playground's calls are anonymous, which is why yours failed. The second test calls the server in-process with [`createDirect()`](https://frontmcp.dev/learn/running-frontmcp-anywhere#calling-your-tools-without-a-client-createdirect), as the signed-in user `nour`: she can read her run while it works, and `sam` can't. > **Pitfall: Anonymous callers can't read their runs** > > Without an explicit `read` rule, on a public server under 2026-07-28, `get_job_status` and `get_workflow_status` never find a run for an anonymous caller. The job still runs, and anything it changes still changes; the caller just can't read the result. Either have callers [authenticate](https://frontmcp.dev/learn/authenticating-clients), so each has a `sub` of their own, or give the result another way out, as [further down](https://frontmcp.dev/learn/running-jobs-in-the-background#handing-results-to-anonymous-callers) shows. With `auth: { mode: "static" }`, the caller is derived from the key, so every client that shares a key can read the others' runs, and a client with another key can't. The Playground can't send a key, so that one you'd try on a real server. ## What a run looks like over time For the rest of this lesson, the tests read runs as `nour`. `get_job_status` returns the run's record: ```ts states.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; const asNour = { authContext: { user: { sub: "nour" } } }; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("a run is `running` with no logs, then `completed` with all of them", async () => { const server = await FrontMcpInstance.createDirect(config); const status = async (runId: string) => (await server.callTool("get_job_status", { runId }, asNour)).structuredContent as any; const started = await server.callTool("execute_job", { name: "export-tickets", background: true }, asNour); const { runId } = started.structuredContent as { runId: string }; await wait(500); // two pages in const during = await status(runId); await wait(800); const after = await status(runId); await server.dispose(); expect(during).toEqual({ runId, jobName: "export-tickets", state: "running", startedAt: expect.any(Number), attempt: 1, logs: [] }); expect(after).toMatchObject({ state: "completed", result: { rows: 5 }, attempt: 1, completedAt: expect.any(Number) }); expect(after.logs).toHaveLength(5); expect(after.logs[4]).toMatch(/\] Read page 5 of 5$/); }); ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { ExportTickets } from "./export-tickets.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [ExportTickets] }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }; @FrontMcp(config) export default class Server {} ``` ```ts export-tickets.job.ts import { Job, JobContext, z } from "@frontmcp/sdk"; const readPage = async (page: number) => { await new Promise((resolve) => setTimeout(resolve, 200)); return [`T-${page},Ticket ${page},open`]; }; @Job({ name: "export-tickets", description: "Export every support ticket as CSV.", inputSchema: {}, outputSchema: { rows: z.number(), csv: z.string() }, }) export class ExportTickets extends JobContext { async execute() { const rows: string[] = []; for (let page = 1; page <= 5; page++) { rows.push(...(await readPage(page))); this.log(`Read page ${page} of 5`); } return { rows: rows.length, csv: ["id,title,status", ...rows].join("\n") }; } } ``` | Field | Meaning | | --- | --- | | `runId`, `jobName` | Which run, of which job. | | `state` | Where the run is; see below. | | `result` | What `execute()` returned, once the run has completed. | | `error` | `{ message, name }` of the error, once the run has failed. | | `startedAt`, `completedAt` | Milliseconds since 1970. `completedAt` is set when the run completes or fails. | | `attempt` | Counts attempts, when the job [retries](https://frontmcp.dev/learn/running-jobs-in-the-background#retrying-a-flaky-job). | | `logs` | The `this.log()` lines, **once the run has completed**. Until then it's empty. | A run's `state` is one of: | `state` | When | | --- | --- | | `"pending"` | Created, not started yet. It's what `execute_job` returns for a background run. | | `"running"` | The job is working. | | `"retrying"` | An attempt failed, and the run is waiting to try again. | | `"completed"` | The job returned. `result` is set. | | `"failed"` | The last attempt threw. `error` is set. | | `"timed_out"` | The job exceeded its deadline. | | `"cancelled"` | The caller cancelled the run. | | `"interrupted"` | The runner that owned the run stopped. | The empty `logs` in `during` matter: FrontMCP saves the logs when the run ends, and only if it succeeds. For progress while it runs, call `this.progress()` in the job and read the run resource, `job://runs/{runId}`. Its `progress` field holds the latest update; subscribers receive resource update notifications. ### What about this.progress()? `JobContext` has `this.progress(progress, total, message)`. It records progress on the run and returns `true` when recording succeeds, even without a session. Under 2026-07-28 it sends no session progress notification; read the run resource instead. Changed in 1.11.0: before, with no session it returned `false` and kept no progress on the run: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "export-tickets" } } ``` ```ts main.ts active import { App, FrontMcp, Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "export-tickets", inputSchema: {}, outputSchema: { delivered: z.array(z.boolean()) } }) class ExportTickets extends JobContext { async execute() { const delivered: boolean[] = []; for (let page = 1; page <= 3; page++) { delivered.push(await this.progress(page, 3, `Read page ${page} of 3`)); } return { delivered }; } } @App({ id: "help-desk", name: "Help Desk", jobs: [ExportTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts progress.test.ts import { test, expect } from "@frontmcp/testing"; test("progress is recorded without a session notification", async ({ mcp }) => { const progress = mcp.notifications.collectProgress(); const run = (await mcp.tools.call("execute_job", { name: "export-tickets" })).json(); expect(run.result.delivered).toEqual([true, true, true]); expect(progress.all).toEqual([]); }); ``` Run resources use the same access rules as `get_job_status`. For anonymous callers, keep an application-owned result as in [results for anonymous callers](https://frontmcp.dev/learn/running-jobs-in-the-background#handing-results-to-anonymous-callers). ## Retrying a flaky job The CRM the help desk syncs with drops requests now and then: here, the first two tries for each customer fail. `retry` tells FrontMCP to run the job again when it throws, waiting a little longer each time: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "sync-customer", input: { customerId: "C-1" } } } ``` ```ts sync-customer.job.ts active import { Job, JobContext, PublicMcpError, z } from "@frontmcp/sdk"; import { crm } from "./crm"; @Job({ name: "sync-customer", description: "Copy a customer's plan from the CRM into the help desk.", inputSchema: { customerId: z.string().describe("Customer id, like C-1") }, outputSchema: { customerId: z.string(), plan: z.string() }, retry: { maxAttempts: 3, backoffMs: 200 }, }) export class SyncCustomer extends JobContext { async execute({ customerId }: { customerId: string }) { this.log(`Attempt ${this.attempt}: asking the CRM for ${customerId}`); const customer = await crm.find(customerId); if (!customer) throw new PublicMcpError(`There's no customer ${customerId} in the CRM.`); return { customerId, plan: customer.plan }; } } ``` ```ts crm.ts // Stands in for a CRM that drops the first two requests for each customer. export const requests: Record = {}; export const crm = { async find(id: string) { requests[id] = (requests[id] ?? 0) + 1; if (requests[id] <= 2) throw new Error("CRM timed out"); return id.startsWith("C-4") ? undefined : { id, plan: "business" }; }, }; ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { SyncCustomer } from "./sync-customer.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [SyncCustomer] }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }; @FrontMcp(config) export default class Server {} ``` ```ts retry.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; import { requests } from "./crm"; const asNour = { authContext: { user: { sub: "nour" } } }; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("the third try works, after waiting 200 ms and then 400 ms", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-2" } }); expect(result.json()).toMatchObject({ state: "completed", result: { customerId: "C-2", plan: "business" } }); expect(requests["C-2"]).toBe(3); expect(result.durationMs).toBeGreaterThanOrEqual(600); }); test("only the last attempt's logs are kept", async ({ mcp }) => { const run = (await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-3" } })).json(); expect(run.logs).toEqual([expect.stringMatching(/\] Attempt 3: asking the CRM for C-3$/)]); }); test("between attempts, the run is `retrying`", async () => { const server = await FrontMcpInstance.createDirect(config); const started = await server.callTool("execute_job", { name: "sync-customer", input: { customerId: "C-5" }, background: true }, asNour); const { runId } = started.structuredContent as { runId: string }; await wait(100); const during = (await server.callTool("get_job_status", { runId }, asNour)).structuredContent; await wait(700); const after = (await server.callTool("get_job_status", { runId }, asNour)).structuredContent; await server.dispose(); expect(during).toMatchObject({ state: "retrying", attempt: 1 }); expect(after).toMatchObject({ state: "completed", attempt: 3 }); }); test("a mistake is retried too", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-404" } }); expect(result).toBeError("PUBLIC_ERROR"); expect(requests["C-404"]).toBe(3); }); ``` The first try fails, FrontMCP waits 200 ms, the second fails, it waits 400 ms, and the third works. Take `retry` out and run the tests again: the job runs once, and the call fails with the CRM's first timeout. `retry` takes: | Field | Default | Meaning | | --- | --- | --- | | `maxAttempts` | `3` | How many times to run the job in all, counting the first. | | `backoffMs` | `1000` | How long to wait before the first retry, in milliseconds. | | `backoffMultiplier` | `2` | What each wait is multiplied by for the next one. | | `maxBackoffMs` | `60000` | The longest FrontMCP waits between two attempts. | The defaults apply once `retry` is set, so `retry: {}` means three attempts, waiting 1 and then 2 seconds. Without `retry`, a job runs once. An inline call waits through every retry, so keep `maxAttempts` and the waits small for jobs a model runs inline, and run slow-to-retry jobs in the background. A few things about retries are easy to trip over: - **Public errors are not retried.** Customer `C-404` does not exist, so its `PublicMcpError` fails once. Bad input and invalid output also fail once. Throw a plain `Error` for a failure another attempt could fix. Changed in 1.11.3: before, public errors and bad input were retried. - **Logs are per attempt.** A run keeps the logs of its last attempt only. - **`this.attempt` is the attempt number**, from 1, as the second test's log line shows. (Changed in 1.9.2: before, it was always `1`.) - **Hooks see every attempt.** Each attempt runs the `jobs:execute-job` flow, so a plugin's [`JobHook`](https://frontmcp.dev/reference/sdk/job#hooking-every-attempt-of-a-job) sees each retry and its error, while the caller only hears about the last one. (New in 1.9.4.) > **Pitfall: A retried job runs again from the top** > > Each attempt runs `execute()` from the beginning, so anything the job did before it failed happens again. A job that emails a customer and then fails on the next line emails them once per attempt. Before you add `retry`, make the job safe to run twice: do the part that can fail first, or check whether the work was already done. The [second challenge](https://frontmcp.dev/learn/running-jobs-in-the-background#try-some-challenges) is this bug. ## What a failed run looks like When the last attempt fails, the run's `state` becomes `"failed"`, with the error: ```ts failed.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; const asNour = { authContext: { user: { sub: "nour" } } }; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("a failed run keeps the error, and none of the logs", async () => { const server = await FrontMcpInstance.createDirect(config); const started = await server.callTool("execute_job", { name: "sync-customer", input: { customerId: "C-404" }, background: true }, asNour); const { runId } = started.structuredContent as { runId: string }; await wait(400); const status = (await server.callTool("get_job_status", { runId }, asNour)).structuredContent; await server.dispose(); expect(status).toEqual({ runId, jobName: "sync-customer", state: "failed", error: { message: "There's no customer C-404 in the CRM.", name: "PublicMcpError" }, startedAt: expect.any(Number), completedAt: expect.any(Number), attempt: 1, logs: [], }); }); ``` ```ts sync-customer.job.ts import { Job, JobContext, PublicMcpError, z } from "@frontmcp/sdk"; @Job({ name: "sync-customer", description: "Copy a customer's plan from the CRM into the help desk.", inputSchema: { customerId: z.string() }, outputSchema: { customerId: z.string(), plan: z.string() }, retry: { maxAttempts: 3, backoffMs: 50 }, }) export class SyncCustomer extends JobContext { async execute({ customerId }: { customerId: string }) { this.log(`Asking the CRM for ${customerId}`); if (customerId !== "C-1") throw new PublicMcpError(`There's no customer ${customerId} in the CRM.`); return { customerId, plan: "business" }; } } ``` ```ts main.ts import { App, FrontMcp, LogLevel } from "@frontmcp/sdk"; import { SyncCustomer } from "./sync-customer.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [SyncCustomer] }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], logging: { level: LogLevel.Info }, }; @FrontMcp(config) export default class Server {} ``` - **`error`** has the last attempt's `message`, as thrown, and `name`, the error's class. - **`logs`** is empty: a failed run keeps none of its logs. `this.log()` also writes each line to the server's own log, tagged `[job:sync-customer]`, so that's where to look when a run fails. It writes them at `info`. The Playground runs FrontMCP in a browser, where the level is `Warn` unless you set it, so `main.ts` sets `LogLevel.Info` and the lines show in the **Logs** tab. - **`attempt`** is the number of attempts made. (Changed in 1.9.2: before, it was one less.) ## Handing results to anonymous callers A job can share state with tools, as tools share it with each other: through a [provider](https://frontmcp.dev/learn/sharing-state-with-providers) or a module. So when callers can't read runs, the job can put its result where a tool can read it. The nightly report job saves each day's report, and `get_daily_report` returns it: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "build-daily-report", input: { day: "2026-09-26" }, background: true } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { BuildDailyReport, GetDailyReport, ReportStore } from "./reports"; @App({ id: "help-desk", name: "Help Desk", tools: [GetDailyReport], jobs: [BuildDailyReport], providers: [ReportStore], // one store, for the job and the tool }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts reports.ts import { Job, JobContext, Provider, Tool, ToolContext, z } from "@frontmcp/sdk"; @Provider({ name: "ReportStore" }) export class ReportStore { readonly reports = new Map(); } @Job({ name: "build-daily-report", description: "Count the tickets opened and closed on one day, and save the report.", inputSchema: { day: z.string().describe("The day, like 2026-09-26") }, outputSchema: { day: z.string() }, }) export class BuildDailyReport extends JobContext { async execute({ day }: { day: string }) { await new Promise((resolve) => setTimeout(resolve, 300)); // reading every ticket this.get(ReportStore).reports.set(day, { opened: 12, closed: 9 }); return { day }; } } @Tool({ name: "get_daily_report", description: "Get the ticket report for one day. The build-daily-report job makes it; if it isn't ready, try again in a minute.", inputSchema: { day: z.string().describe("The day, like 2026-09-26") }, annotations: { readOnlyHint: true }, }) export class GetDailyReport extends ToolContext { async execute({ day }: { day: string }) { const report = this.get(ReportStore).reports.get(day); return report ? { day, ready: true, ...report } : { day, ready: false }; } } ``` ```ts report.test.ts import { test, expect } from "@frontmcp/testing"; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("an anonymous caller starts the report, and reads it with the tool", async ({ mcp }) => { await mcp.tools.call("execute_job", { name: "build-daily-report", input: { day: "2026-09-25" }, background: true }); expect((await mcp.tools.call("get_daily_report", { day: "2026-09-25" })).json()).toEqual({ day: "2026-09-25", ready: false }); await wait(400); expect((await mcp.tools.call("get_daily_report", { day: "2026-09-25" })).json()).toEqual({ day: "2026-09-25", ready: true, opened: 12, closed: 9, }); }); ``` Press **Call** with `get_daily_report` and `{ "day": "2026-09-26" }` a moment after the example starts: the report is there. The job and the tool see the same `ReportStore` because it's registered once, on their app. The report is keyed by day, not by run, because a job doesn't know its run's id. Anyone can read it, too, so keep this for results that every caller may see. A job finds providers on its own app and on the server, as a tool does. (Changed in 1.9.2: before, a job only found the server's.) A provider on another app isn't there for it: the [third challenge](https://frontmcp.dev/learn/running-jobs-in-the-background#try-some-challenges) starts from that mistake. ## Where runs are kept Without a shared backend, FrontMCP keeps runs in memory, in the server process. That's what the Playground uses, and it's fine on one machine, with two limits: runs are lost when the server restarts, and a server behind a load balancer only knows the runs it started itself, so `get_job_status` fails whenever the request lands on another instance. For those, keep runs in Redis: ```ts main.ts @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], jobs: { enabled: true, store: { redis: { provider: "redis", host: "redis.internal", port: 6379, password: process.env.REDIS_PASSWORD }, keyPrefix: "help-desk:jobs:", // the default is "mcp:jobs:" }, }, }) export default class Server {} ``` The Playground can't connect to Redis, so this part is for a real server. It was checked on one, with FrontMCP 1.9.4, against a Redis that needs a password. What FrontMCP does with it: - **`enabled: true` is required** once you write a `jobs` option. `jobs: { enabled: false }` turns jobs off: FrontMCP adds none of the job tools, even with jobs registered. - **It needs Node and `ioredis`.** If the Redis client cannot be created, for example because `ioredis` is missing, the job stores warn and fall back to memory. Invalid Redis settings still stop startup. Vercel KV is not supported for job stores. - **It connects the way the server's [`redis`](https://frontmcp.dev/reference/deployment/redis#options) option does**: with `host`, `port`, `password`, `db` and `tls`, or with a `url` such as `redis://:@redis.internal:6379`. Beside a `url`, those fields only fill in what it leaves out, and one that contradicts it stops the server at startup. So does a missing password (`NOAUTH Authentication required.`) or a wrong one (`WRONGPASS invalid username-password pair`). (Changed in 1.9.3: before, only `host` and `port` reached Redis, so a Redis that needs a password or TLS couldn't hold runs.) - **Runs in Redis expire after 24 hours.** Runs in memory stay until the server restarts. The sets FrontMCP keeps beside the runs, `idx:jobId:` and `idx:sessionId:`, expire 24 hours after the last run added to them, and keep the ids of runs that expired before that. A job that runs at least once a day keeps its set, which grows for as long as the job runs. Changed in 1.11.0: before, these sets never expired. > **Note: Runs that no caller starts** > > New in 1.12.0: a workflow with `trigger: "schedule"` starts its own background runs, at the times of a cron expression. Such a run has no owner, so only an explicit `read` rule lets anyone read it, and its id is made from the scheduled time, so instances that share a run store never start the same one twice. [Scheduling Work and Running Workers](https://frontmcp.dev/learn/scheduling-work-and-running-workers) covers it. ## Recap - `execute_job { name, input, background: true }` returns `{ runId, state: "pending", uri }` at once, and the job keeps running. `get_job_status { runId }` returns the run: `state`, `result` or `error`, `attempt`, times and `logs`. - A run goes `pending`, `running`, and `completed` or `failed`, with `retrying` between attempts. Deadlines, cancellation and lost runners can end it as `timed_out`, `cancelled` or `interrupted`. Logs appear only when a run completes; a failed run keeps none. - The caller who started a run, or one passing its explicit `read` rule, can read it. Under 2026-07-28 an anonymous caller is new on every request, so without an explicit `read` rule it cannot read its runs: have callers sign in, or have the job save its result where a tool can read it. - `retry: { maxAttempts, backoffMs, backoffMultiplier, maxBackoffMs }` runs a failed job again, waiting longer each time. Public errors, invalid input or output, authorization denials, cancellations, interruptions and admission timeouts are not retried. Each attempt starts from the top, so make retried jobs safe to run twice. - A job finds providers on its own app and on the server, so a job and a tool can share one. - Runs inherit the server's top-level Redis (except Vercel KV) or SQLite, or use memory when neither is set. Changed in 1.11.0: before, jobs used memory unless `jobs.store` was set. `jobs.store: false` forces memory. `jobs: { enabled: true, store: { redis } }` keeps them in Redis, connected like the server's `redis` option, password and TLS included. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Retry the CRM sync The CRM drops the first two requests for each customer, so `sync-customer` fails every first call. Make FrontMCP try up to 3 times, waiting 100 ms before the first retry and 200 ms before the second. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "sync-customer", input: { customerId: "C-1" } } } ``` ```ts sync-customer.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; import { crm } from "./crm"; @Job({ name: "sync-customer", description: "Copy a customer's plan from the CRM into the help desk.", inputSchema: { customerId: z.string() }, outputSchema: { customerId: z.string(), plan: z.string() }, }) export class SyncCustomer extends JobContext { async execute({ customerId }: { customerId: string }) { const customer = await crm.find(customerId); return { customerId, plan: customer.plan }; } } ``` **Solution file (alternative to the starter):** ```ts sync-customer.job.ts solution import { Job, JobContext, z } from "@frontmcp/sdk"; import { crm } from "./crm"; @Job({ name: "sync-customer", description: "Copy a customer's plan from the CRM into the help desk.", inputSchema: { customerId: z.string() }, outputSchema: { customerId: z.string(), plan: z.string() }, retry: { maxAttempts: 3, backoffMs: 100 }, }) export class SyncCustomer extends JobContext { async execute({ customerId }: { customerId: string }) { const customer = await crm.find(customerId); return { customerId, plan: customer.plan }; } } ``` ```ts crm.ts // Stands in for a CRM that drops the first two requests for each customer. export const requests: Record = {}; export const crm = { async find(id: string) { requests[id] = (requests[id] ?? 0) + 1; if (requests[id] <= 2) throw new Error("CRM timed out"); return { id, plan: "business" }; }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts retry.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { requests } from "./crm"; test("syncing C-2 succeeds on the third try", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-2" } }); expect(result).toBeSuccessful(); expect(result.json().result).toEqual({ customerId: "C-2", plan: "business" }); expect(requests["C-2"]).toBe(3); }); test("the retries wait 100 ms and then 200 ms", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-3" } }); expect(result.durationMs).toBeGreaterThanOrEqual(300); expect(result.durationMs).toBeLessThan(1_000); }); ``` **Hint:** `@Job` has a `retry` option. Its multiplier already doubles each wait, so you only need to set the first one. **Solution:** `retry: { maxAttempts: 3, backoffMs: 100 }` runs the job up to three times. The first wait is `backoffMs`, and each wait after that is multiplied by `backoffMultiplier`, which is `2` by default: 100 ms, then 200 ms. `retry: {}` would also get the sync through, but with the default waits of 1 and 2 seconds, so a model running the job inline would wait three seconds for it. ### Challenge: Send the reminder once `remind-customer` emails a customer about an unpaid invoice, then marks the invoice as reminded in billing. Billing times out on the first try, so the job is retried, and customers get two emails. Fix the job so a successful run sends exactly one email. The retry must stay. Initial call configuration: ```js { tool: "list_outbox", arguments: {} } ``` ```ts remind-customer.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; import { billing, outbox } from "./services"; @Job({ name: "remind-customer", description: "Email a customer about an unpaid invoice, and record that they were reminded.", inputSchema: { invoiceId: z.string() }, outputSchema: { invoiceId: z.string(), reminded: z.boolean() }, retry: { maxAttempts: 3, backoffMs: 50 }, }) export class RemindCustomer extends JobContext { async execute({ invoiceId }: { invoiceId: string }) { outbox.push(`Invoice ${invoiceId} is still unpaid.`); await billing.markReminded(invoiceId); return { invoiceId, reminded: true }; } } ``` **Solution file (alternative to the starter):** ```ts remind-customer.job.ts solution import { Job, JobContext, z } from "@frontmcp/sdk"; import { billing, outbox } from "./services"; @Job({ name: "remind-customer", description: "Email a customer about an unpaid invoice, and record that they were reminded.", inputSchema: { invoiceId: z.string() }, outputSchema: { invoiceId: z.string(), reminded: z.boolean() }, retry: { maxAttempts: 3, backoffMs: 50 }, }) export class RemindCustomer extends JobContext { async execute({ invoiceId }: { invoiceId: string }) { await billing.markReminded(invoiceId); // the part that can fail goes first outbox.push(`Invoice ${invoiceId} is still unpaid.`); return { invoiceId, reminded: true }; } } ``` ```ts services.ts import { Tool, ToolContext } from "@frontmcp/sdk"; export const outbox: string[] = []; const attempts: Record = {}; // Stands in for billing: the first request for each invoice times out. export const billing = { async markReminded(invoiceId: string) { attempts[invoiceId] = (attempts[invoiceId] ?? 0) + 1; if (attempts[invoiceId] === 1) throw new Error("billing timed out"); }, }; @Tool({ name: "list_outbox", description: "List the emails sent to customers.", inputSchema: {} }) export class ListOutbox extends ToolContext { async execute() { return { emails: outbox }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts remind.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the reminder succeeds despite billing's first timeout", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "remind-customer", input: { invoiceId: "INV-7" } }); expect(result.json()).toMatchObject({ state: "completed", result: { invoiceId: "INV-7", reminded: true } }); }); test("the customer gets exactly one email", async ({ mcp }) => { await mcp.tools.call("execute_job", { name: "remind-customer", input: { invoiceId: "INV-8" } }); const { emails } = (await mcp.tools.call("list_outbox", {})).json(); expect(emails.filter((e: string) => e.includes("INV-8"))).toHaveLength(1); }); ``` **Hint:** Each attempt runs `execute()` from the top. Which line runs on every attempt, even the ones that fail? **Solution:** The email went out before the call to billing, so every attempt that billing failed had already sent one. Calling billing first means a failed attempt has sent nothing, and the email goes out once, on the attempt that gets past billing. When a job has two side effects, put the one that can fail first, or check whether the work was already done before doing it again. ### Challenge: Let the job find the report store `build-daily-report` should save each day's report in `ReportStore`, for `get_daily_report` to return. The job is in the help desk's app, and the tool in the reporting team's. But the job fails, and the report never appears. Fix it so that after the job runs, the tool returns the report. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "build-daily-report", input: { day: "2026-09-26" } } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { BuildDailyReport, GetDailyReport, ReportStore } from "./reports"; @App({ id: "help-desk", name: "Help Desk", jobs: [BuildDailyReport] }) class HelpDeskApp {} @App({ id: "reports", name: "Reports", tools: [GetDailyReport], providers: [ReportStore] }) class ReportsApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp, ReportsApp], }) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { App, FrontMcp } from "@frontmcp/sdk"; import { BuildDailyReport, GetDailyReport, ReportStore } from "./reports"; @App({ id: "help-desk", name: "Help Desk", jobs: [BuildDailyReport] }) class HelpDeskApp {} @App({ id: "reports", name: "Reports", tools: [GetDailyReport] }) class ReportsApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp, ReportsApp], providers: [ReportStore], // on the server, for both apps }) export default class Server {} ``` ```ts reports.ts import { Job, JobContext, Provider, Tool, ToolContext, z } from "@frontmcp/sdk"; @Provider({ name: "ReportStore" }) export class ReportStore { readonly reports = new Map(); } @Job({ name: "build-daily-report", description: "Count the tickets opened and closed on one day, and save the report.", inputSchema: { day: z.string() }, outputSchema: { day: z.string() }, }) export class BuildDailyReport extends JobContext { async execute({ day }: { day: string }) { this.get(ReportStore).reports.set(day, { opened: 12, closed: 9 }); return { day }; } } @Tool({ name: "get_daily_report", description: "Get the ticket report for one day, if the build-daily-report job has made it.", inputSchema: { day: z.string() }, annotations: { readOnlyHint: true }, }) export class GetDailyReport extends ToolContext { async execute({ day }: { day: string }) { const report = this.get(ReportStore).reports.get(day); return report ? { day, ready: true, ...report } : { day, ready: false }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts report.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`build-daily-report` completes", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "build-daily-report", input: { day: "2026-09-25" } }); expect(result).toBeSuccessful(); }); test("`get_daily_report` returns the report the job saved", async ({ mcp }) => { await mcp.tools.call("execute_job", { name: "build-daily-report", input: { day: "2026-09-24" } }); const report = (await mcp.tools.call("get_daily_report", { day: "2026-09-24" })).json(); expect(report).toEqual({ day: "2026-09-24", ready: true, opened: 12, closed: 9 }); }); ``` **Hint:** Read the error in the Call tab. Where does a job look for providers, and where is `ReportStore`? **Solution:** A job's `this.get()` finds providers on its own app and on the server. `ReportStore` was on the `reports` app, which only that app's tools and jobs see, so the job failed with `Provider "ReportStore" is not available`. Registered on the server, it's one instance that both apps find, so the tool returns what the job saved. Putting the job and the tool in one app, with the store, works too. --- # Chaining Jobs into Workflows > How to chain FrontMCP jobs into a workflow with @Workflow, pass each step's output to the next, run independent steps in parallel, and decide what a failing step does to the rest. Source: https://frontmcp.dev/learn/chaining-jobs-into-workflows [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 The help desk's nightly report is three jobs: collect the day's tickets, find the ones that broke their SLA, and write the report. A model could run them one by one with `execute_job`, copying each result into the next call. A **workflow** does that on the server: it names the jobs, says which ones need which, and says what each one gets as input. FrontMCP runs the steps in order, runs the ones that don't depend on each other at the same time, and returns what every step produced. **You will learn** - How to declare a workflow with `@Workflow` and `steps`, and run it with `execute_workflow` - How to pass one step's output to the next - Which steps run at the same time, and what `maxConcurrency` does - What a failing step does to the rest, and how to change it with `retry`, `continueOnError` and `condition` - How to run a workflow in the background, and read its steps afterwards ## One job at a time With three jobs and no workflow, the report takes three round trips through the model. It calls `execute_job` for `collect-tickets`, reads the list of tickets, copies all of it into a call to `check-sla`, then copies the day, the count and the breaches into a call to `write-report`. Every ticket passes through the model's context twice, the model can copy something wrong at each step, and nothing happens on the server while the model is thinking. And if the report should be written every night, there may be no model around at all. ## Declaring a workflow `@Workflow` lists the steps. Each step runs one job, and says which steps it depends on and where its input comes from. Open the **Tests** tab: Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: { day: "2026-09-26" } } } ``` ```ts nightly-report.workflow.ts active import { Workflow } from "@frontmcp/sdk"; import type { Ticket } from "./store"; @Workflow({ name: "nightly-ticket-report", description: "Collect a day's tickets, find the ones that broke their SLA, and write the report.", steps: [ // No `input`: the step gets the workflow's input, { day }. { id: "collect", jobName: "collect-tickets" }, { id: "breaches", jobName: "check-sla", dependsOn: ["collect"], input: (steps) => ({ tickets: steps.get("collect").outputs.tickets }), }, { id: "report", jobName: "write-report", dependsOn: ["collect", "breaches"], input: (steps) => ({ day: steps.get("collect").outputs.day, total: (steps.get("collect").outputs.tickets as Ticket[]).length, breaches: steps.get("breaches").outputs.breaches, }), }, ], }) export class NightlyTicketReport {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; import { ticketsByDay, type Ticket } from "./store"; const ticket = z.object({ id: z.string(), priority: z.enum(["high", "normal"]), hoursToFirstReply: z.number() }); const SLA_HOURS = { high: 4, normal: 24 }; @Job({ name: "collect-tickets", description: "Collect the tickets opened on one day.", inputSchema: { day: z.string().describe("The day, like 2026-09-26") }, outputSchema: { day: z.string(), tickets: z.array(ticket) }, }) export class CollectTickets extends JobContext { async execute({ day }: { day: string }) { const tickets = ticketsByDay[day] ?? []; this.log(`Collected ${tickets.length} tickets for ${day}`); return { day, tickets }; } } @Job({ name: "check-sla", description: "Find the tickets whose first reply came later than their SLA allows.", inputSchema: { tickets: z.array(ticket) }, outputSchema: { breaches: z.array(z.string()) }, }) export class CheckSla extends JobContext { async execute({ tickets }: { tickets: Ticket[] }) { return { breaches: tickets.filter((t) => t.hoursToFirstReply > SLA_HOURS[t.priority]).map((t) => t.id) }; } } @Job({ name: "write-report", description: "Write the nightly SLA report.", inputSchema: { day: z.string(), total: z.number(), breaches: z.array(z.string()) }, outputSchema: { report: z.string() }, }) export class WriteReport extends JobContext { async execute({ day, total, breaches }: { day: string; total: number; breaches: string[] }) { const which = breaches.length ? `: ${breaches.join(", ")}` : ""; return { report: `${day}: ${breaches.length} of ${total} tickets broke their SLA${which}.` }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { CheckSla, CollectTickets, WriteReport } from "./jobs"; import { NightlyTicketReport } from "./nightly-report.workflow"; @App({ id: "help-desk", name: "Help Desk", jobs: [CollectTickets, CheckSla, WriteReport], workflows: [NightlyTicketReport], }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts store.ts export type Ticket = { id: string; priority: "high" | "normal"; hoursToFirstReply: number }; export const ticketsByDay: Record = { "2026-09-26": [ { id: "T-1", priority: "high", hoursToFirstReply: 6 }, { id: "T-2", priority: "normal", hoursToFirstReply: 30 }, { id: "T-3", priority: "high", hoursToFirstReply: 2 }, { id: "T-4", priority: "normal", hoursToFirstReply: 5 }, ], "2026-09-27": [{ id: "T-5", priority: "normal", hoursToFirstReply: 3 }], }; ``` ```ts report.test.ts import { test, expect } from "@frontmcp/testing"; test("the report names the tickets that broke their SLA", async ({ mcp }) => { const run = await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: { day: "2026-09-26" } }); expect(run).toBeSuccessful(); expect(run.json()).toMatchObject({ runId: expect.any(String), state: "completed", result: { workflowName: "nightly-ticket-report", state: "completed", stepResults: { collect: { state: "completed", outputs: { day: "2026-09-26" } }, breaches: { state: "completed", outputs: { breaches: ["T-1", "T-2"] } }, report: { state: "completed", outputs: { report: "2026-09-26: 2 of 4 tickets broke their SLA: T-1, T-2." } }, }, }, }); }); test("a day without breaches, and no logs in the result", async ({ mcp }) => { const run = (await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: { day: "2026-09-27" } })).json(); expect(run.result.stepResults.report.outputs.report).toBe("2026-09-27: 0 of 1 tickets broke their SLA."); expect(run.logs).toBeUndefined(); }); ``` Change `day` in the Call tab to `2026-09-27` and call it again. Each step takes: | Field | What it does | | --- | --- | | `id` | The step's name within this workflow. Other steps use it in `dependsOn` and `steps.get()`. | | `jobName` | The name of the job the step runs. If no job has that name, the step fails when the workflow runs. | | `dependsOn` | The steps that must be done before this one starts. Without it, the step starts right away. | | `input` | What the job gets. See [below](https://frontmcp.dev/learn/chaining-jobs-into-workflows#passing-data-between-steps). | | `retry`, `timeout` | Override the job's own. See [When a step fails](https://frontmcp.dev/learn/chaining-jobs-into-workflows#when-a-step-fails) and [Timeouts](https://frontmcp.dev/learn/chaining-jobs-into-workflows#timeouts). | | `continueOnError`, `condition` | Let a step fail, or skip it. See [Optional steps](https://frontmcp.dev/learn/chaining-jobs-into-workflows#optional-steps). | A workflow is registered like a job, with `workflows: [...]` on `@App`, and its jobs go in `jobs`. (Most examples below leave `main.ts` out, and the Playground registers their jobs and workflows for you.) The class itself stays empty: everything is in the decorator. A client runs it with `execute_workflow`, which takes `name`, `input` and `background`, like `execute_job`, and answers with the run: ```json { "runId": "0c8f1a52-…", "state": "completed", "result": { "workflowName": "nightly-ticket-report", "state": "completed", "stepResults": { "collect": { "outputs": { "day": "2026-09-26", "tickets": [/* … */] }, "state": "completed" }, "breaches": { "outputs": { "breaches": ["T-1", "T-2"] }, "state": "completed" }, "report": { "outputs": { "report": "2026-09-26: 2 of 4 tickets broke their SLA: T-1, T-2." }, "state": "completed" } }, "startedAt": 1790467200000, "completedAt": 1790467200004 } } ``` `stepResults` has every step's `outputs`, what its job returned, and its `state`. There are no logs: the steps' `this.log()` lines only go to the server's log. So the model gets the whole report in one call, and so does a client that runs the workflow every night with no model involved. ## Passing data between steps A step's `input` can be three things: | `input` | The job gets | | --- | --- | | Left out | The workflow's input: the `input` passed to `execute_workflow`, or `{}`. | | An object | That object, on every run. | | A function | What the function returns. FrontMCP calls it just before the step starts, with `(steps, input)`. | `steps.get(id)` returns a finished step's `{ outputs, state }`. An input function also receives the parsed workflow input as its second argument. The workflow's `inputSchema` is checked before any step starts; each job checks its own input too. Changed in 1.11.3: before, workflow input was not validated or passed to input functions. > **Pitfall: Depend on every step you read** > > `steps.get()` only knows steps that have finished. If `report` reads `breaches` but only lists `collect` in `dependsOn`, the two start together as soon as `collect` is done, and `report`'s input function runs before `breaches` has an answer: > > Initial call configuration: > > ```js > { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: { day: "2026-09-26" } } } > ``` > > ```ts nightly-report.workflow.ts active > import { Workflow } from "@frontmcp/sdk"; > > @Workflow({ > name: "nightly-ticket-report", > steps: [ > { id: "collect", jobName: "collect-tickets" }, > { id: "breaches", jobName: "check-sla", dependsOn: ["collect"], input: (steps) => ({ tickets: steps.get("collect").outputs.tickets }) }, > { > id: "report", > jobName: "write-report", > dependsOn: ["collect"], // 🚩 reads "breaches" too > input: (steps) => ({ breaches: steps.get("breaches").outputs.breaches }), > }, > ], > }) > export class NightlyTicketReport {} > ``` > > ```ts jobs.ts > import { Job, JobContext, z } from "@frontmcp/sdk"; > > @Job({ name: "collect-tickets", inputSchema: { day: z.string() }, outputSchema: { tickets: z.array(z.string()) } }) > export class CollectTickets extends JobContext { > async execute({ day }: { day: string }) { > return { tickets: ["T-1", "T-2", "T-3"] }; > } > } > > @Job({ name: "check-sla", inputSchema: { tickets: z.array(z.string()) }, outputSchema: { breaches: z.array(z.string()) } }) > export class CheckSla extends JobContext { > async execute({ tickets }: { tickets: string[] }) { > return { breaches: tickets.slice(0, 1) }; > } > } > > @Job({ name: "write-report", inputSchema: { breaches: z.array(z.string()) }, outputSchema: { report: z.string() } }) > export class WriteReport extends JobContext { > async execute({ breaches }: { breaches: string[] }) { > return { report: `${breaches.length} tickets broke their SLA.` }; > } > } > ``` > > ```ts depends.test.ts > import { test, expect } from "@frontmcp/testing"; > > test("a step that reads a step it doesn't depend on fails", async ({ mcp }) => { > const run = (await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: { day: "2026-09-26" } })).json(); > expect(run.state).toBe("failed"); > expect(run.result.stepResults.breaches.state).toBe("completed"); > expect(run.result.stepResults.report).toEqual({ outputs: {}, state: "failed" }); > }); > ``` > > `report` fails, and the result doesn't say why. The reason is only in the server's log (the **Logs** tab): `Step "breaches" has not completed yet or does not exist`. Add `"breaches"` to `dependsOn` and it works. ## Steps that run at the same time Steps that don't depend on each other don't wait for each other. The report now also counts tickets per customer, which has nothing to do with the SLA check, so both depend only on `collect` and run side by side. Paging the on-call agent needs the breaches, and nothing else: Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: { day: "2026-09-26" } } } ``` ```ts nightly-report.workflow.ts active import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "collect", jobName: "collect-tickets" }, { id: "breaches", jobName: "check-sla", dependsOn: ["collect"] }, // 100 ms { id: "customers", jobName: "count-by-customer", dependsOn: ["collect"] }, // 300 ms { id: "page", jobName: "page-on-call", dependsOn: ["breaches"] }, { id: "report", jobName: "write-report", dependsOn: ["breaches", "customers"] }, ], }) export class NightlyTicketReport {} @Workflow({ name: "one-at-a-time", maxConcurrency: 1, steps: [ { id: "breaches", jobName: "check-sla" }, { id: "customers", jobName: "count-by-customer" }, ], }) export class OneAtATime {} ``` ```ts jobs.ts import { Job, JobContext } from "@frontmcp/sdk"; import { work } from "./timeline"; // Each job records when it starts and ends, and takes as long as its real work would. @Job({ name: "collect-tickets", inputSchema: {}, outputSchema: {} }) export class CollectTickets extends JobContext { async execute() { await work("collect-tickets", 10); return {}; } } @Job({ name: "check-sla", inputSchema: {}, outputSchema: {} }) export class CheckSla extends JobContext { async execute() { await work("check-sla", 100); return {}; } } @Job({ name: "count-by-customer", inputSchema: {}, outputSchema: {} }) export class CountByCustomer extends JobContext { async execute() { await work("count-by-customer", 300); return {}; } } @Job({ name: "page-on-call", inputSchema: {}, outputSchema: {} }) export class PageOnCall extends JobContext { async execute() { await work("page-on-call", 10); return {}; } } @Job({ name: "write-report", inputSchema: {}, outputSchema: {} }) export class WriteReport extends JobContext { async execute() { await work("write-report", 10); return {}; } } ``` ```ts timeline.ts export const timeline: string[] = []; export async function work(job: string, ms: number) { timeline.push(`start ${job}`); await new Promise((resolve) => setTimeout(resolve, ms)); timeline.push(`end ${job}`); } ``` ```ts parallel.test.ts import { test, expect } from "@frontmcp/testing"; import { timeline } from "./timeline"; test("steps run in batches", async ({ mcp }) => { timeline.length = 0; const run = await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: {} }); const at = (event: string) => timeline.indexOf(event); // check-sla and count-by-customer run at the same time... expect(at("start count-by-customer")).toBeLessThan(at("end check-sla")); // ...so the whole run takes about 300 ms, not 400. expect(run.durationMs).toBeLessThan(400); // 🚩 page-on-call only needs check-sla, but waits for count-by-customer too. expect(at("start page-on-call")).toBeGreaterThan(at("end count-by-customer")); }); test("with `maxConcurrency: 1`, steps run one at a time, in order", async ({ mcp }) => { timeline.length = 0; await mcp.tools.call("execute_workflow", { name: "one-at-a-time", input: {} }); expect(timeline).toEqual(["start check-sla", "end check-sla", "start count-by-customer", "end count-by-customer"]); }); ``` FrontMCP runs a workflow in **batches**. It takes every step whose `dependsOn` are all done, starts up to `maxConcurrency` of them at once (5 by default), and waits until the whole batch has finished before it looks for the next steps. So `check-sla` and `count-by-customer` overlap, and the run takes about 300 ms instead of 400. But `page-on-call` could start after 100 ms, when `check-sla` is done, and instead it waits for `count-by-customer`: a batch is as slow as its slowest step. `maxConcurrency` on `@Workflow` caps the batch. Steps beyond it wait for the next batch, in the order you declared them, and `maxConcurrency: 1` runs the steps one at a time. Lower it when the steps share something that can't take much at once, like a rate-limited API. ## When a step fails The pager service is down tonight, so `page-on-call` fails. Two steps come after it: marking the late tickets as escalated, and emailing their customers that they were. Without a retry policy, each step runs once: Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: {} } } ``` ```ts nightly-report.workflow.ts active import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "breaches", jobName: "check-sla" }, { id: "page", jobName: "page-on-call", dependsOn: ["breaches"] }, { id: "escalate", jobName: "mark-escalated", dependsOn: ["page"] }, { id: "email", jobName: "email-customers", dependsOn: ["escalate"] }, { id: "report", jobName: "write-report", dependsOn: ["breaches"] }, ], }) export class NightlyTicketReport {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; export const pagerCalls: string[] = []; export const outbox: string[] = []; @Job({ name: "check-sla", inputSchema: {}, outputSchema: { breaches: z.array(z.string()) } }) export class CheckSla extends JobContext { async execute() { return { breaches: ["T-1", "T-2"] }; } } @Job({ name: "page-on-call", inputSchema: {}, outputSchema: { paged: z.string() } }) export class PageOnCall extends JobContext { async execute() { pagerCalls.push(new Date().toISOString()); throw new Error("Pager service unavailable"); } } @Job({ name: "mark-escalated", inputSchema: {}, outputSchema: { escalated: z.number() } }) export class MarkEscalated extends JobContext { async execute() { return { escalated: 2 }; } } @Job({ name: "email-customers", inputSchema: {}, outputSchema: { sent: z.number() } }) export class EmailCustomers extends JobContext { async execute() { outbox.push("Your ticket was escalated to our on-call agent."); return { sent: 1 }; } } @Job({ name: "write-report", inputSchema: {}, outputSchema: { report: z.string() } }) export class WriteReport extends JobContext { async execute() { return { report: "2 tickets broke their SLA." }; } } ``` ```ts failure.test.ts import { test, expect } from "@frontmcp/testing"; import { outbox, pagerCalls } from "./jobs"; test("what one failed step does to the rest", async ({ mcp }) => { pagerCalls.length = 0; outbox.length = 0; const call = await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: {} }); // The call succeeds; the run inside it failed. expect(call).toBeSuccessful(); const run = call.json(); expect(run.state).toBe("failed"); // page-on-call runs once, and the error is only in the server log. expect(pagerCalls).toHaveLength(1); expect(call.durationMs).toBeLessThan(1000); expect(run.result.stepResults.page).toEqual({ outputs: {}, state: "failed" }); // The step that depends on it is skipped, and the ones that don't depend on it still run. expect(run.result.stepResults.escalate.state).toBe("skipped"); expect(run.result.stepResults.report.state).toBe("completed"); // Failure skips indirect dependents too. expect(run.result.stepResults.email.state).toBe("skipped"); expect(outbox).toHaveLength(0); }); ``` The run shows how failures travel through dependencies: - **The step ran once.** Neither the step nor its job has a `retry` policy. - **The failed step's direct dependents were skipped.** `escalate` never ran, and its state is `"skipped"`. - **Everything else ran.** `report` doesn't depend on `page`, so the report was written. - **The workflow failed, but the call didn't.** `execute_workflow` returned normally, with `state: "failed"` in the run. A client has to check `state`, not just whether the call succeeded. - **The reason is gone.** A failed step's result is `{ outputs: {}, state: "failed" }`, whatever went wrong. `Pager service unavailable` is only in the server's log. - **`email` was skipped too.** It depends on `escalate`, which was skipped because of the failure. Changed in 1.11.3: before, a step without `retry` ran three times, and only direct dependents of a failure were skipped. You can still list all prerequisites explicitly and set `maxAttempts: 1` to override a job's retry policy: Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: {} } } ``` ```ts nightly-report.workflow.ts active import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "breaches", jobName: "check-sla" }, { id: "page", jobName: "page-on-call", dependsOn: ["breaches"], retry: { maxAttempts: 1 } }, // ✅ fail at once { id: "escalate", jobName: "mark-escalated", dependsOn: ["page"] }, { id: "email", jobName: "email-customers", dependsOn: ["page", "escalate"] }, // ✅ needs both to succeed { id: "report", jobName: "write-report", dependsOn: ["breaches"] }, ], }) export class NightlyTicketReport {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; export const pagerCalls: string[] = []; export const outbox: string[] = []; @Job({ name: "check-sla", inputSchema: {}, outputSchema: { breaches: z.array(z.string()) } }) export class CheckSla extends JobContext { async execute() { return { breaches: ["T-1", "T-2"] }; } } @Job({ name: "page-on-call", inputSchema: {}, outputSchema: { paged: z.string() } }) export class PageOnCall extends JobContext { async execute() { pagerCalls.push(new Date().toISOString()); throw new Error("Pager service unavailable"); } } @Job({ name: "mark-escalated", inputSchema: {}, outputSchema: { escalated: z.number() } }) export class MarkEscalated extends JobContext { async execute() { return { escalated: 2 }; } } @Job({ name: "email-customers", inputSchema: {}, outputSchema: { sent: z.number() } }) export class EmailCustomers extends JobContext { async execute() { outbox.push("Your ticket was escalated to our on-call agent."); return { sent: 1 }; } } @Job({ name: "write-report", inputSchema: {}, outputSchema: { report: z.string() } }) export class WriteReport extends JobContext { async execute() { return { report: "2 tickets broke their SLA." }; } } ``` ```ts failure.test.ts import { test, expect } from "@frontmcp/testing"; import { outbox, pagerCalls } from "./jobs"; test("the pager is tried once, and no customer is emailed", async ({ mcp }) => { pagerCalls.length = 0; outbox.length = 0; const call = await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: {} }); const { stepResults } = call.json().result; expect(pagerCalls).toHaveLength(1); expect(call.durationMs).toBeLessThan(500); expect(stepResults.escalate.state).toBe("skipped"); expect(stepResults.email.state).toBe("skipped"); expect(outbox).toEqual([]); expect(stepResults.report.state).toBe("completed"); }); ``` A step's `retry` takes the same fields as a [job's](https://frontmcp.dev/learn/running-jobs-in-the-background#retrying-a-flaky-job), and replaces the job's own for that step. Without a step or job policy, the job runs once. ## Optional steps Two options make a step optional, in different ways: - **`continueOnError: true`** lets a step fail without failing the workflow. Its state is still `"failed"`, but its dependents run, and the workflow can complete. - **`condition: (steps) => boolean`** decides whether a step runs at all. It's called with `steps` once the step's `dependsOn` are done, and when it returns `false` the step is `"skipped"`. Posting the report to the team's chat is nice to have, and the chat service is down. Paging on-call only makes sense when something broke: Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: { day: "2026-09-27" } } } ``` ```ts nightly-report.workflow.ts active import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "breaches", jobName: "check-sla" }, { id: "page", jobName: "page-on-call", dependsOn: ["breaches"], condition: (steps) => (steps.get("breaches").outputs.breaches as string[]).length > 0, input: (steps) => ({ tickets: steps.get("breaches").outputs.breaches }), }, { id: "report", jobName: "write-report", dependsOn: ["breaches", "page"], input: (steps) => ({ breaches: steps.get("breaches").outputs.breaches, paged: steps.get("page").state === "completed" }), }, { id: "post", jobName: "post-to-chat", dependsOn: ["report"], input: (steps) => ({ text: steps.get("report").outputs.report }), continueOnError: true, retry: { maxAttempts: 1 }, }, ], }) export class NightlyTicketReport {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; const breachesByDay: Record = { "2026-09-26": ["T-1", "T-2"], "2026-09-27": [] }; export const pages: string[][] = []; @Job({ name: "check-sla", inputSchema: { day: z.string() }, outputSchema: { breaches: z.array(z.string()) } }) export class CheckSla extends JobContext { async execute({ day }: { day: string }) { return { breaches: breachesByDay[day] ?? [] }; } } @Job({ name: "page-on-call", inputSchema: { tickets: z.array(z.string()) }, outputSchema: { paged: z.boolean() } }) export class PageOnCall extends JobContext { async execute({ tickets }: { tickets: string[] }) { pages.push(tickets); return { paged: true }; } } @Job({ name: "write-report", inputSchema: { breaches: z.array(z.string()), paged: z.boolean() }, outputSchema: { report: z.string() }, }) export class WriteReport extends JobContext { async execute({ breaches, paged }: { breaches: string[]; paged: boolean }) { return { report: `${breaches.length} tickets broke their SLA. On-call was ${paged ? "" : "not "}paged.` }; } } @Job({ name: "post-to-chat", inputSchema: { text: z.string() }, outputSchema: { posted: z.boolean() } }) export class PostToChat extends JobContext { async execute() { throw new Error("Chat service unavailable"); } } ``` ```ts optional.test.ts import { test, expect } from "@frontmcp/testing"; import { pages } from "./jobs"; const run = async (mcp: any, day: string) => (await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: { day } })).json(); test("with no breaches, on-call isn't paged, and the report still runs", async ({ mcp }) => { pages.length = 0; const { state, result } = await run(mcp, "2026-09-27"); expect(state).toBe("completed"); expect(result.stepResults.page).toEqual({ outputs: {}, state: "skipped" }); expect(result.stepResults.report.outputs.report).toBe("0 tickets broke their SLA. On-call was not paged."); expect(pages).toEqual([]); }); test("with breaches, on-call is paged", async ({ mcp }) => { const { result } = await run(mcp, "2026-09-26"); expect(result.stepResults.page.state).toBe("completed"); expect(result.stepResults.report.outputs.report).toBe("2 tickets broke their SLA. On-call was paged."); }); test("a failed chat post doesn't fail the workflow", async ({ mcp }) => { const { state, result } = await run(mcp, "2026-09-26"); expect(result.stepResults.post.state).toBe("failed"); expect(state).toBe("completed"); }); ``` `report` depends on `page`, which is skipped on a quiet night, and runs anyway: a skipped step, when a `condition` skipped it, counts as done for the steps after it. So a step after an optional one has to handle both cases. `report` does that in its input function: `steps.get("page").state` is `"completed"`, `"failed"` or `"skipped"`. ## Timeouts A step can't run forever. It gets the job's `timeout`, `jobs.defaultTimeoutMs` (5 minutes) unless the job sets one, or the step's own `timeout`, and when that runs out the step fails. The job's signal aborts when the deadline passes. Work that ignores the signal keeps going. Changed in 1.11.0: before, only workflow steps enforced the job's timeout. `execute_job` now does too: Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-export" } } ``` ```ts export.ts active import { Job, JobContext, Workflow, z } from "@frontmcp/sdk"; export const exports: string[] = []; @Job({ name: "export-tickets", description: "Export every ticket as CSV.", inputSchema: {}, outputSchema: { rows: z.number() }, timeout: 200, }) export class ExportTickets extends JobContext { async execute() { await new Promise((resolve) => setTimeout(resolve, 500)); // takes longer than its timeout exports.push(new Date().toISOString()); return { rows: 5 }; } } @Workflow({ name: "nightly-export", steps: [{ id: "export", jobName: "export-tickets", retry: { maxAttempts: 1 } }], }) export class NightlyExport {} ``` ```ts timeout.test.ts import { test, expect } from "@frontmcp/testing"; import { exports } from "./export"; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("as a step, the job fails after 200 ms, and keeps running", async ({ mcp }) => { exports.length = 0; const call = await mcp.tools.call("execute_workflow", { name: "nightly-export" }); expect(call.json().result.stepResults.export).toEqual({ outputs: {}, state: "failed" }); expect(call.durationMs).toBeLessThan(400); await wait(400); expect(exports).toHaveLength(1); }); test("execute_job enforces the timeout too", async ({ mcp }) => { const call = await mcp.tools.call("execute_job", { name: "export-tickets" }); expect(call).toBeError("JOB_TIMEOUT"); expect(call.durationMs).toBeLessThan(450); }); ``` Since a timed-out job isn't stopped, a step with a `timeout` and a `retry` can start its next attempt while the last one is still running. As with [retries](https://frontmcp.dev/learn/running-jobs-in-the-background#retrying-a-flaky-job), make such a job safe to run twice. ## Running a workflow in the background `execute_workflow` takes `background: true`, like `execute_job`, and returns `{ runId, state: "pending" }` at once. The same rule decides who can read the run: [the owner or a caller passing an explicit `read` rule](https://frontmcp.dev/learn/running-jobs-in-the-background#who-can-read-a-run). Without that rule, under 2026-07-28 anonymous callers cannot read their runs. Also, reading it with `get_workflow_status` leaves out the steps: Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: { day: "2026-09-26" }, background: true } } ``` ```ts status.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; const asNour = { authContext: { user: { sub: "nour" } } }; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("get_workflow_status has no steps; get_job_status has them all", async () => { const server = await FrontMcpInstance.createDirect(config); const started = await server.callTool("execute_workflow", { name: "nightly-ticket-report", input: { day: "2026-09-26" }, background: true }, asNour); const { runId } = started.structuredContent as { runId: string }; await wait(100); const workflowStatus = (await server.callTool("get_workflow_status", { runId }, asNour)).structuredContent; const jobStatus = (await server.callTool("get_job_status", { runId }, asNour)).structuredContent as any; await server.dispose(); expect(workflowStatus).toMatchObject({ runId, workflowName: "nightly-ticket-report", state: "completed", stepResults: {} }); expect(jobStatus).toMatchObject({ runId, jobName: "nightly-ticket-report", state: "completed" }); expect(jobStatus.result.stepResults.report.outputs).toEqual({ report: "2026-09-26: 2 tickets broke their SLA." }); }); test("a webhook workflow can also be called manually", async ({ mcp }) => { const { workflows } = (await mcp.tools.call("list_workflows", {})).json(); expect(workflows).toEqual([expect.objectContaining({ name: "nightly-ticket-report", trigger: "webhook", stepCount: 2 })]); const run = await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: { day: "2026-09-26" } }); expect(run.json().state).toBe("completed"); }); ``` ```ts main.ts import { App, FrontMcp, workflow } from "@frontmcp/sdk"; import { CheckSla, WriteReport } from "./jobs"; // A workflow can also be written as a function, like a job. const NightlyTicketReport = workflow({ name: "nightly-ticket-report", trigger: "webhook", webhook: { secret: "example-workflow-secret-at-least-32-chars" }, steps: [ { id: "breaches", jobName: "check-sla" }, { id: "report", jobName: "write-report", dependsOn: ["breaches"], input: (steps) => steps.get("breaches").outputs }, ], }); @App({ id: "help-desk", name: "Help Desk", jobs: [CheckSla, WriteReport], workflows: [NightlyTicketReport] }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }; @FrontMcp(config) export default class Server {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "check-sla", inputSchema: { day: z.string() }, outputSchema: { day: z.string(), breaches: z.array(z.string()) } }) export class CheckSla extends JobContext { async execute({ day }: { day: string }) { return { day, breaches: ["T-1", "T-2"] }; } } @Job({ name: "write-report", inputSchema: { day: z.string(), breaches: z.array(z.string()) }, outputSchema: { report: z.string() } }) export class WriteReport extends JobContext { async execute({ day, breaches }: { day: string; breaches: string[] }) { return { report: `${day}: ${breaches.length} tickets broke their SLA.` }; } } ``` `get_workflow_status` returns the run's `state`, times and name, with `stepResults` always empty. A workflow's run is stored like a job's, and `get_job_status` with the same `runId` returns all of it: `jobName` is the workflow's name, and `result` is what `execute_workflow` would have returned inline, `stepResults` included. Until that's fixed, read workflow runs with `get_job_status`. > **Note** > > `trigger` takes `"manual"` (the default), `"webhook"`, `"event"` or `"schedule"`. A webhook workflow needs `webhook.secret` and serves a signed HTTP route. An event workflow starts when the server emits its event, or publishes an event of that name. A schedule workflow starts a background run at each time of its `schedule.cron`: [Scheduling Work and Running Workers](https://frontmcp.dev/learn/scheduling-work-and-running-workers) puts this lesson's nightly report on one. All of them still accept `execute_workflow`. See [workflow triggers](https://frontmcp.dev/reference/sdk/workflow#workflow-triggers). Changed in 1.11.3: before, these options only labeled the workflow. New in 1.12.0: `"schedule"`, and published events starting event workflows. ## Recap - `@Workflow({ name, steps })`, or `workflow({...})`, chains jobs. Register it with `@App({ workflows })`, next to its jobs, and run it with `execute_workflow { name, input }`. The result's `stepResults` has each step's `outputs` and `state`. - A step's `input` is the workflow's input when left out, a fixed object, or a function of `(steps, input)`. Read earlier results with `steps.get(id)` and list them in `dependsOn`. - Steps run in batches of up to `maxConcurrency` (5). Independent steps overlap, and each batch waits for its slowest step. - A failed step runs once without a retry policy. Its direct and indirect dependents are skipped, independent steps run, and the run's `state` is `"failed"` in a successful call. The error is only in the server log. - `continueOnError` lets a step fail without failing the workflow, and `condition` skips a step. Steps after either one run, so check `steps.get(id).state`. - Steps time out after their job's `timeout` (5 minutes by default), and work that ignores the aborted signal keeps running. Read background workflow runs with `get_job_status`: `get_workflow_status` has no steps. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Hand the breaches to the report The report always says "0 of 0 tickets broke their SLA", because its step has a fixed input. Make `report` run after `collect` and `breaches`, and give it the day, the number of tickets and the breaches from those steps. Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: { day: "2026-09-26" } } } ``` ```ts nightly-report.workflow.ts active import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "collect", jobName: "collect-tickets" }, { id: "breaches", jobName: "check-sla", dependsOn: ["collect"], input: (steps) => ({ tickets: steps.get("collect").outputs.tickets }) }, { id: "report", jobName: "write-report", input: { day: "", total: 0, breaches: [] } }, ], }) export class NightlyTicketReport {} ``` **Solution file (alternative to the starter):** ```ts nightly-report.workflow.ts solution import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "collect", jobName: "collect-tickets" }, { id: "breaches", jobName: "check-sla", dependsOn: ["collect"], input: (steps) => ({ tickets: steps.get("collect").outputs.tickets }) }, { id: "report", jobName: "write-report", dependsOn: ["collect", "breaches"], input: (steps) => ({ day: steps.get("collect").outputs.day, total: (steps.get("collect").outputs.tickets as unknown[]).length, breaches: steps.get("breaches").outputs.breaches, }), }, ], }) export class NightlyTicketReport {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; import { ticketsByDay, type Ticket } from "./store"; const ticket = z.object({ id: z.string(), priority: z.enum(["high", "normal"]), hoursToFirstReply: z.number() }); const SLA_HOURS = { high: 4, normal: 24 }; @Job({ name: "collect-tickets", inputSchema: { day: z.string() }, outputSchema: { day: z.string(), tickets: z.array(ticket) }, }) export class CollectTickets extends JobContext { async execute({ day }: { day: string }) { return { day, tickets: ticketsByDay[day] ?? [] }; } } @Job({ name: "check-sla", inputSchema: { tickets: z.array(ticket) }, outputSchema: { breaches: z.array(z.string()) }, }) export class CheckSla extends JobContext { async execute({ tickets }: { tickets: Ticket[] }) { return { breaches: tickets.filter((t) => t.hoursToFirstReply > SLA_HOURS[t.priority]).map((t) => t.id) }; } } @Job({ name: "write-report", inputSchema: { day: z.string(), total: z.number(), breaches: z.array(z.string()) }, outputSchema: { report: z.string() }, }) export class WriteReport extends JobContext { async execute({ day, total, breaches }: { day: string; total: number; breaches: string[] }) { return { report: `${day}: ${breaches.length} of ${total} tickets broke their SLA.` }; } } ``` ```ts store.ts export type Ticket = { id: string; priority: "high" | "normal"; hoursToFirstReply: number }; export const ticketsByDay: Record = { "2026-09-26": [ { id: "T-1", priority: "high", hoursToFirstReply: 6 }, { id: "T-2", priority: "normal", hoursToFirstReply: 30 }, { id: "T-3", priority: "high", hoursToFirstReply: 2 }, { id: "T-4", priority: "normal", hoursToFirstReply: 5 }, ], "2026-09-27": [{ id: "T-5", priority: "normal", hoursToFirstReply: 3 }], }; ``` **Hidden fixture/test file (runs with the example):** ```ts report.test.ts hidden import { test, expect } from "@frontmcp/testing"; const report = async (mcp: any, day: string) => (await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: { day } })).json().result.stepResults.report; test("the 2026-09-26 report counts 2 of 4 tickets", async ({ mcp }) => { expect(await report(mcp, "2026-09-26")).toEqual({ state: "completed", outputs: { report: "2026-09-26: 2 of 4 tickets broke their SLA." } }); }); test("the 2026-09-27 report counts 0 of 1", async ({ mcp }) => { expect((await report(mcp, "2026-09-27")).outputs.report).toBe("2026-09-27: 0 of 1 tickets broke their SLA."); }); ``` **Hint:** A step's `input` can be a function of `steps`. Which steps must be done before it can read them? **Solution:** `dependsOn: ["collect", "breaches"]` makes `report` wait for both, and its input function reads their outputs with `steps.get()`. Here `collect-tickets` returns the day it was given; an input function could also read the workflow's parsed input as its second argument. ### Challenge: Check both at once Counting tickets per customer doesn't need the SLA check, but the workflow runs one after the other, and the run takes more than 600 ms. Make the two run at the same time. The report still needs both. Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: {} } } ``` ```ts nightly-report.workflow.ts active import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "collect", jobName: "collect-tickets" }, { id: "breaches", jobName: "check-sla", dependsOn: ["collect"] }, { id: "customers", jobName: "count-by-customer", dependsOn: ["breaches"] }, { id: "report", jobName: "write-report", dependsOn: ["customers"], input: (steps) => ({ breaches: steps.get("breaches").outputs.breaches, customers: steps.get("customers").outputs.customers }), }, ], }) export class NightlyTicketReport {} ``` **Solution file (alternative to the starter):** ```ts nightly-report.workflow.ts solution import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "collect", jobName: "collect-tickets" }, { id: "breaches", jobName: "check-sla", dependsOn: ["collect"] }, { id: "customers", jobName: "count-by-customer", dependsOn: ["collect"] }, { id: "report", jobName: "write-report", dependsOn: ["breaches", "customers"], input: (steps) => ({ breaches: steps.get("breaches").outputs.breaches, customers: steps.get("customers").outputs.customers }), }, ], }) export class NightlyTicketReport {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; const slow = () => new Promise((resolve) => setTimeout(resolve, 300)); @Job({ name: "collect-tickets", inputSchema: {}, outputSchema: {} }) export class CollectTickets extends JobContext { async execute() { return {}; } } @Job({ name: "check-sla", inputSchema: {}, outputSchema: { breaches: z.number() } }) export class CheckSla extends JobContext { async execute() { await slow(); return { breaches: 2 }; } } @Job({ name: "count-by-customer", inputSchema: {}, outputSchema: { customers: z.number() } }) export class CountByCustomer extends JobContext { async execute() { await slow(); return { customers: 3 }; } } @Job({ name: "write-report", inputSchema: { breaches: z.number(), customers: z.number() }, outputSchema: { report: z.string() } }) export class WriteReport extends JobContext { async execute({ breaches, customers }: { breaches: number; customers: number }) { return { report: `${breaches} SLA breaches across ${customers} customers.` }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts parallel.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the report still has both numbers", async ({ mcp }) => { const run = (await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: {} })).json(); expect(run.state).toBe("completed"); expect(run.result.stepResults.report.outputs.report).toBe("2 SLA breaches across 3 customers."); }); test("the run takes less than 500 ms", async ({ mcp }) => { const call = await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: {} }); expect(call.durationMs).toBeLessThan(500); }); ``` **Hint:** A step starts in the first batch after every step in its `dependsOn` is done. Which step does `count-by-customer` really need? **Solution:** `customers` now depends on `collect`, like `breaches`, so the two are ready together and run in the same batch. `report` has to list both in `dependsOn`: before, it got `breaches` through `customers`, and without it, it would start alongside `breaches` and fail to read it. ### Challenge: Keep the report when paging fails The pager is down, so `page` fails, and with it the whole workflow: the report is skipped. Make the workflow complete with a report that says on-call wasn't paged. Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: {} } } ``` ```ts nightly-report.workflow.ts active import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "breaches", jobName: "check-sla" }, { id: "page", jobName: "page-on-call", dependsOn: ["breaches"] }, { id: "report", jobName: "write-report", dependsOn: ["breaches", "page"], input: (steps) => ({ breaches: steps.get("breaches").outputs.breaches, paged: steps.get("page").state === "completed" }), }, ], }) export class NightlyTicketReport {} ``` **Solution file (alternative to the starter):** ```ts nightly-report.workflow.ts solution import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "breaches", jobName: "check-sla" }, { id: "page", jobName: "page-on-call", dependsOn: ["breaches"], continueOnError: true, retry: { maxAttempts: 1 } }, { id: "report", jobName: "write-report", dependsOn: ["breaches", "page"], input: (steps) => ({ breaches: steps.get("breaches").outputs.breaches, paged: steps.get("page").state === "completed" }), }, ], }) export class NightlyTicketReport {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "check-sla", inputSchema: {}, outputSchema: { breaches: z.array(z.string()) } }) export class CheckSla extends JobContext { async execute() { return { breaches: ["T-1", "T-2"] }; } } @Job({ name: "page-on-call", inputSchema: {}, outputSchema: { paged: z.boolean() } }) export class PageOnCall extends JobContext { async execute() { throw new Error("Pager service unavailable"); } } @Job({ name: "write-report", inputSchema: { breaches: z.array(z.string()), paged: z.boolean() }, outputSchema: { report: z.string() }, }) export class WriteReport extends JobContext { async execute({ breaches, paged }: { breaches: string[]; paged: boolean }) { return { report: `${breaches.length} tickets broke their SLA. On-call was ${paged ? "" : "not "}paged.` }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts page.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the workflow completes, and says on-call wasn't paged", async ({ mcp }) => { const call = await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: {} }); const run = call.json(); expect(run.state).toBe("completed"); expect(run.result.stepResults.page.state).toBe("failed"); expect(run.result.stepResults.report.outputs.report).toBe("2 tickets broke their SLA. On-call was not paged."); expect(call.durationMs).toBeLessThan(1_000); }); ``` **Hint:** Two step options: one lets a step fail without taking its dependents down, and one says how many times to try it. **Solution:** `continueOnError: true` keeps `page`'s state `"failed"` but lets `report` run, and the workflow completes. `report`'s input function already checks `steps.get("page").state`, so the report says what happened. `retry: { maxAttempts: 1 }` makes the one-attempt policy explicit. ### Challenge: Only page when something broke On-call gets paged every night, even when no ticket broke its SLA. Skip the `page` step when `check-sla` finds no breaches, and keep paging when it finds some. Initial call configuration: ```js { tool: "execute_workflow", arguments: { name: "nightly-ticket-report", input: { day: "2026-09-27" } } } ``` ```ts nightly-report.workflow.ts active import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "breaches", jobName: "check-sla" }, { id: "page", jobName: "page-on-call", dependsOn: ["breaches"], input: (steps) => ({ tickets: steps.get("breaches").outputs.breaches }), }, ], }) export class NightlyTicketReport {} ``` **Solution file (alternative to the starter):** ```ts nightly-report.workflow.ts solution import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", steps: [ { id: "breaches", jobName: "check-sla" }, { id: "page", jobName: "page-on-call", dependsOn: ["breaches"], condition: (steps) => (steps.get("breaches").outputs.breaches as string[]).length > 0, input: (steps) => ({ tickets: steps.get("breaches").outputs.breaches }), }, ], }) export class NightlyTicketReport {} ``` ```ts jobs.ts import { Job, JobContext, z } from "@frontmcp/sdk"; const breachesByDay: Record = { "2026-09-26": ["T-1", "T-2"], "2026-09-27": [] }; export const pages: string[][] = []; @Job({ name: "check-sla", inputSchema: { day: z.string() }, outputSchema: { breaches: z.array(z.string()) } }) export class CheckSla extends JobContext { async execute({ day }: { day: string }) { return { breaches: breachesByDay[day] ?? [] }; } } @Job({ name: "page-on-call", inputSchema: { tickets: z.array(z.string()) }, outputSchema: { paged: z.boolean() } }) export class PageOnCall extends JobContext { async execute({ tickets }: { tickets: string[] }) { pages.push(tickets); return { paged: true }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts condition.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { pages } from "./jobs"; const run = async (mcp: any, day: string) => (await mcp.tools.call("execute_workflow", { name: "nightly-ticket-report", input: { day } })).json(); test("a night without breaches skips `page`", async ({ mcp }) => { pages.length = 0; const { state, result } = await run(mcp, "2026-09-27"); expect(state).toBe("completed"); expect(result.stepResults.page.state).toBe("skipped"); expect(pages).toEqual([]); }); test("a night with breaches still pages on-call", async ({ mcp }) => { const { result } = await run(mcp, "2026-09-26"); expect(result.stepResults.page.state).toBe("completed"); }); ``` **Hint:** A step can decide whether to run. It gets the same `steps` an input function gets. **Solution:** `condition` is called once `breaches` is done, and returning `false` marks `page` as `"skipped"` without running its job, so nobody is paged. The workflow still completes: a skipped step isn't a failure. If another step depended on `page`, it would still run, so it would have to check `steps.get("page").state`. --- # Scheduling Work and Running Workers > How to run FrontMCP work that no client asks for: a @Duty every interval or on a cron schedule, a workflow on a schedule, and a supervised @Worker that keeps a connection open, with what happens to each across several copies of the server and at a restart. Source: https://frontmcp.dev/learn/scheduling-work-and-running-workers [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every job and workflow in this chapter ran because a client called `execute_job` or `execute_workflow`. Some work has no caller. The help desk's nightly report should run at night with nobody asking, expired sessions should be swept every ten minutes, and the support mailbox should be watched for as long as the server is up. FrontMCP has three things for that: a **duty** runs on a schedule, a workflow can have a schedule of its own, and a **worker** keeps a long-running process alive. All three answer a question a timer can't: when several copies of the server run, which one does the work? **You will learn** - Why a timer in a provider runs once per copy of the server, and what a lease does about it - How to run work every interval or on a cron schedule with `@Duty` - How to put a workflow on a schedule, and who its runs run as - How to keep a long-running process supervised with `@Worker`, and how it reports what it sees - What happens to all three across several instances, at a restart, and where they don't run > **Note** > > Duties, workers and schedules need a long-lived Node process, and most need a store for their lease. The Playground runs FrontMCP's browser build, which starts none of them. So the Playgrounds in this lesson run the same classes by hand, in tests, and the log lines and `/readyz` answers are from a Node server. Workers, cron schedules, `scope: "cluster"` and scheduled workflows are new in FrontMCP 1.12.0; interval duties came with 1.11.0. ## A timer runs in every copy The obvious way to sweep expired sessions every ten minutes is a timer in a [provider](https://frontmcp.dev/learn/sharing-state-with-providers). It works with one server. Start a second copy, as a stdio server does for each client and a deployment does for each instance, and the sweep runs twice: **Hidden fixture/test file (runs with the example):** ```ts main.ts hidden import { App } from "@frontmcp/sdk"; @App({ name: "Help Desk" }) export class HelpDeskApp {} ``` ```ts sweeper.ts import { Provider } from "@frontmcp/sdk"; /** Which copy swept, in order. It stands in for the database every copy cleans. */ export const sweeps: number[] = []; let copies = 0; @Provider({ name: "SessionSweeper" }) export class SessionSweeper { private readonly copy = ++copies; private timer?: ReturnType; onReady() { // Every 20 ms here, so the test is quick; every 10 minutes in the help desk. this.timer = setInterval(() => sweeps.push(this.copy), 20); } onShutdown() { clearInterval(this.timer); } } ``` ```ts copies.test.ts active import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { SessionSweeper, sweeps } from "./sweeper"; @App({ id: "help-desk", name: "Help Desk", providers: [SessionSweeper] }) class HelpDesk {} test("🚩 two copies of the server, two sweeps each time", async () => { const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }; const first = await FrontMcpInstance.createDirect(config); const second = await FrontMcpInstance.createDirect(config); await new Promise((resolve) => setTimeout(resolve, 100)); await first.dispose(); await second.dispose(); const copiesThatSwept = new Set(sweeps); expect(copiesThatSwept.size).toBe(2); }); ``` Each server builds its own `SessionSweeper`, and each one starts its own timer. With ten copies, the database is swept ten times every ten minutes, a nightly report is sent ten times, and two copies that compact the same file at once can corrupt it. The copies don't know about each other, so none of them can decide to stay out. What they can share is a **lease**: a key in a store every copy reaches, which holds the id of one process and expires unless that process keeps renewing it. Every copy tries to take the lease, one gets it and does the work, and when that one stops, the lease runs out and another copy takes over. Duties, scheduled workflows and workers all use one. ## Running work on a schedule with `@Duty` A duty is a provider class with a `run()` method. `@Duty` says how often it runs and among which copies one of them runs it: ```ts sweeper.duty.ts import { Duty, type DutyRunContext } from "@frontmcp/sdk"; import { sessions } from "./sessions"; @Duty({ name: "sweep-sessions", every: "10m", scope: "machine" }) export class SessionSweeper { async run({ signal }: DutyRunContext) { for (const session of sessions.expired()) { if (signal.aborted) return; // the lease was lost, or the server is shutting down sessions.remove(session); } } } ``` ```ts help-desk.app.ts @App({ id: "help-desk", name: "Help Desk", providers: [SessionSweeper] }) export class HelpDeskApp {} ``` Register it in `providers`, like any provider. Every copy of the server registers the duty, and the lease chooses who runs it. Two copies started on one machine log: ```text Duty "sweep-sessions" runs in this process every 600000 ms ``` ```text Duty "sweep-sessions" already runs elsewhere (lease "help-desk:sweep-sessions"); this one takes it over if that one stops ``` | Option | What it says | | --- | --- | | `every` | How often: milliseconds, or `"500ms"`, `"30s"`, `"10m"`, `"1h"`, `"1d"` | | `cron`, `timezone` | Or when, on the calendar: see [below](https://frontmcp.dev/learn/scheduling-work-and-running-workers#on-the-calendar-with-cron) | | `scope` | Among which copies one runs it: `"machine"`, `"workspace"` (the copies of one machine that run from the same project folder) or `"cluster"` (every machine that shares the server's Redis) | | `name` | The lease's name. The class name by default; set it, since a build can rename classes | `run()` gets a `signal` that aborts when this process loses the lease or the server shuts down. A long run should look at it between steps, or pass it on to what it awaits. A run that throws is logged, `Duty "sweep-sessions" failed: `, and the duty runs again at its next time. A run that would start while the last one is still going is skipped. A duty is a class, so a test can run it without waiting ten minutes. The Playground can't start the duty, but it can read what the decorator resolved, with `dutyMetadataOf()`, and call `run()` itself: **Hidden fixture/test file (runs with the example):** ```ts main.ts hidden import { App } from "@frontmcp/sdk"; @App({ name: "Help Desk" }) export class HelpDeskApp {} ``` ```ts sweeper.duty.ts import { Duty, type DutyRunContext } from "@frontmcp/sdk"; import { sessions } from "./sessions"; @Duty({ name: "sweep-sessions", every: "10m", scope: "machine" }) export class SessionSweeper { async run({ signal }: DutyRunContext) { for (const session of sessions.expired()) { if (signal.aborted) return; // the lease was lost, or the server is shutting down sessions.remove(session); } } } ``` ```ts sessions.ts type Session = { id: string; expired: boolean }; let all: Session[] = []; export const sessions = { reset(next: Session[]) { all = [...next]; }, ids: () => all.map((session) => session.id), expired: () => all.filter((session) => session.expired), remove(session: Session) { all = all.filter((other) => other !== session); }, }; ``` ```ts sweeper.test.ts active import { test, expect } from "@frontmcp/testing"; import { dutyMetadataOf } from "@frontmcp/sdk"; import { SessionSweeper } from "./sweeper.duty"; import { sessions } from "./sessions"; const threeSessions = () => [ { id: "s-1", expired: true }, { id: "s-2", expired: false }, { id: "s-3", expired: true }, ]; test("the decorator resolved the schedule: every 600000 ms, in one process of the machine", () => { expect(dutyMetadataOf(new SessionSweeper())).toEqual({ name: "sweep-sessions", everyMs: 600000, scope: "machine", leaseMs: 60000 }); }); test("one run removes the expired sessions", async () => { sessions.reset(threeSessions()); await new SessionSweeper().run({ signal: new AbortController().signal }); expect(sessions.ids()).toEqual(["s-2"]); }); test("a run whose signal is aborted stops before the next session", async () => { sessions.reset(threeSessions()); await new SessionSweeper().run({ signal: AbortSignal.abort() }); expect(sessions.ids()).toEqual(["s-1", "s-2", "s-3"]); }); ``` `leaseMs` is how long the lease outlives a holder that stopped renewing it. It defaults to three intervals, kept between 3 and 60 seconds, and decides how soon another copy takes over from one that crashed. ### On the calendar, with `cron` An interval drifts with every restart and knows nothing about weekdays. For a report at nine on weekday mornings, give the duty a `cron` expression in place of `every`, and the time zone it is meant in: ```ts sla-report.duty.ts import { Duty, type DutyRunContext } from "@frontmcp/sdk"; @Duty({ name: "sla-report", cron: "0 9 * * 1-5", timezone: "Europe/Berlin", scope: "machine" }) export class SlaReport { async run({ signal }: DutyRunContext) { // Find the tickets that broke their SLA and mail the report. } } ``` The five fields are `minute hour day-of-month month day-of-week`; a sixth, in front, is seconds. | Expression | Runs | | --- | --- | | `0 9 * * 1-5` | At 09:00, Monday to Friday | | `*/15 * * * *` | Every 15 minutes | | `0 0 1 * *` | At midnight on the first of each month | | `*/10 * * * * *` | Every 10 seconds | | `@daily` | At midnight | A cron duty behaves differently from an interval in two ways that matter at a restart: - **It does not run when the server starts.** It waits for its next scheduled time. - **It catches up once.** The lease store remembers when the schedule was last taken. A copy that gets the lease after a scheduled time passed, because every copy was down at 09:00 or the holder crashed, runs once at once, however many times were missed, then continues on schedule. > **Pitfall** > > Without `timezone`, the expression is read in UTC: `0 9 * * 1-5` runs at 10:00 in Berlin in winter and 11:00 in summer. An expression the server can't read, like `61 9 * * *` or a date that never comes (`0 0 30 2 *`), stops startup, with `InvalidDutyCronError` as the cause: the decorator doesn't check it, the server does when it builds the duty. ## Putting a workflow on a schedule The nightly report from [Chaining Jobs into Workflows](https://frontmcp.dev/learn/chaining-jobs-into-workflows) is a workflow, and so far a client had to run it. A workflow has a `trigger`, and `"schedule"` starts a background run at each time of a cron: ```ts nightly-report.workflow.ts import { Workflow, z } from "@frontmcp/sdk"; @Workflow({ name: "nightly-ticket-report", trigger: "schedule", schedule: { cron: "0 2 * * *", timezone: "Europe/Berlin", input: { priority: "high" } }, inputSchema: { priority: z.enum(["high", "normal"]) }, steps: [ { id: "breaches", jobName: "find-sla-breaches" }, { id: "report", jobName: "write-report", dependsOn: ["breaches"], input: (steps) => ({ breaches: steps.get("breaches").outputs.breaches }) }, ], }) export class NightlyTicketReport {} ``` `schedule.input` is the input of every scheduled run, checked against the `inputSchema` like a client's. The server holds one lease per schedule, so each scheduled time starts one run, however many copies are up: ```text The schedule of workflow "nightly-ticket-report" runs in this process on cron "0 2 * * *" (Europe/Berlin) ``` Should the report be a cron duty or a scheduled workflow? Use the workflow when the work is several jobs, or when you want what jobs give you: retries, a run with an id and a state, and `execute_workflow` to run it by hand as well. Use a duty for plain recurring work in a provider. ### Who a scheduled run runs as A run that a client starts runs as that client. A scheduled run has no client: it runs as the role `schedule:`, and nothing else. That matters as soon as the workflow, or a job it runs, has [permission rules](https://frontmcp.dev/learn/authorizing-calls): ```ts permissions: [ { action: "execute", roles: ["admin", "schedule:nightly-ticket-report"] }, // admins by hand, and the schedule { action: "read", roles: ["admin"] }, // nobody owns a scheduled run, so say who may read it ], ``` Without the schedule's role among the `execute` roles, every scheduled time is refused and logged, and nothing runs: ```text The schedule did not start workflow "nightly-ticket-report": its create or execute rules don't allow the role "schedule:nightly-ticket-report"; add it to their roles ``` A webhook's and an event's runs work the same way, as `webhook:` and `event:`. ## Keeping a process running with `@Worker` A duty runs, ends, and runs again. Watching the support mailbox never ends: the connection stays open and mail arrives when it arrives. Started from a provider's `onReady()`, such a loop has nobody to start it again when the connection drops, and nobody to stop it at shutdown. A **worker** is a provider class whose `run()` the server supervises: ```ts inbox.worker.ts import { Worker, type WorkerRunContext } from "@frontmcp/sdk"; import { Mailbox } from "./mailbox"; @Worker({ name: "inbox-watcher", scope: "machine" }) export class InboxWatcher { constructor(private readonly mailbox: Mailbox) {} async run({ signal }: WorkerRunContext) { for await (const mail of this.mailbox.incoming(signal)) { this.mailbox.openTicket(mail); } } } ``` The server does four things with it: 1. **Starts `run()` once the server serves.** With a `scope` other than `"process"`, in the one copy that holds the worker's lease. 2. **Runs it again when it ends.** When `run()` throws or returns before its signal aborted, the server waits and runs it again: 1 second the first time, then twice as long each time, up to a minute. `restart: { minDelayMs, maxDelayMs, factor }` sets the waits, and `restart: false` runs it once. 3. **Keeps the failure away from the server.** What `run()` throws is logged with the worker's name. It doesn't crash the server or stop other workers. 4. **Stops it at shutdown.** The server aborts `signal` and waits for `run()` to return, up to 3 seconds by default. A mailbox whose connection keeps dropping looks like this in the log: ```text Worker "inbox-watcher" runs in this process Worker "inbox-watcher" failed: connection lost; it runs again in 1000 ms Worker "inbox-watcher" failed: connection lost; it runs again in 2000 ms Worker "inbox-watcher" failed: connection lost; it runs again in 4000 ms ``` So `run()` has two obligations, and both can be tested by calling it: return when the signal aborts, and leave by throwing when the work fails. Don't catch the error and loop inside `run()`: the server already waits, waits longer each time, and reports the state. **Hidden fixture/test file (runs with the example):** ```ts main.ts hidden import { App } from "@frontmcp/sdk"; @App({ name: "Help Desk" }) export class HelpDeskApp {} ``` ```ts inbox.worker.ts import { Worker, type WorkerRunContext } from "@frontmcp/sdk"; import { Mailbox } from "./mailbox"; @Worker({ name: "inbox-watcher", scope: "machine" }) export class InboxWatcher { constructor(private readonly mailbox: Mailbox) {} async run({ signal }: WorkerRunContext) { for await (const mail of this.mailbox.incoming(signal)) { this.mailbox.openTicket(mail); } } } ``` ```ts mailbox.ts /** A stand-in for a mail connection: mail arrives with deliver(), and the connection drops with drop(). */ export class Mailbox { readonly tickets: string[] = []; connected = false; private arrived: string[] = []; private failure?: Error; private wake: () => void = () => {}; deliver(subject: string) { this.arrived.push(subject); this.wake(); } drop() { this.failure = new Error("connection lost"); this.wake(); } openTicket(subject: string) { this.tickets.push(subject); } async *incoming(signal: AbortSignal): AsyncGenerator { this.connected = true; signal.addEventListener("abort", () => this.wake(), { once: true }); try { while (!signal.aborted) { if (this.failure) throw this.failure; const subject = this.arrived.shift(); if (subject === undefined) await new Promise((resolve) => (this.wake = resolve)); else yield subject; } } finally { this.connected = false; } } } ``` ```ts inbox.test.ts active import { test, expect } from "@frontmcp/testing"; import { workerMetadataOf } from "@frontmcp/sdk"; import { InboxWatcher } from "./inbox.worker"; import { Mailbox } from "./mailbox"; test("the defaults: one process of the machine, restarts from 1 s up to 60 s", () => { expect(workerMetadataOf(new InboxWatcher(new Mailbox()))).toEqual({ name: "inbox-watcher", scope: "machine", leaseMs: 15000, restart: { minDelayMs: 1000, maxDelayMs: 60000, factor: 2 }, }); }); test("run() opens a ticket for each mail until its signal aborts, then returns", async () => { const mailbox = new Mailbox(); const shutdown = new AbortController(); const running = new InboxWatcher(mailbox).run({ signal: shutdown.signal }); mailbox.deliver("Cannot log in"); mailbox.deliver("Invoice is wrong"); await new Promise((resolve) => setTimeout(resolve, 10)); expect(mailbox.tickets).toEqual(["Cannot log in", "Invoice is wrong"]); shutdown.abort(); await running; expect(mailbox.connected).toBe(false); }); test("a dropped connection leaves run() by throwing, which is what makes the server run it again", async () => { const mailbox = new Mailbox(); const running = new InboxWatcher(mailbox).run({ signal: new AbortController().signal }); mailbox.drop(); await expect(running).rejects.toThrow("connection lost"); expect(mailbox.connected).toBe(false); }); ``` `scope` has one more value for a worker: `"process"`, where every copy runs its own, with no lease. Use it for work each copy needs for itself, like keeping a cache in its own memory warm. Use a leased scope for anything there should be one of, like the mailbox connection. > **Pitfall** > > A `run()` that ignores its signal holds shutdown up until the timeout, and after a lost lease it is still running when the next copy starts: two connections for a moment. Pass `signal` to whatever `run()` awaits, or return when it aborts. A lease gives one holder at a time, not a promise that the work happens exactly once, so make what a worker or duty does safe to repeat. ## Telling clients, and workflows, what a worker saw A worker that only writes to a database is invisible to the rest of the server. To tell someone, it publishes an [event](https://frontmcp.dev/reference/sdk/event): clients subscribed to it are notified, and a workflow with `trigger: "event"` starts with the occurrence as its input. The worker takes the server's publisher from the `EVENT_PUBLISHER` token, through a factory provider: ```ts inbox.worker.ts import { AsyncProvider, EVENT_PUBLISHER, Worker, type EventPublisher, type WorkerRunContext } from "@frontmcp/sdk"; import { mailReceived } from "./mail-received.event"; import { Mailbox } from "./mailbox"; @Worker({ name: "inbox-watcher", scope: "machine" }) class InboxWatcher { constructor( private readonly mailbox: Mailbox, private readonly events: EventPublisher, ) {} async run({ signal }: WorkerRunContext) { for await (const mail of this.mailbox.incoming(signal)) { await this.events.publish(mailReceived, { from: mail.from, subject: mail.subject }); } } } export const inboxWatcher = AsyncProvider({ provide: InboxWatcher, name: "inbox-watcher", inject: () => [Mailbox, EVENT_PUBLISHER] as const, useFactory: (mailbox, events) => new InboxWatcher(mailbox, events), }); ``` Register `inboxWatcher` in `providers`, and the event in the app's `events`. A duty publishes the same way. The Playground below has no worker, so a tool stands in for it and publishes what the worker would. The workflow doesn't know the difference: it listens to the event's name. Initial call configuration: ```js { tool: "receive_mail", arguments: { from: "ada@example.com", subject: "Cannot log in" } } ``` ```ts help-desk.app.ts active import { App, Job, JobContext, Tool, ToolContext, Workflow, event, z } from "@frontmcp/sdk"; export const tickets: { from: string; subject: string }[] = []; export const mailReceived = event({ name: "mail.received", description: "A mail arrived in the support mailbox", payloadSchema: { from: z.string(), subject: z.string() }, }); // What a published event looks like on the way in: the occurrence, with the payload under `data`. const occurrence = { eventId: z.string(), name: z.string(), timestamp: z.string(), data: z.object({ from: z.string(), subject: z.string() }), }; @Job({ name: "open-ticket", inputSchema: occurrence, outputSchema: { opened: z.boolean() } }) class OpenTicket extends JobContext { async execute({ data }: { data: { from: string; subject: string } }) { tickets.push(data); return { opened: true }; } } @Workflow({ name: "triage-mail", trigger: "event", event: "mail.received", inputSchema: occurrence, steps: [{ id: "open", jobName: "open-ticket" }], }) class TriageMail {} // Stands in for the worker: it publishes what the worker would when a mail arrives. @Tool({ name: "receive_mail", description: "Pretend a mail arrived in the support mailbox", inputSchema: { from: z.string(), subject: z.string() } }) class ReceiveMail extends ToolContext { async execute(mail: { from: string; subject: string }) { return this.events.publish(mailReceived, mail); } } @App({ id: "help-desk", name: "Help Desk", tools: [ReceiveMail], events: [mailReceived], jobs: [OpenTicket], workflows: [TriageMail] }) export class HelpDesk {} ``` ```ts triage.test.ts import { test, expect } from "@frontmcp/testing"; import { tickets } from "./help-desk.app"; test("publishing mail.received starts the workflow, which opens a ticket", async ({ mcp }) => { const published = (await mcp.tools.call("receive_mail", { from: "li@example.com", subject: "Invoice is wrong" })).json(); expect(published).toEqual({ eventId: expect.stringMatching(/^evt_/), matched: 0 }); for (let i = 0; i < 100 && !tickets.some((ticket) => ticket.from === "li@example.com"); i++) await new Promise((r) => setTimeout(r, 10)); expect(tickets).toContainEqual({ from: "li@example.com", subject: "Invoice is wrong" }); }); ``` `publish()` answers with the occurrence's `eventId` and `matched`, the number of webhook subscriptions it was queued for. The workflow starts either way, and its run runs as the role `event:mail.received`. With a leased worker, one copy publishes; with `scope: "process"`, every copy publishes its own occurrence of the same mail. ## Several copies, restarts, and where it runs What `scope` to pick depends on where the copies are: | The copies run | A duty or worker there should be one of | Needs | | --- | --- | --- | | On one machine: a stdio server per client, several processes | `scope: "machine"`, or `"workspace"` for one per project folder | The `@frontmcp/storage-sqlite` package, for the lease file under `~/.frontmcp`, unless the server has a `redis` | | On several machines, containers or pods | `scope: "cluster"` | A top-level `redis` on the server, the same on every instance | A scheduled workflow has no `scope`: with `redis` its schedule is shared by every instance, and without it by the copies of one machine that run from the same project folder. > **Pitfall** > > `scope: "machine"` is not enough behind a load balancer. With `redis`, a machine lease is per hostname, and every container has a hostname of its own, so each instance runs the duty. Use `"cluster"`. A `"cluster"` duty or worker on a server without `redis` doesn't start it: startup fails with `ClusterScopeNeedsRedisError`. What happens when things stop and start: | | A duty | A scheduled workflow | A worker | | --- | --- | --- | --- | | The holder shuts down (`SIGTERM`) | It aborts the run, waits for it and releases the lease; another copy takes over at its next check | The same | The same | | The holder crashes | Another copy takes over once the lease expires: `leaseMs` plus a third of it | The same, within 80 seconds | The same, within 20 seconds by default | | Every copy was down at a scheduled time | Cron: one run when a copy is back. Interval: a run at once when the interval since the last run has passed | One run when a copy is back | It starts again | | The lease store can't be opened | The server starts, logs it, and tries again; the duty runs once it opens | The same | The same | Each started duty and worker also has a check in [`/readyz`](https://frontmcp.dev/reference/deployment/health-and-metrics#background-work-and-events), `duty:` and `worker:`, which says whether this instance holds it and how the worker is doing: ```json {"duty:sweep-sessions":{"status":"healthy","details":{"holdsLease":false}},"worker:inbox-watcher":{"status":"degraded","details":{"state":"restarting","restarts":3,"lastError":"connection lost"},"error":"connection lost"}} ``` All of this needs a process that stays up: - **A long-lived Node server**, in a container or under a service manager, runs them for as long as it runs. - **A serverless or edge deployment starts none of them.** A function that lives for one request has nothing to keep a timer in. The server logs `Duty "…" does not run in a serverless or edge deployment: it needs a long-lived process`, and the same for workers and scheduled workflows. - **A stdio server that a client starts** runs them only while that client is connected. - **The [shared local server](https://frontmcp.dev/reference/sdk/frontmcp-instance#frontmcpinstancerunsharedconfigorclass-options)** stays up while a session is attached, and exits `idleTimeoutMs`, ten minutes by default, after the last one left. A running worker doesn't count as activity. Pass `idleTimeoutMs: false` to `runShared()` for one that must keep running. The references have the rest: [`@Duty`](https://frontmcp.dev/reference/sdk/duty) the cron fields, the lease keys and the store, [`@Worker`](https://frontmcp.dev/reference/sdk/worker) the states `/readyz` reports and watching files with `watchFiles()`, and [`@Workflow`](https://frontmcp.dev/reference/sdk/workflow#schedule-options) the schedule options. [High availability](https://frontmcp.dev/reference/deployment/high-availability#background-work-across-instances) has the table of what runs where. ## Recap - A timer in a provider runs in every copy of the server. A duty, a scheduled workflow and a leased worker run in one, the copy that holds a lease, and another copy takes over when that one stops. - `@Duty({ every | cron, timezone, scope })` on a provider class with `run({ signal })` runs recurring work. A cron duty doesn't run at startup, reads its expression in UTC unless `timezone` says otherwise, and catches up once after a missed time. - `@Workflow({ trigger: "schedule", schedule: { cron, timezone, input } })` starts a background run at each scheduled time, as the role `schedule:`: add it to the workflow's `execute` rules when it has any. - `@Worker({ scope, restart })` keeps `run({ signal })` going: started once the server serves, run again with a growing wait when it throws or returns, stopped at shutdown. Return when `signal` aborts, and throw when the work fails. - A worker or a duty publishes events through `EVENT_PUBLISHER`, and a workflow with `trigger: "event"` starts for each one. - On one machine use `scope: "machine"` or `"workspace"`; across machines use `"cluster"`, with `redis`. Nothing here runs on serverless or edge, and `/readyz` shows each one as `duty:` or `worker:`. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Send the report on weekday mornings The SLA report runs every 24 hours, at whatever time of day it first ran, weekends included, and once per machine. The team wants it at 09:00 from Monday to Friday, Berlin time, and once among all the instances, which share a Redis. Change the duty's options; the tool shows what the decorator resolves. Initial call configuration: ```js { tool: "describe_report", arguments: {} } ``` ```ts report.duty.ts active import { Duty, type DutyRunContext } from "@frontmcp/sdk"; @Duty({ name: "sla-report", every: "1d", scope: "machine" }) export class SlaReport { async run({ signal }: DutyRunContext) { // Find the tickets that broke their SLA and mail the report. } } ``` **Solution file (alternative to the starter):** ```ts report.duty.ts solution import { Duty, type DutyRunContext } from "@frontmcp/sdk"; @Duty({ name: "sla-report", cron: "0 9 * * 1-5", timezone: "Europe/Berlin", scope: "cluster" }) export class SlaReport { async run({ signal }: DutyRunContext) { // Find the tickets that broke their SLA and mail the report. } } ``` **Hidden fixture/test file (runs with the example):** ```ts main.ts hidden import { App, Tool, ToolContext, dutyMetadataOf } from "@frontmcp/sdk"; import { SlaReport } from "./report.duty"; @Tool({ name: "describe_report", description: "Show the schedule the duty's options resolve to", inputSchema: {} }) class DescribeReport extends ToolContext { async execute() { return { duty: dutyMetadataOf(new SlaReport()) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DescribeReport] }) export class HelpDesk {} ``` **Hidden fixture/test file (runs with the example):** ```ts report.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { createContainer, dutyMetadataOf } from "@frontmcp/sdk"; import { SlaReport } from "./report.duty"; const resolved = () => dutyMetadataOf(new SlaReport()); test("the duty has a `cron` in place of `every`", () => { expect(resolved()?.cron).toBeDefined(); expect(resolved()?.everyMs).toBeUndefined(); }); test("it runs at 09:00, Monday to Friday", () => { expect(resolved()?.cron?.expression.trim().toUpperCase()).toMatch(/^(0 )?0 0?9 \* \* (1-5|MON-FRI)$/); }); test("the cron is read in `Europe/Berlin`", () => { expect(resolved()?.cron?.timezone).toBe("Europe/Berlin"); }); test("one instance runs it among all of them", () => { expect(resolved()?.scope).toBe("cluster"); }); test("the server can read the cron", async () => { const container = await createContainer({ providers: [SlaReport] }); await container.dispose(); }); ``` **Hint:** `every` and `cron` can't be set together. The five cron fields are `minute hour day-of-month month day-of-week`, and Monday to Friday is `1-5`. **Solution:** `cron: "0 9 * * 1-5"` with `timezone: "Europe/Berlin"` runs at nine on weekdays in Berlin, in winter and in summer; without the time zone it would be read in UTC. `scope: "cluster"` keeps one lease in the server's Redis for every instance, where `"machine"` would give each container its own. The last check builds the duty in a container, which reads the expression the way the server does at startup. ### Challenge: Stop when the server says so This worker takes tickets off a queue. It never returns, so the server waits out its shutdown timeout every time it stops, and a copy that loses the worker's lease keeps consuming next to the copy that took over. Make `run()` return when its signal aborts, and close the queue when it ends, however it ends. `queue.next(signal)` resolves with `undefined` once that signal aborts. ```ts consumer.worker.ts active import { Worker, type WorkerRunContext } from "@frontmcp/sdk"; import { TicketQueue } from "./queue"; @Worker({ name: "ticket-queue", scope: "machine" }) export class TicketQueueConsumer { constructor(private readonly queue: TicketQueue) {} async run(_context: WorkerRunContext) { while (true) { const ticket = await this.queue.next(); if (ticket !== undefined) this.queue.handled.push(ticket); } } } ``` **Solution file (alternative to the starter):** ```ts consumer.worker.ts solution import { Worker, type WorkerRunContext } from "@frontmcp/sdk"; import { TicketQueue } from "./queue"; @Worker({ name: "ticket-queue", scope: "machine" }) export class TicketQueueConsumer { constructor(private readonly queue: TicketQueue) {} async run({ signal }: WorkerRunContext) { try { while (!signal.aborted) { const ticket = await this.queue.next(signal); if (ticket !== undefined) this.queue.handled.push(ticket); } } finally { this.queue.close(); } } } ``` ```ts queue.ts /** A stand-in for a queue connection. */ export class TicketQueue { readonly handled: string[] = []; closed = false; private waiting: string[] = []; private wake: () => void = () => {}; add(ticket: string) { this.waiting.push(ticket); this.wake(); } /** The next ticket, or `undefined` once `signal` aborts. */ async next(signal?: AbortSignal): Promise { signal?.addEventListener("abort", () => this.wake(), { once: true }); while (this.waiting.length === 0 && !signal?.aborted) { await new Promise((resolve) => (this.wake = resolve)); } return signal?.aborted ? undefined : this.waiting.shift(); } close() { this.closed = true; } } ``` **Hidden fixture/test file (runs with the example):** ```ts main.ts hidden import { App } from "@frontmcp/sdk"; @App({ name: "Help Desk" }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts consumer.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { TicketQueueConsumer } from "./consumer.worker"; import { TicketQueue } from "./queue"; const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); async function startConsumer() { const queue = new TicketQueue(); const shutdown = new AbortController(); let returned = false; const running = Promise.resolve(new TicketQueueConsumer(queue).run({ signal: shutdown.signal })).then(() => (returned = true)); running.catch(() => undefined); return { queue, shutdown, hasReturned: () => returned }; } test("`run()` handles the tickets that arrive", async () => { const { queue, shutdown } = await startConsumer(); queue.add("T-1"); queue.add("T-2"); await settle(); expect(queue.handled).toEqual(["T-1", "T-2"]); shutdown.abort(); }); test("`run()` returns when its signal aborts", async () => { const { queue, shutdown, hasReturned } = await startConsumer(); queue.add("T-1"); await settle(); expect(hasReturned()).toBe(false); shutdown.abort(); await settle(); expect(hasReturned()).toBe(true); }); test("the queue is closed once `run()` has ended", async () => { const { queue, shutdown } = await startConsumer(); await settle(); expect(queue.closed).toBe(false); shutdown.abort(); await settle(); expect(queue.closed).toBe(true); }); ``` **Hint:** `run()` gets `{ signal }`. Loop while it isn't aborted, hand it to `queue.next()` so a wait for the next ticket ends too, and put the `close()` in a `finally`. **Solution:** The loop now ends in two places: its condition, and the `await`, which resolves with `undefined` when the signal aborts while the queue is empty. The `finally` closes the queue on a normal return and on an error alike, so a run the server starts again opens a fresh connection. Nothing here catches errors: a failure should leave `run()`, and the server runs it again after its wait. ### Challenge: Let the event start the workflow Mail arrives, `mail.received` is published, and no ticket is opened: the `triage-mail` workflow only lets the `support` role run it, and a run that an event starts has no such role. Let the event start the workflow, without letting everyone else run it by hand. The Logs tab says why each run is refused. Initial call configuration: ```js { tool: "receive_mail", arguments: { from: "ada@example.com", subject: "Cannot log in" } } ``` ```ts triage.workflow.ts active import { Workflow, z } from "@frontmcp/sdk"; export const occurrence = { eventId: z.string(), name: z.string(), timestamp: z.string(), data: z.object({ from: z.string(), subject: z.string() }), }; @Workflow({ name: "triage-mail", trigger: "event", event: "mail.received", inputSchema: occurrence, permissions: [{ action: "execute", roles: ["support"] }], steps: [{ id: "open", jobName: "open-ticket" }], }) export class TriageMail {} ``` **Solution file (alternative to the starter):** ```ts triage.workflow.ts solution import { Workflow, z } from "@frontmcp/sdk"; export const occurrence = { eventId: z.string(), name: z.string(), timestamp: z.string(), data: z.object({ from: z.string(), subject: z.string() }), }; @Workflow({ name: "triage-mail", trigger: "event", event: "mail.received", inputSchema: occurrence, permissions: [{ action: "execute", roles: ["support", "event:mail.received"] }], steps: [{ id: "open", jobName: "open-ticket" }], }) export class TriageMail {} ``` ```ts help-desk.app.ts import { App, Job, JobContext, Tool, ToolContext, event, z } from "@frontmcp/sdk"; import { TriageMail, occurrence } from "./triage.workflow"; export const tickets: { from: string; subject: string }[] = []; export const mailReceived = event({ name: "mail.received", description: "A mail arrived in the support mailbox", payloadSchema: { from: z.string(), subject: z.string() }, }); @Job({ name: "open-ticket", inputSchema: occurrence, outputSchema: { opened: z.boolean() } }) class OpenTicket extends JobContext { async execute({ data }: { data: { from: string; subject: string } }) { tickets.push(data); return { opened: true }; } } // Stands in for the worker that watches the mailbox. @Tool({ name: "receive_mail", description: "Pretend a mail arrived in the support mailbox", inputSchema: { from: z.string(), subject: z.string() } }) class ReceiveMail extends ToolContext { async execute(mail: { from: string; subject: string }) { return this.events.publish(mailReceived, mail); } } @App({ id: "help-desk", name: "Help Desk", tools: [ReceiveMail], events: [mailReceived], jobs: [OpenTicket], workflows: [TriageMail] }) export class HelpDesk {} ``` **Hidden fixture/test file (runs with the example):** ```ts triage.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { tickets } from "./help-desk.app"; const input = { eventId: "evt_by_hand", name: "mail.received", timestamp: "2026-11-11T09:00:00.000Z", data: { from: "mallory@example.com", subject: "By hand" } }; test("a published `mail.received` opens a ticket", async ({ mcp }) => { await mcp.tools.call("receive_mail", { from: "li@example.com", subject: "Invoice is wrong" }); for (let i = 0; i < 50 && !tickets.some((ticket) => ticket.from === "li@example.com"); i++) await new Promise((r) => setTimeout(r, 10)); expect(tickets).toContainEqual({ from: "li@example.com", subject: "Invoice is wrong" }); }); test("a caller without the `support` role still can't run the workflow by hand", async ({ mcp }) => { const byHand = await mcp.tools.call("execute_workflow", { name: "triage-mail", input }); expect(byHand).toBeError(); expect(tickets).not.toContainEqual(input.data); }); ``` **Hint:** A run a trigger starts has one role, named after the trigger. For an event it is `event:` and the event's name. **Solution:** `roles: ["support", "event:mail.received"]` lets a caller with either role pass the rule. The event's run has exactly that one role. The Playground's anonymous caller has neither, so running the workflow by hand still answers `not found or not permitted`. A scheduled workflow needs the same line with `schedule:`, and a webhook's with `webhook:`. Removing `permissions` would also open the ticket, and let anyone run the workflow. --- # 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 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. ## 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. ## 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. ## 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. ## 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. ## 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; private readonly reported = new Set(); 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 `` 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). ## 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. ## 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 }; /** 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((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 & { cancel(): Promise }; /** 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 }; /** 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. --- # Delegating to Agents > When the client's model shouldn't do every step itself. FrontMCP agents run a model of their own, with their own instructions and tools, so a client can hand off a whole task in one call; skills teach the client's model a procedure instead. Source: https://frontmcp.dev/learn/delegating-to-agents [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every tool in this course so far does one thing, and the client's model decides what to call next. Some tasks are a string of those decisions. Triaging a ticket means reading it, looking up the customer, choosing a priority and setting it. The client's model can do that one call at a time, if it knows how and you trust it with every tool. Or your server can do it: in FrontMCP, an **agent** is a tool that runs a model of its own, with instructions and tools you choose, so the client's model hands over the whole task in one call. This chapter covers agents that run on your server, and **skills**, the other way to teach a model a procedure, and points out where 1.8 behaves differently from its docs. **In this chapter** - [How to write an agent, and what a client sees of it](https://frontmcp.dev/learn/your-first-agent) - [How to give an agent tools, and what its loop does with them](https://frontmcp.dev/learn/giving-an-agent-tools) - [How to connect an agent to a real model, and what that costs](https://frontmcp.dev/learn/connecting-a-real-model) - [How one agent hands a task to another](https://frontmcp.dev/learn/agents-that-call-agents) - [How to teach the client's model a procedure with a skill](https://frontmcp.dev/learn/teaching-the-model-skills) > **Note** > > Two kinds of agent meet in this chapter's help desk. The people who answer tickets are **support agents**. An **agent** on its own is always a FrontMCP agent, the thing this chapter is about. ## Your first agent An agent is a class, like a tool. `@Agent` gives it a description for the client's model, instructions for its own model, an input schema, and `llm`, the model it runs. It has no `execute()`: FrontMCP sends the input to the model and returns the model's answer. A client sees one tool, `invoke_triage`: Initial call configuration: ```js { tool: "invoke_triage", arguments: { title: "Cannot log in", body: "Since this morning nobody on our team can log in." } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Suggest a priority for a new support ticket, with a one-line reason. Pass the ticket's title and body.", systemInstructions: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, " + "and say why in one sentence. High is for anything that stops the customer from working.", inputSchema: { title: z.string().describe("The ticket's title"), body: z.string().describe("What the customer wrote"), }, llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { Triage } from "./triage.agent"; @App({ id: "help-desk", name: "Help Desk", agents: [Triage] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts model.example.ts // Stands in for a real model, which the Playground can't reach. FrontMCP calls // completion() each time the agent needs the model. This one follows a fixed // rule instead of reading the ticket. A real server doesn't need this file. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion(prompt) { const blocked = /can't|cannot|down/i.test(prompt.messages[0].content ?? ""); return { content: blocked ? "High. The customer can't work until this is fixed." : "Normal. Nothing stops the customer from working.", finishReason: "stop", }; }, }; ``` ```ts agent.test.ts import { test, expect } from "@frontmcp/testing"; test("the agent is one tool, `invoke_triage`", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool).toMatchObject({ name: "invoke_triage", description: "Suggest a priority for a new support ticket, with a one-line reason. Pass the ticket's title and body.", inputSchema: { properties: { title: { type: "string" }, body: { type: "string" } } }, }); }); test("its result is the model's answer", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "Cannot log in", body: "Nobody on our team can log in." }); expect(result.json()).toEqual({ response: "High. The customer can't work until this is fixed." }); }); ``` The Playground can't reach a real model, so every example in this chapter has a `model.example.ts` that plays one: an object with a `completion()` method, which is all FrontMCP asks of a model. It follows a script, so the examples are the same every time you run them. ### [Your First Agent](https://frontmcp.dev/learn/your-first-agent) Learn how to write and register an agent, how a client sees it, what its model is sent and how FrontMCP builds that from the input, and what comes back, checked by `outputSchema`. ## Giving an agent tools With `tools`, an agent's model can look things up and change things, as a support agent would. FrontMCP runs a loop: it asks the model what to do, runs the tools the model asks for, gives it the results, and asks again, until the model answers. The tools are the agent's alone. The client doesn't see them: *[Illustration: An agent's loop. The MCP client makes one call, tools/call invoke_triage with a ticket id. Inside, in a loop of up to 10 turns, triage asks its model for a completion with the prompt and its tools; the model asks for get_ticket; triage runs get_ticket and gets the ticket's title and status; triage asks the model again with the tool result; the model answers. Triage returns that answer to the client as the call's result.]* Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", priority: "none" }], ["T-3", { id: "T-3", title: "Export is slow", priority: "none" }], ]); @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") } }) class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return ticket; } } @Tool({ name: "set_priority", description: "Set a ticket's priority.", inputSchema: { id: z.string().describe("Ticket id, like T-1"), priority: z.enum(["high", "normal", "low"]) }, }) class SetPriority extends ToolContext { async execute({ id, priority }: { id: string; priority: "high" | "normal" | "low" }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); ticket.priority = priority; return { id, priority }; } } @Agent({ name: "triage", description: "Triage a support ticket: read it and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket, then set its priority with set_priority: " + "high if the customer can't work, normal otherwise. Finish with one sentence that says what you set.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket, SetPriority], llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts model.example.ts // Stands in for a real model. It follows the agent's instructions, one step // per request: read the ticket, set the priority, answer. import type { AgentCompletion, AgentLlmAdapter } from "@frontmcp/sdk"; export let requests = 0; export const model: AgentLlmAdapter = { async completion(prompt) { requests++; const { ticketId } = JSON.parse(prompt.messages[0].content ?? "{}"); const [ticket, updated] = prompt.messages.filter((m) => m.role === "tool").map((m) => JSON.parse(m.content ?? "null")); if (!ticket) return callTool("get_ticket", { id: ticketId }); if (!updated) return callTool("set_priority", { id: ticketId, priority: /cannot/i.test(ticket.title) ? "high" : "normal" }); return { content: `${ticketId} is now ${updated.priority} priority.`, finishReason: "stop" }; }, }; function callTool(name: string, args: Record): AgentCompletion { return { content: null, finishReason: "tool_calls", toolCalls: [{ id: `call_${name}`, name, arguments: args }] }; } ``` ```ts tools.test.ts import { test, expect } from "@frontmcp/testing"; import { requests } from "./model.example"; import { tickets } from "./triage.agent"; test("the model asks for two tools, then answers", async ({ mcp }) => { const before = requests; const result = await mcp.tools.call("invoke_triage", { ticketId: "T-3" }); expect(requests - before).toBe(3); expect(result.json()).toEqual({ response: "T-3 is now normal priority." }); expect(tickets.get("T-3")?.priority).toBe("normal"); }); test("the client sees the agent, not its tools", async ({ mcp }) => { expect((await mcp.tools.list()).map((t) => t.name)).toEqual(["invoke_triage"]); expect(await mcp.tools.call("get_ticket", { id: "T-1" })).toBeError("TOOL_NOT_FOUND"); }); ``` One call to `invoke_triage`, three requests to the agent's model. This loop is what every agent runs: 1. The client's model calls `invoke_triage`, and waits. 2. FrontMCP sends the agent's model its instructions, the input and the agent's tools. 3. The model asks for a tool. FrontMCP runs it and adds the call and its result to the conversation. 4. FrontMCP sends the whole conversation back, and the model decides again, as often as it needs, up to a limit you set. 5. When the model answers instead of asking for a tool, the answer is `invoke_triage`'s result. The client's model sees steps 1 and 5. Everything between, including every tool call and every failed one, happens on your server. ### [Giving an Agent Tools](https://frontmcp.dev/learn/giving-an-agent-tools) Learn how the loop runs step by step, which tools the client and the agent can each see, what the model hears when a tool fails, how to limit the loop, how to add your own steps before and after it, and what a client hears while it runs. ## Connecting a real model Outside the Playground, `llm` names a provider, a model and where the API key is: ```ts triage.agent.ts @Agent({ name: "triage", // … llm: { provider: "anthropic", // or "openai", with the `openai` package model: "claude-opus-5", apiKey: { env: "ANTHROPIC_API_KEY" }, }, }) export class Triage extends AgentContext {} ``` The Playground can't run this: it has no network and no API key. A real model also changes what an agent costs. Every turn of the loop is a request to the provider, paid for by your server's key, carrying the whole conversation so far, and the client waits for all of them. ### [Connecting a Real Model](https://frontmcp.dev/learn/connecting-a-real-model) Learn which packages to install, where the key comes from and what happens when it's missing, exactly what FrontMCP sends Anthropic and OpenAI, how failed requests are retried, and how to see and keep down what each call costs. ## Agents that call agents Billing questions need billing's tools and billing's rules. FrontMCP's docs describe nesting agents and "swarm" settings for this, but in 1.8 neither connects one agent to another. What works is one agent calling another the way it would call any tool, from its own `execute()`: Initial call configuration: ```js { tool: "invoke_triage", arguments: { message: "INV-7 was charged twice." } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { triageModel } from "./model.example"; type Answer = { response?: string; handoff?: "billing"; question?: string }; @Agent({ name: "triage", description: "Answer a customer's message, or hand billing questions to the billing agent.", systemInstructions: "Answer the customer's message. If it's about an invoice or a charge, answer only with " + '{"handoff": "billing", "question": ""}.', inputSchema: { message: z.string().describe("What the customer wrote") }, llm: { adapter: triageModel }, }) export class Triage extends AgentContext { async execute(input: { message: string }) { const answer = (await super.execute(input)) as Answer; // triage's own loop if (answer.handoff === "billing") { const billing = await this.callTool("invoke_billing", { question: answer.question }); return billing.structuredContent as Answer; } return answer; } } ``` ```ts billing.agent.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { billingModel } from "./model.example"; @Agent({ name: "billing", description: "Answer a customer's question about an invoice or a charge.", systemInstructions: "You answer billing questions for a help desk.", inputSchema: { question: z.string().describe("The customer's question") }, llm: { adapter: billingModel }, }) export class Billing extends AgentContext {} ``` ```ts model.example.ts // Stand-ins for the two agents' models. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const triageModel: AgentLlmAdapter = { async completion(prompt) { const message = prompt.messages[0].content ?? ""; if (/invoice|charge|INV-/i.test(message)) { return { content: JSON.stringify({ handoff: "billing", question: message }), finishReason: "stop" }; } return { content: "A support agent will look at this today.", finishReason: "stop" }; }, }; export const billingModel: AgentLlmAdapter = { async completion() { return { content: "The second charge on INV-7 is refunded. It takes 3 to 5 business days.", finishReason: "stop" }; }, }; ``` ```ts handoff.test.ts import { test, expect } from "@frontmcp/testing"; test("a billing question is answered by billing", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { message: "INV-7 was charged twice." }); expect(result.json()).toEqual({ response: "The second charge on INV-7 is refunded. It takes 3 to 5 business days." }); }); test("anything else, triage answers itself", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { message: "The export button is grey." }); expect(result.json()).toEqual({ response: "A support agent will look at this today." }); }); ``` ### [Agents That Call Agents](https://frontmcp.dev/learn/agents-that-call-agents) Learn what two agents on one server see of each other, what nested agents and swarm settings do in 1.8, how to hand a task off from `execute()`, what to do when the other agent fails, and how to stop handoffs that never end. ## Teaching the model skills An agent does a task with your model. A **skill** hands the procedure to the client's model instead: the steps, the tools they use and the rules, which the client's model reads and then follows with your tools. A skill adds no tools; FrontMCP serves it as a document, `SKILL.md`: Initial call configuration: ```js { resource: "skill://refund-duplicate-charge/SKILL.md" } ``` ```ts refund.skill.ts active import { Skill, SkillContext } from "@frontmcp/sdk"; @Skill({ name: "refund-duplicate-charge", description: "Refund a customer who was charged more than once for the same invoice.", instructions: `1. Read the invoice with get_invoice. Refund only if it has more than one charge. 2. Refund every charge after the first with refund_charge. Never refund the first charge.`, tools: ["get_invoice", "refund_charge"], }) export class RefundDuplicateCharge extends SkillContext {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_invoice", description: "Get an invoice, with its charges.", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, charges: [{ id: "ch_1", amount: "49 EUR" }, { id: "ch_2", amount: "49 EUR" }] }; } } @Tool({ name: "refund_charge", description: "Refund one charge.", inputSchema: { chargeId: z.string() } }) export class RefundCharge extends ToolContext { async execute({ chargeId }: { chargeId: string }) { return { refunded: chargeId }; } } ``` ```ts skill.test.ts import { test, expect } from "@frontmcp/testing"; test("a skill adds no tools", async ({ mcp }) => { expect((await mcp.tools.list()).map((t) => t.name)).toEqual(["get_invoice", "refund_charge"]); }); test("it's served as a SKILL.md resource", async ({ mcp }) => { const md = (await mcp.resources.read("skill://refund-duplicate-charge/SKILL.md")).text(); expect(md).toContain("name: refund-duplicate-charge"); expect(md).toContain("Never refund the first charge."); }); ``` ### [Teaching the Model Skills](https://frontmcp.dev/learn/teaching-the-model-skills) Learn how to write a skill with instructions, tools, parameters and examples, how a client finds and reads skills, how to search and load them with FrontMCP's own requests, where instructions can come from, and when to write a skill, an agent or a prompt. ## Tool, agent or skill? | If the work… | Write | | --- | --- | | Is one action the model calls and uses the answer of right away | A tool | | Is a procedure the client's model can follow with your tools, once it knows the steps | A skill | | Needs a model of its own, uses tools the client shouldn't have, or should run the same way for every client | An agent | The difference that's easiest to miss is who pays. A skill runs on the client's model. An agent runs on yours, for every client that calls it, so write one when the task is worth that, and keep it behind [authentication](https://frontmcp.dev/learn/authenticating-clients) and [rate limits](https://frontmcp.dev/learn/limiting-calls). ## What's next? Start the chapter with [Your First Agent](https://frontmcp.dev/learn/your-first-agent). To see an agent with a full set of help desk tools in one server, read the [Triage Agent](https://frontmcp.dev/examples/triage-agent) example, and look up every option in the [`@Agent`](https://frontmcp.dev/reference/sdk/agent) and [`@Skill`](https://frontmcp.dev/reference/sdk/skill) references. After this chapter, [Tools with a UI](https://frontmcp.dev/learn/tools-with-a-ui) shows how a tool can answer with a small page the host displays, not just data. --- # Your First Agent > How to write a FrontMCP agent with @Agent and AgentContext, register it on an app, call it through its invoke_ tool, and read what its model is sent and what comes back. Source: https://frontmcp.dev/learn/your-first-agent [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every tool so far does one thing and answers, and the client's model decides what happens next. A FrontMCP **agent** moves some of that deciding into your server. It's a tool that runs a model of its own, with instructions you write, so the client's model can hand it a whole task in one call. This lesson writes an agent that suggests a priority for a new support ticket, calls it the way a client would, and looks at what its model is sent and what comes back. **You will learn** - How to write an agent with `@Agent` and `AgentContext`, and register it on an app - How a client sees an agent: one `invoke_` tool - What the agent's model is sent, and how FrontMCP builds it from the input - What comes back, and how `outputSchema` checks it - How a scripted model stands in for a real one ## Writing an agent New tickets arrive with a title and whatever the customer wrote, and before anyone works on one, a support agent gives it a priority. That's a judgment call on free text, which a model makes well. Here's an agent that makes it. Open the **Tests** tab: Initial call configuration: ```js { tool: "invoke_triage", arguments: { title: "Cannot log in", body: "Since this morning nobody on our team can log in." } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Suggest a priority for a new support ticket, with a one-line reason. Pass the ticket's title and body.", systemInstructions: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, " + "and say why in one sentence. High is for anything that stops the customer from working.", inputSchema: { title: z.string().describe("The ticket's title"), body: z.string().describe("What the customer wrote"), }, llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { Triage } from "./triage.agent"; @App({ id: "help-desk", name: "Help Desk", agents: [Triage] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts model.example.ts // Stands in for a real model, which the Playground can't reach. FrontMCP calls // completion() each time the agent needs the model, and treats what it returns // as the model's reply. This one follows a fixed rule instead of reading the // ticket. A real server doesn't need this file. import type { AgentLlmAdapter, AgentPrompt } from "@frontmcp/sdk"; /** Every prompt the model was sent, oldest first. */ export const prompts: AgentPrompt[] = []; export const model: AgentLlmAdapter = { async completion(prompt) { prompts.push(structuredClone(prompt)); const ticket = prompt.messages[0].content ?? ""; const blocked = /can't|cannot|can not|down/i.test(ticket); return { content: blocked ? "High. The customer can't work until this is fixed." : "Normal. Nothing stops the customer from working.", finishReason: "stop", }; }, }; ``` ```ts triage.test.ts import { test, expect } from "@frontmcp/testing"; test("the agent is one tool, `invoke_triage`", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).toEqual(["invoke_triage"]); }); test("it answers with its model's reply", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "Cannot log in", body: "Since this morning nobody on our team can log in.", }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ response: "High. The customer can't work until this is fixed." }); }); test("a ticket that blocks nobody is Normal", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "New invoice address", body: "Please send our invoices to the new office from next month.", }); expect(result.json()).toEqual({ response: "Normal. Nothing stops the customer from working." }); }); ``` An agent is a class, like a tool: - **`@Agent({ name, description, systemInstructions, inputSchema, llm })`** describes it. `description` is for the client's model, which decides when to call the agent. `systemInstructions` are for the agent's own model, which does the work. `inputSchema` is a Zod shape, as on a tool. - **`llm`** says which model the agent runs. Here it's `{ adapter: model }`, an object you write; the lesson [Connecting a Real Model](https://frontmcp.dev/learn/connecting-a-real-model) replaces it with OpenAI or Anthropic. - **`AgentContext`** is the base class, and there's no `execute()`. FrontMCP's own sends the input to the model and returns its answer. You can [override it](https://frontmcp.dev/learn/giving-an-agent-tools#before-and-after-the-loop) when you need to. - **`agents: [Triage]`** on `@App` registers it. > **Note** > > The Playground runs in your browser, with no network and no API key, so it can't reach a real model. Every example in this chapter has a `model.example.ts` file that plays one: an object with a `completion()` method, which is all FrontMCP asks of a model. It follows a fixed rule instead of thinking, and records what it was sent so the tests can check it. With a [real model](https://frontmcp.dev/learn/connecting-a-real-model), you don't need it. ## How a client sees an agent Open the **Capabilities** tab of the example above. The agent is a tool called `invoke_triage`, and nothing about it says there's a model behind it. A client lists it and calls it like any other tool: ```ts listing.test.ts active import { test, expect } from "@frontmcp/testing"; test("`invoke_triage` is built from the agent's options", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool).toEqual({ name: "invoke_triage", description: "Suggest a priority for a new support ticket, with a one-line reason. Pass the ticket's title and body.", inputSchema: { $schema: "https://json-schema.org/draft/2020-12/schema", type: "object", properties: { title: { type: "string", description: "The ticket's title" }, body: { type: "string", description: "What the customer wrote" }, }, required: ["title", "body"], }, annotations: { title: "triage", readOnlyHint: false, openWorldHint: true }, }); }); test("input that doesn't match `inputSchema` never reaches the model", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "Cannot log in" }); expect(result).toBeError("INVALID_INPUT"); }); ``` ```ts triage.agent.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Suggest a priority for a new support ticket, with a one-line reason. Pass the ticket's title and body.", systemInstructions: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, " + "and say why in one sentence. High is for anything that stops the customer from working.", inputSchema: { title: z.string().describe("The ticket's title"), body: z.string().describe("What the customer wrote"), }, llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts model.example.ts // Stands in for a real model. See the first example on this page. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion() { return { content: "High. The customer can't work until this is fixed.", finishReason: "stop" }; }, }; ``` From here on, examples leave out `main.ts`: when an example exports an agent but no app, the Playground registers it in one for you, as it does tools. | `@Agent` option | What the client sees | | --- | --- | | `name` | The tool's name, `invoke_` and the name, and its `annotations.title`. | | `description` | The tool's description. | | `inputSchema` | The tool's input schema. Input that doesn't match fails with `INVALID_INPUT` before the model is asked, as for any tool. | | `systemInstructions` | Nothing. They go to the agent's model only. | FrontMCP marks every agent's tool `readOnlyHint: false` and `openWorldHint: true`, whatever the agent does. The [`@Agent` reference](https://frontmcp.dev/reference/sdk/agent) has the rest of the naming rules, like `id`, which names the tool instead of `name`. > **Pitfall: Don't leave out the description** > > Without a `description`, FrontMCP makes one up from the start of the system instructions: > > ```ts triage.agent.ts active > import { Agent, AgentContext, z } from "@frontmcp/sdk"; > import { model } from "./model.example"; > > @Agent({ > name: "triage", > // 🚩 no description > systemInstructions: > "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, " + > "and say why in one sentence. High is for anything that stops the customer from working.", > inputSchema: { title: z.string(), body: z.string() }, > llm: { adapter: model }, > }) > export class Triage extends AgentContext {} > ``` > > ```ts model.example.ts > // Stands in for a real model. See the first example on this page. > import type { AgentLlmAdapter } from "@frontmcp/sdk"; > > export const model: AgentLlmAdapter = { > async completion() { > return { content: "High. The customer can't work until this is fixed.", finishReason: "stop" }; > }, > }; > ``` > > ```ts description.test.ts > import { test, expect } from "@frontmcp/testing"; > > test("🚩 the description is the instructions' first 100 characters", async ({ mcp }) => { > const [tool] = await mcp.tools.list(); > expect(tool.description).toBe( > "Invoke the triage agent. You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, and say why in ...", > ); > }); > ``` > > The system instructions are written for the agent's model, as if it were doing the work. The client's model needs something else: what the agent is for and what to pass it, as in any [tool description](https://frontmcp.dev/learn/writing-descriptions-agents-understand). Write both. ## What the agent's model is sent When `invoke_triage` is called, FrontMCP calls the adapter's `completion(prompt, tools)`. `prompt` is the whole conversation so far, and at the start that's the system instructions and one message from the "user", made from the input. The model in this example records every prompt, and the test reads the first: Initial call configuration: ```js { tool: "invoke_triage", arguments: { title: "Cannot log in", body: "Since this morning nobody on our team can log in." } } ``` ```ts prompt.test.ts active import { test, expect } from "@frontmcp/testing"; import { prompts } from "./model.example"; test("the model gets the instructions and the input as JSON", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { title: "Cannot log in", body: "Since this morning nobody on our team can log in." }); expect(prompts[0]).toEqual({ system: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, " + "and say why in one sentence. High is for anything that stops the customer from working.", messages: [{ role: "user", content: '{"title":"Cannot log in","body":"Since this morning nobody on our team can log in."}' }], }); }); ``` ```ts triage.agent.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Suggest a priority for a new support ticket, with a one-line reason. Pass the ticket's title and body.", systemInstructions: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, " + "and say why in one sentence. High is for anything that stops the customer from working.", inputSchema: { title: z.string().describe("The ticket's title"), body: z.string().describe("What the customer wrote"), }, llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts model.example.ts // Stands in for a real model, which the Playground can't reach. FrontMCP calls // completion() each time the agent needs the model, and treats what it returns // as the model's reply. This one follows a fixed rule instead of reading the // ticket. A real server doesn't need this file. import type { AgentLlmAdapter, AgentPrompt } from "@frontmcp/sdk"; /** Every prompt the model was sent, oldest first. */ export const prompts: AgentPrompt[] = []; export const model: AgentLlmAdapter = { async completion(prompt) { prompts.push(structuredClone(prompt)); const ticket = prompt.messages[0].content ?? ""; const blocked = /can't|cannot|can not|down/i.test(ticket); return { content: blocked ? "High. The customer can't work until this is fixed." : "Normal. Nothing stops the customer from working.", finishReason: "stop", }; }, }; ``` - **`system`** is `systemInstructions`, or `""` if you didn't set any. - **`messages`** starts with one `{ role: "user", content }`. The model reads the input as JSON, so field names like `title` and `body` are part of what it reads: name them for the model. What the model sends back is the reply. `completion()` returns `{ content, finishReason }`, and `finishReason: "stop"` means the model is done, so its `content` is the agent's answer. The other value that matters is `"tool_calls"`, which the [next lesson](https://frontmcp.dev/learn/giving-an-agent-tools) covers. > **Pitfall: A `query` or `message` field hides the rest of the input** > > When the input has a field called `query`, `message`, `prompt` or `input`, and it isn't empty, FrontMCP sends the model that field alone, as it is, and drops everything else: > > Initial call configuration: > > ```js > { tool: "invoke_triage", arguments: { message: "Nothing works since your update.", customer: "Acme" } } > ``` > > ```ts triage.agent.ts active > import { Agent, AgentContext, z } from "@frontmcp/sdk"; > import { model } from "./model.example"; > > @Agent({ > name: "triage", > description: "Suggest a priority for a new support ticket. Pass what the customer wrote, and who they are.", > systemInstructions: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, and say why.", > inputSchema: { > message: z.string().describe("What the customer wrote"), > customer: z.string().describe("The customer's company"), > }, > llm: { adapter: model }, > }) > export class Triage extends AgentContext {} > ``` > > ```ts model.example.ts > // Stands in for a real model. It records what it was sent. > import type { AgentLlmAdapter, AgentPrompt } from "@frontmcp/sdk"; > > export const prompts: AgentPrompt[] = []; > > export const model: AgentLlmAdapter = { > async completion(prompt) { > prompts.push(structuredClone(prompt)); > return { content: "High. The customer can't work until this is fixed.", finishReason: "stop" }; > }, > }; > ``` > > ```ts message.test.ts > import { test, expect } from "@frontmcp/testing"; > import { prompts } from "./model.example"; > > test("🚩 the model never hears about the customer", async ({ mcp }) => { > await mcp.tools.call("invoke_triage", { message: "Nothing works since your update.", customer: "Acme" }); > expect(prompts[0].messages).toEqual([{ role: "user", content: "Nothing works since your update." }]); > }); > ``` > > That's handy for an agent that takes a single question as `query`, and a trap for one that takes more. Either give the fields other names, or write the message yourself: `AgentContext` builds it in `protected buildUserMessage(input)`, which returns a string, and you can override it. The [third challenge](https://frontmcp.dev/learn/your-first-agent#try-some-challenges) does. ## What comes back The agent's answer is the model's last reply. A reply that's text arrives as `{ response: text }`, as in the first example. A reply that's a JSON object arrives as that object. So when a client needs fields, not prose, ask the model for JSON, and declare what it should look like with `outputSchema`: Initial call configuration: ```js { tool: "invoke_triage", arguments: { title: "Cannot log in", body: "Since this morning nobody on our team can log in." } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Suggest a priority for a new support ticket, with a one-line reason. Pass the ticket's title and body.", systemInstructions: "You triage tickets for a help desk. Answer with JSON only: " + '{"priority": "high" | "normal" | "low", "reason": one sentence}. ' + "High is for anything that stops the customer from working.", inputSchema: { title: z.string().describe("The ticket's title"), body: z.string().describe("What the customer wrote"), }, outputSchema: { priority: z.enum(["high", "normal", "low"]), reason: z.string(), }, llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts model.example.ts // Stands in for a real model. It answers in JSON, as the instructions ask, but // when a customer shouts, it makes up a priority of its own, and a question // makes it forget the JSON, as models do now and then. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion(prompt) { const ticket = prompt.messages[0].content ?? ""; if (ticket.includes("?")) return { content: "Normal: it's a question.", finishReason: "stop" }; const priority = /!!!/.test(ticket) ? "urgent" : /can't|cannot|down/i.test(ticket) ? "high" : "normal"; const reason = priority === "normal" ? "Nothing stops the customer from working." : "The customer can't work."; return { content: JSON.stringify({ priority, reason }), finishReason: "stop" }; }, }; ``` ```ts output.test.ts import { test, expect } from "@frontmcp/testing"; test("a JSON reply is the result", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "Cannot log in", body: "Nobody on our team can log in." }); expect(result.json()).toEqual({ priority: "high", reason: "The customer can't work." }); expect(result.raw.structuredContent).toEqual(result.json()); }); test("`outputSchema` is in tools/list", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool.outputSchema).toMatchObject({ properties: { priority: { enum: ["high", "normal", "low"] }, reason: { type: "string" } }, required: ["priority", "reason"], }); }); test("a reply that doesn't match fails the call", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "DOWN AGAIN", body: "Fix it now!!!" }); expect(result).toBeError("INVALID_OUTPUT"); expect(result.text()).toBe("Tool output validation failed (output does not match outputSchema at priority)"); }); test("so does a reply that isn't JSON", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "Export", body: "How do I export my tickets?" }); expect(result).toBeError("INVALID_OUTPUT"); expect(result.text()).toBe("Tool output validation failed (output does not match outputSchema at priority)"); }); ``` FrontMCP checks the model's answer against `outputSchema` as it checks a tool's result. A reply with a priority the help desk doesn't have fails the call with `INVALID_OUTPUT`, and the text names the field that didn't match, `priority`. So does a reply that isn't JSON at all, because it arrives as `{ response }`, which has no `priority`. That's better than handing the client's model a priority nobody uses, but the call still failed, and whoever called it has to try again. Say exactly what you want in `systemInstructions`, and keep `outputSchema` as the check. Changed in 1.8.7: FrontMCP 1.8.5 and 1.8.6 sent this failure as a `TOOL_EXECUTION_ERROR` with a stack trace in the development text, where 1.8.4 sent `INVALID_OUTPUT`. In 1.8.7 it's `INVALID_OUTPUT` again, with only the one line. ## Recap - An agent is a class that extends `AgentContext`, decorated with `@Agent({ name, description, systemInstructions, inputSchema, llm })`, and registered with `@App({ agents: [...] })`. It needs no `execute()`. - A client sees one tool, `invoke_`, with the agent's `description` and `inputSchema`. The system instructions go to the agent's model only, so write a description for the client's model too. - `llm: { adapter }` takes any object with `completion(prompt, tools)`. It's called with `{ system, messages }` and returns `{ content, finishReason }`; `"stop"` ends the agent's work. - The model is sent the input as JSON, unless the input has a `query`, `message`, `prompt` or `input` field, which is then sent alone. Override `buildUserMessage(input)` to write the message yourself. - A text reply arrives as `{ response }`, a JSON object as itself. `outputSchema` is advertised and checked: a reply that doesn't match fails the call. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Register the agent, and describe it The `triage` agent is written, but a client connected to this server only finds `search_tickets`. Register the agent, and give it a description that tells the client's model what it's for: suggesting a priority for a ticket. ```ts main.ts active import { Agent, AgentContext, App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", systemInstructions: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, and say why.", inputSchema: { title: z.string(), body: z.string() }, llm: { adapter: model }, }) class Triage extends AgentContext {} @Tool({ name: "search_tickets", description: "Search tickets by words in their title", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [] }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { Agent, AgentContext, App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Suggest a priority for a new support ticket, with a one-line reason. Pass the ticket's title and body.", systemInstructions: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, and say why.", inputSchema: { title: z.string(), body: z.string() }, llm: { adapter: model }, }) class Triage extends AgentContext {} @Tool({ name: "search_tickets", description: "Search tickets by words in their title", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [] }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets], agents: [Triage] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts model.example.ts // Stands in for a real model, which the Playground can't reach. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion(prompt) { const blocked = /can't|cannot|down/i.test(prompt.messages[0].content ?? ""); return { content: blocked ? "High. The customer can't work." : "Normal. Nothing is blocked.", finishReason: "stop" }; }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts register.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`invoke_triage` is listed", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("invoke_triage"); }); test("its description mentions a priority", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "invoke_triage"); expect(tool?.description).toMatch(/priority/i); expect(tool?.description).not.toMatch(/^Invoke the triage agent/); }); test("it triages a ticket", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "Cannot log in", body: "Nobody can log in." }); expect(result.json()).toEqual({ response: "High. The customer can't work." }); }); ``` **Hint:** `@App` has a list for agents next to `tools`. The text the client's model reads is a different option from the one the agent's model reads. **Solution:** `agents: [Triage]` on `@App` adds the `invoke_triage` tool. Without a `description`, FrontMCP would have described it as "Invoke the triage agent." and the start of the system instructions, which are written for the agent's model. The description says what the tool is for and what to pass, for the model deciding whether to call it. ### Challenge: Keep the team the model suggests The model now also suggests which team should take the ticket, and says so in its JSON. But the result only has `priority` and `reason`: FrontMCP drops fields that `outputSchema` doesn't list. Add `team`, which is `"accounts"`, `"billing"` or `"product"`, so it reaches the client and clients know it's there. Initial call configuration: ```js { tool: "invoke_triage", arguments: { title: "Cannot log in", body: "Nobody on our team can log in." } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Suggest a priority and a team for a new support ticket. Pass the ticket's title and body.", systemInstructions: "You triage tickets for a help desk. Answer with JSON only: " + '{"priority": "high" | "normal" | "low", "team": "accounts" | "billing" | "product", "reason": one sentence}.', inputSchema: { title: z.string(), body: z.string() }, outputSchema: { priority: z.enum(["high", "normal", "low"]), reason: z.string(), }, llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` **Solution file (alternative to the starter):** ```ts triage.agent.ts solution import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Suggest a priority and a team for a new support ticket. Pass the ticket's title and body.", systemInstructions: "You triage tickets for a help desk. Answer with JSON only: " + '{"priority": "high" | "normal" | "low", "team": "accounts" | "billing" | "product", "reason": one sentence}.', inputSchema: { title: z.string(), body: z.string() }, outputSchema: { priority: z.enum(["high", "normal", "low"]), team: z.enum(["accounts", "billing", "product"]), reason: z.string(), }, llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts model.example.ts // Stands in for a real model, which the Playground can't reach. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion(prompt) { const ticket = prompt.messages[0].content ?? ""; const answer = /invoice|refund|charge/i.test(ticket) ? { priority: "normal", team: "billing", reason: "A billing question, and nothing is blocked." } : { priority: "high", team: "accounts", reason: "The customer can't log in." }; return { content: JSON.stringify(answer), finishReason: "stop" }; }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts team.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the result has the `team`", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "Cannot log in", body: "Nobody on our team can log in." }); expect(result.json()).toEqual({ priority: "high", team: "accounts", reason: "The customer can't log in." }); }); test("`team` is in the output schema, with its three values", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool.outputSchema?.properties?.team).toMatchObject({ enum: ["accounts", "billing", "product"] }); }); test("a billing ticket goes to `billing`", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { title: "Wrong invoice", body: "We were charged twice." }); expect(result.json().team).toBe("billing"); }); ``` **Hint:** The agent's result goes through the same check as a tool's: only what `outputSchema` describes gets through. **Solution:** `team: z.enum(["accounts", "billing", "product"])` in `outputSchema` lets the field through, advertises it in `tools/list`, and fails the call if the model ever names a team that doesn't exist. The instructions already asked for it; the schema is what makes FrontMCP keep it. ### Challenge: Tell the model who the customer is This agent takes the customer's `message` and their `plan`, because a customer on the `enterprise` plan gets High for anything that blocks them. But the model only ever gets the message. Make the user message it's sent contain both, for example `Plan: enterprise. Message: Nothing works since your update.`, without changing the agent's input schema. Initial call configuration: ```js { tool: "invoke_triage", arguments: { message: "Nothing works since your update.", plan: "enterprise" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Suggest a priority for a new support ticket. Pass what the customer wrote, and their plan.", systemInstructions: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, and say why.", inputSchema: { message: z.string().describe("What the customer wrote"), plan: z.enum(["free", "business", "enterprise"]).describe("The customer's plan"), }, llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` **Solution file (alternative to the starter):** ```ts triage.agent.ts solution import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; type Input = { message: string; plan: "free" | "business" | "enterprise" }; @Agent({ name: "triage", description: "Suggest a priority for a new support ticket. Pass what the customer wrote, and their plan.", systemInstructions: "You triage tickets for a help desk. Give the ticket a priority, High, Normal or Low, and say why.", inputSchema: { message: z.string().describe("What the customer wrote"), plan: z.enum(["free", "business", "enterprise"]).describe("The customer's plan"), }, llm: { adapter: model }, }) export class Triage extends AgentContext { protected buildUserMessage({ message, plan }: Input) { return `Plan: ${plan}. Message: ${message}`; } } ``` ```ts model.example.ts // Stands in for a real model. It records what it was sent. import type { AgentLlmAdapter, AgentPrompt } from "@frontmcp/sdk"; export const prompts: AgentPrompt[] = []; export const model: AgentLlmAdapter = { async completion(prompt) { prompts.push(structuredClone(prompt)); const ticket = prompt.messages[0].content ?? ""; return { content: /enterprise/.test(ticket) ? "High. An enterprise customer is blocked." : "Normal.", finishReason: "stop" }; }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts plan.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { prompts } from "./model.example"; test("the model is sent the plan", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { message: "Nothing works since your update.", plan: "enterprise" }); expect(prompts.at(-1)?.messages[0].content).toContain("enterprise"); }); test("and the message", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { message: "The export button is grey.", plan: "free" }); const content = prompts.at(-1)?.messages[0].content; expect(content).toContain("The export button is grey."); expect(content).toContain("free"); }); test("the input schema still has `message` and `plan`", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(Object.keys(tool.inputSchema.properties ?? {}).sort()).toEqual(["message", "plan"]); }); test("an enterprise customer gets High", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { message: "Nothing works since your update.", plan: "enterprise" }); expect(result.json()).toEqual({ response: "High. An enterprise customer is blocked." }); }); ``` **Hint:** Because the input has a field called `message`, FrontMCP sends that field alone. `AgentContext` has a method that builds the user message, and a subclass can override it. **Solution:** Overriding `buildUserMessage(input)` replaces FrontMCP's rule: whatever string it returns is the user message. Writing it yourself also lets you phrase it for the model, rather than sending raw JSON. Renaming `message` would have worked too, but it changes what clients send, which the challenge ruled out. --- # Giving an Agent Tools > Give a FrontMCP agent a limited tool set, follow its execution loop and handle tool failures before connecting a real model. Source: https://frontmcp.dev/learn/giving-an-agent-tools [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 The triage agent in the [last lesson](https://frontmcp.dev/learn/your-first-agent) could only judge what it was handed. A support agent triaging a ticket looks things up first: the ticket, the customer and their plan, and then sets the priority in the help desk. Give an agent tools, and its model can work the same way. FrontMCP runs a loop: it asks the model what to do, runs the tools the model asks for, sends back the results, and asks again, until the model answers. This lesson gives the triage agent tools, follows that loop step by step, and covers what happens when a tool fails, when the model won't stop, and how to add steps of your own. **You will learn** - How to give an agent tools, and which of them the client can see - How the loop runs: tool calls, results and the final answer - What the model hears when a tool fails - How to limit the loop with `maxIterations` and `timeout` - How to add your own steps before and after the loop, and report progress ## An agent with tools This agent takes a ticket id. To triage it, its model needs three tools: one to read the ticket, one to look up the customer, and one to set the priority. They're ordinary tools, and `tools` on `@Agent` hands them to the agent. Open the **Tests** tab: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; import { GetCustomer, GetTicket, SetPriority } from "./tools"; @Agent({ name: "triage", description: "Triage a support ticket: read it, look up its customer, and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket and look up its customer with get_customer. " + "Then set its priority with set_priority: high if the customer is on the enterprise plan or can't work, " + "low if they're on the free plan, normal otherwise. Finish with one sentence that says what you set.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket, GetCustomer, SetPriority], llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { customers, tickets } from "./store"; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return ticket; } } @Tool({ name: "get_customer", description: "Get a customer by id: their name and plan.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { const customer = customers.get(id); if (!customer) throw new PublicMcpError(`There's no customer ${id}.`); return customer; } } @Tool({ name: "set_priority", description: "Set a ticket's priority.", inputSchema: { id: z.string().describe("Ticket id, like T-1"), priority: z.enum(["high", "normal", "low"]), }, }) export class SetPriority extends ToolContext { async execute({ id, priority }: { id: string; priority: "high" | "normal" | "low" }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); ticket.priority = priority; return { id, priority }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { Triage } from "./triage.agent"; @App({ id: "help-desk", name: "Help Desk", agents: [Triage] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", customerId: "C-1", status: "open", priority: "none" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", customerId: "C-2", status: "open", priority: "none" }], ["T-3", { id: "T-3", title: "Export is slow", customerId: "C-3", status: "open", priority: "none" }], ]); export const customers = new Map([ ["C-1", { id: "C-1", name: "Acme", plan: "business" }], ["C-2", { id: "C-2", name: "Globex", plan: "enterprise" }], ["C-3", { id: "C-3", name: "Initech", plan: "free" }], ]); ``` ```ts model.example.ts // Stands in for a real model, which the Playground can't reach. It follows the // steps in the agent's instructions, one per request: read the ticket, look up // the customer, set the priority, answer. A real model works the steps out // itself, from the instructions and the tools it's offered. A real server // doesn't need this file. import type { AgentCompletion, AgentLlmAdapter, AgentPrompt, AgentToolDefinition } from "@frontmcp/sdk"; /** Every request FrontMCP made to the model, oldest first. */ export const requests: { prompt: AgentPrompt; tools?: AgentToolDefinition[] }[] = []; export const model: AgentLlmAdapter = { async completion(prompt, tools) { requests.push(structuredClone({ prompt, tools })); const { ticketId } = JSON.parse(prompt.messages[0].content ?? "{}"); const results = prompt.messages.filter((m) => m.role === "tool").map((m) => JSON.parse(m.content ?? "null")); const [ticket, customer, updated] = results; if (!ticket) return callTool("get_ticket", { id: ticketId }); if (!customer) return callTool("get_customer", { id: ticket.customerId }); if (!updated) return callTool("set_priority", { id: ticket.id, priority: choose(ticket, customer) }); return { content: `${ticket.id} is now ${updated.priority} priority.`, finishReason: "stop" }; }, }; function choose(ticket: { title: string }, customer: { plan: string }) { if (customer.plan === "enterprise" || /can't|cannot/i.test(ticket.title)) return "high"; return customer.plan === "free" ? "low" : "normal"; } function callTool(name: string, args: Record): AgentCompletion { return { content: null, finishReason: "tool_calls", toolCalls: [{ id: `call_${name}`, name, arguments: args }] }; } ``` ```ts triage.test.ts import { test, expect } from "@frontmcp/testing"; import { tickets } from "./store"; test("the agent sets the priority, and says so", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json()).toEqual({ response: "T-1 is now high priority." }); expect(tickets.get("T-1")?.priority).toBe("high"); }); test("an enterprise customer's ticket is high", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(tickets.get("T-2")?.priority).toBe("high"); }); test("a free customer's ticket is low", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-3" }); expect(tickets.get("T-3")?.priority).toBe("low"); }); ``` ```ts loop.test.ts import { test, expect } from "@frontmcp/testing"; import { requests } from "./model.example"; test("the model is offered the agent's tools, with JSON Schemas", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); const tools = requests[0].tools ?? []; expect(tools.map((t) => t.name)).toEqual(["get_ticket", "get_customer", "set_priority"]); expect(tools[0]).toEqual({ name: "get_ticket", description: "Get a support ticket by its id.", parameters: { $schema: "https://json-schema.org/draft/2020-12/schema", type: "object", properties: { id: { type: "string", description: "Ticket id, like T-1" } }, required: ["id"], }, }); }); test("each tool call and its result join the conversation", async ({ mcp }) => { const before = requests.length; await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(requests.length - before).toBe(4); const ticket = expect.stringMatching(/^\{"id":"T-1","title":"Cannot log in","customerId":"C-1"/); expect(requests.at(-1)?.prompt.messages).toEqual([ { role: "user", content: '{"ticketId":"T-1"}' }, { role: "assistant", content: null, toolCalls: [{ id: "call_get_ticket", name: "get_ticket", arguments: { id: "T-1" } }] }, { role: "tool", content: ticket, toolCallId: "call_get_ticket", name: "get_ticket" }, { role: "assistant", content: null, toolCalls: [{ id: "call_get_customer", name: "get_customer", arguments: { id: "C-1" } }] }, { role: "tool", content: '{"id":"C-1","name":"Acme","plan":"business"}', toolCallId: "call_get_customer", name: "get_customer" }, { role: "assistant", content: null, toolCalls: [{ id: "call_set_priority", name: "set_priority", arguments: { id: "T-1", priority: "high" } }] }, { role: "tool", content: '{"id":"T-1","priority":"high"}', toolCallId: "call_set_priority", name: "set_priority" }, ]); }); ``` The tools are written like any other; nothing in them knows an agent calls them. What's new is on `@Agent`: - **`tools: [GetTicket, GetCustomer, SetPriority]`** gives the agent's model these tools, and only these. - **`systemInstructions`** say which tool is for what, and in what order. A real model reads the tools' descriptions too, but the instructions are where you say how a support agent would go about it. The model in `model.example.ts` follows those instructions to the letter: its replies are the ones a real model would make on a good day, one step at a time. ## The loop, step by step One call to `invoke_triage` made four requests to the model, and the model in that example recorded each one. Open `loop.test.ts` in it: each request carries the whole conversation so far, and the test reads the last. This is the loop every agent runs: 1. FrontMCP sends the model the system instructions, the conversation, and the agent's tools, each as a name, a description and its input as JSON Schema. 2. The model replies with `finishReason: "tool_calls"` and a list of `toolCalls`, each with an `id` it makes up, a tool `name` and `arguments`. 3. FrontMCP adds that reply to the conversation, runs each tool call, and adds one `tool` message per call: the result as JSON, with the call's `id` as `toolCallId`. 4. It sends the longer conversation back to the model, and the model decides what to do next. 5. The first reply that isn't a tool call ends the loop. Its `content` is the agent's answer, as in the [last lesson](https://frontmcp.dev/learn/your-first-agent#what-comes-back). *[Illustration: An agent's loop. The MCP client makes one call, tools/call invoke_triage with a ticket id. Inside, in a loop of up to 10 turns, triage asks its model for a completion with the prompt and its tools; the model asks for get_ticket; triage runs get_ticket and gets the ticket's title and status; triage asks the model again with the tool result; the model answers. Triage returns that answer to the client as the call's result.]* Each request carries everything before it. By the fourth, the model is reading the ticket and the customer again, along with every tool's schema. That's what a model needs to decide the next step, and it's also what you pay for with a [real model](https://frontmcp.dev/learn/connecting-a-real-model#cost-and-latency). The tools' input is checked against their `inputSchema`, as for a client's call. When one reply asks for several tools, FrontMCP runs them one after another, in the order the model gave them; `execution` has no option to run them in parallel. ## What the client sees An agent's tools belong to the agent. They aren't in `tools/list`, and a client that calls one by name gets `TOOL_NOT_FOUND`. It works the other way too: by default, the agent's model is offered its own tools and nothing else, not even the app's: ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; import { Triage } from "./triage.agent"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title.", inputSchema: { query: z.string() }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [{ id: "T-1", title: "Cannot log in" }].filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets], agents: [Triage] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts visibility.test.ts import { test, expect } from "@frontmcp/testing"; import { Agent, AgentContext, App, FrontMcpInstance, z } from "@frontmcp/sdk"; import { SearchTickets } from "./main"; import { model, requests } from "./model.example"; import { GetTicket } from "./triage.agent"; test("the client sees the agent and the app's tool", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).toEqual(["invoke_triage", "search_tickets"]); }); test("the client can't call the agent's tools", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result).toBeError("TOOL_NOT_FOUND"); expect(result.text()).toBe('Tool "get_ticket" not found'); }); test("the agent's model isn't offered the app's tools", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(requests[0].tools?.map((t) => t.name)).toEqual(["get_ticket", "set_priority"]); }); test("unless the agent sets `inheritParentTools`", async () => { @Agent({ name: "triage", inputSchema: { ticketId: z.string() }, tools: [GetTicket], execution: { inheritParentTools: true }, llm: { adapter: model } }) class Triage extends AgentContext {} @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets], agents: [Triage] }) class HelpDeskApp {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); try { requests.length = 0; await server.callTool("invoke_triage", { ticketId: "T-1" }); expect(requests[0].tools?.map((t) => t.name)).toEqual(["get_ticket", "search_tickets"]); } finally { await server.dispose(); } }); ``` ```ts triage.agent.ts import { Agent, AgentContext, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; const tickets = new Map([["T-1", { id: "T-1", title: "Cannot log in", priority: "none" }]]); @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return ticket; } } @Tool({ name: "set_priority", description: "Set a ticket's priority.", inputSchema: { id: z.string(), priority: z.enum(["high", "normal", "low"]) } }) class SetPriority extends ToolContext { async execute({ id, priority }: { id: string; priority: "high" | "normal" | "low" }) { return { id, priority }; } } @Agent({ name: "triage", description: "Triage a support ticket and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket, then set its priority with set_priority.", inputSchema: { ticketId: z.string() }, tools: [GetTicket, SetPriority], llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts model.example.ts // Stands in for a real model. It records every request, and answers at once. import type { AgentLlmAdapter, AgentPrompt, AgentToolDefinition } from "@frontmcp/sdk"; export const requests: { prompt: AgentPrompt; tools?: AgentToolDefinition[] }[] = []; export const model: AgentLlmAdapter = { async completion(prompt, tools) { requests.push(structuredClone({ prompt, tools })); return { content: "T-1 is now high priority.", finishReason: "stop" }; }, }; ``` That split is often what you want. `set_priority` changes the help desk; with it inside the agent, a client can only set a priority by going through triage and its rules. When both should have a tool, like a read-only `get_ticket`, list the same class in `@App({ tools })` and in `@Agent({ tools })`. To offer the model every tool of the app, set `execution: { inheritParentTools: true }` on the agent: its model then gets the app's tools besides its own, other agents excepted, and they run as a client's call to them would. (New in 1.9: before, the option had no effect.) An agent that declares `resources` or `prompts` of its own also offers its model tools to read them, `list_resources` and `read_resource`, `list_prompts` and `get_prompt`: see [Reading the agent's resources and prompts](https://frontmcp.dev/reference/sdk/agent#reading-the-agents-resources-and-prompts). (New in 1.9.4.) ### Which providers an agent's tools see A tool inside an agent gets [providers](https://frontmcp.dev/learn/sharing-state-with-providers) as the app's own tools do: the app's and the server's. Here `TicketStore` is on the app, and `get_ticket` is both the client's and the agent's. Both calls find it: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts main.ts active import { Agent, AgentContext, App, FrontMcp, Provider, Tool, ToolContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Provider({ name: "TicketStore" }) export class TicketStore { find(id: string) { return id === "T-1" ? { id, title: "Cannot log in" } : undefined; } } @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return this.get(TicketStore).find(id); } } @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", inputSchema: { ticketId: z.string() }, tools: [GetTicket], llm: { adapter: model }, }) export class Triage extends AgentContext {} @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], agents: [Triage], providers: [TicketStore] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts model.example.ts // Stands in for a real model. It reads the ticket, and repeats what it heard. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion(prompt) { const heard = prompt.messages.find((m) => m.role === "tool"); if (heard) return { content: `Heard: ${heard.content}`, finishReason: "stop" }; return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "call_1", name: "get_ticket", arguments: { id: "T-1" } }] }; }, }; ``` ```ts providers.test.ts import { test, expect } from "@frontmcp/testing"; import { Agent, AgentContext, App, FrontMcpInstance, z } from "@frontmcp/sdk"; import { GetTicket, TicketStore } from "./main"; import { model } from "./model.example"; test("a client's call finds the app's provider", async ({ mcp }) => { expect((await mcp.tools.call("get_ticket", { id: "T-1" })).json()).toEqual({ id: "T-1", title: "Cannot log in" }); }); test("so does the same tool inside the agent", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json()).toEqual({ response: 'Heard: {"id":"T-1","title":"Cannot log in"}' }); }); test("a provider on @Agent is for the agent's tools", async () => { @Agent({ name: "triage", inputSchema: { ticketId: z.string() }, tools: [GetTicket], providers: [TicketStore], llm: { adapter: model } }) class Triage extends AgentContext {} @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], agents: [Triage] }) class HelpDeskApp {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); try { const result = await server.callTool("invoke_triage", { ticketId: "T-1" }); expect(result.structuredContent).toEqual({ response: 'Heard: {"id":"T-1","title":"Cannot log in"}' }); await expect(server.callTool("get_ticket", { id: "T-1" })).rejects.toThrow('Provider "TicketStore" is not available'); } finally { await server.dispose(); } }); ``` A provider that only the agent's tools use can go on the agent instead, with `@Agent({ providers })`, as the last test does: the app's tools don't see it there. (Changed in 1.9.2: before, an agent's tools didn't see the app's providers, only the server's and the agent's own.) The other examples on this page keep their data in a module, which every tool sees. ## When a tool fails A tool that fails doesn't end the loop. FrontMCP catches the error, and the model reads it as that tool's result, `{"error": "…"}`, then decides what to do. This model gets five things wrong in its first reply: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts model.example.ts active // Stands in for a real model. This one makes five mistakes in its first reply, // to show what the model hears back about each one. Then it gives up. import type { AgentLlmAdapter, AgentPrompt } from "@frontmcp/sdk"; export const prompts: AgentPrompt[] = []; export const model: AgentLlmAdapter = { async completion(prompt) { prompts.push(structuredClone(prompt)); if (prompt.messages.length > 1) return { content: "I couldn't triage T-1.", finishReason: "stop" }; return { content: null, finishReason: "tool_calls", toolCalls: [ { id: "call_1", name: "get_customer", arguments: { id: "C-9" } }, // a customer that doesn't exist { id: "call_2", name: "get_ticket", arguments: { id: "T-7" } }, // the database is down for this one { id: "call_3", name: "set_priority", arguments: { id: "T-1", priority: "urgent" } }, // not a priority { id: "call_4", name: "close_ticket", arguments: { id: "T-1" } }, // a tool the agent doesn't have { id: "call_5", name: "get_ticket", arguments: { id: "T-9" } }, // a ticket that doesn't exist ], }; }, }; ``` ```ts triage.agent.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; import { GetCustomer, GetTicket, SetPriority } from "./tools"; @Agent({ name: "triage", description: "Triage a support ticket: read it, look up its customer, and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket, look up its customer, then set its priority.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket, GetCustomer, SetPriority], llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { customers, findTicket } from "./store"; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = await findTicket(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } @Tool({ name: "get_customer", description: "Get a customer by id: their name and plan.", inputSchema: { id: z.string().describe("Customer id, like C-1") } }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { const customer = customers.get(id); if (!customer) throw new PublicMcpError(`There's no customer ${id}. Customer ids are on the ticket.`); return customer; } } @Tool({ name: "set_priority", description: "Set a ticket's priority.", inputSchema: { id: z.string().describe("Ticket id, like T-1"), priority: z.enum(["high", "normal", "low"]) }, }) export class SetPriority extends ToolContext { async execute({ id, priority }: { id: string; priority: "high" | "normal" | "low" }) { return { id, priority }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { Triage } from "./triage.agent"; @App({ id: "help-desk", name: "Help Desk", agents: [Triage] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts store.ts const tickets = new Map([["T-1", { id: "T-1", title: "Cannot log in", customerId: "C-1" }]]); export const customers = new Map([["C-1", { id: "C-1", name: "Acme", plan: "business" }]]); // Stands in for the ticket database, which fails for T-7 the way a database does when it's down. export async function findTicket(id: string) { if (id === "T-7") throw new Error("connect ECONNREFUSED 10.0.4.7:5432"); return tickets.get(id); } ``` ```ts failures.test.ts import { test, expect } from "@frontmcp/testing"; import { prompts } from "./model.example"; test("the model reads each failure as that tool's result", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); const results = prompts[1].messages.filter((m) => m.role === "tool").map((m) => m.content); expect(results).toEqual([ '{"error":"There\'s no customer C-9. Customer ids are on the ticket."}', '{"error":"Tool \\"get_ticket\\" execution failed: connect ECONNREFUSED 10.0.4.7:5432"}', '{"error":"Invalid tool input"}', '{"error":"Tool \\"close_ticket\\" not found in agent \\"triage\\". Available tools: [get_ticket, get_customer, set_priority]"}', '{"error":"There\'s no ticket T-9."}', ]); }); test("the call still succeeds, with whatever the model said", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ response: "I couldn't triage T-1." }); }); test("the client's log has a line for each failure", async ({ mcp }) => { const log = mcp.notifications.collect(); await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); const errors = log.received.filter((n) => n.params?.level === "error").map((n) => n.params?.data); expect(errors).toHaveLength(5); expect(errors[0]).toEqual({ message: "Tool get_customer failed: There's no customer C-9. Customer ids are on the ticket." }); expect(errors[1].message).toMatch(/^Tool get_ticket failed: Internal FrontMCP error\. Please contact support with error ID: err_\w+$/); }); ``` | What went wrong | What the model reads | | --- | --- | | The tool threw a `PublicMcpError`, or passed one to `this.fail()` | Its message, word for word. | | The tool threw any other error | `Tool "get_ticket" execution failed:` and the message. That's the development message, which the Playground shows. | | The arguments don't match the tool's `inputSchema` | `Invalid tool input`, and nothing about which argument or why. | | The agent has no tool by that name | `Tool "close_ticket" not found in agent "triage".`, and the names it does have. | So the model hears about every failure and can try something else: ask for the right customer id, try again, or say it couldn't. `invoke_triage` succeeded, and its answer is all the client's model gets: it hears about a failure only if the agent's model says so. The client's log does get a line for each failure, as the last test shows, from the messages an agent sends about its loop (see [Progress during the loop](https://frontmcp.dev/learn/giving-an-agent-tools#progress-during-the-loop)). That line has the public message only: a `PublicMcpError`'s, or else FrontMCP's generic `Internal FrontMCP error` with an error id, so the database's address stays on the server. The server's own log line for the failure has the same id and the whole error. (Changed in 1.9.3: before, the client's log line had `connect ECONNREFUSED 10.0.4.7:5432`.) Two things follow. Fail with a `PublicMcpError` whose message says what to do next, because that's the only kind of failure that tells the model something it can act on. And give every argument a `.describe()`, with the allowed values: a model that gets `Invalid tool input` has to guess what it got wrong. ## Limiting the loop The model decides when the loop ends, and a model can keep asking for tools without getting anywhere. FrontMCP stops it after `execution.maxIterations` requests to the model, 10 by default, and fails the call. `execution.timeout` limits the whole loop in milliseconds, 120000 by default: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, Tool, ToolContext, z } from "@frontmcp/sdk"; import { model, slowModel } from "./model.example"; export const searches: string[] = []; @Tool({ name: "search_tickets", description: "Search tickets by words in their title.", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { searches.push(query); return { tickets: [] }; } } @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", systemInstructions: "You triage support tickets. Look for similar tickets first.", inputSchema: { ticketId: z.string() }, tools: [SearchTickets], llm: { adapter: model }, execution: { maxIterations: 3 }, }) export class Triage extends AgentContext {} @Agent({ name: "summarize", description: "Summarize a support ticket in one sentence. Pass the ticket id.", inputSchema: { ticketId: z.string() }, tools: [SearchTickets], llm: { adapter: slowModel }, execution: { timeout: 300 }, }) export class Summarize extends AgentContext {} ``` ```ts model.example.ts // Stand-ins for real models. `model` never finds what it's looking for, and // keeps searching. `slowModel` takes 200 ms to answer each request, and // searches twice before it answers. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export let requests = 0; export const model: AgentLlmAdapter = { async completion() { requests++; const query = ["log in", "login", "sign in", "password"][requests % 4]; return { content: null, finishReason: "tool_calls", toolCalls: [{ id: `call_${requests}`, name: "search_tickets", arguments: { query } }] }; }, }; export const slowModel: AgentLlmAdapter = { async completion(prompt) { await new Promise((resolve) => setTimeout(resolve, 200)); const searches = prompt.messages.filter((m) => m.role === "tool").length; if (searches === 2) return { content: "A customer can't log in.", finishReason: "stop" }; const query = searches === 0 ? "log in" : "login"; return { content: null, finishReason: "tool_calls", toolCalls: [{ id: `call_${searches}`, name: "search_tickets", arguments: { query } }] }; }, }; ``` ```ts limits.test.ts import { test, expect } from "@frontmcp/testing"; import { requests } from "./model.example"; import { searches } from "./triage.agent"; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("the model is asked 3 times, and the call fails", async ({ mcp }) => { const before = requests; const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(requests - before).toBe(3); expect(result).toBeError("AGENT_LOOP_EXCEEDED"); expect(result.text()).toMatch(/^Agent "triage" exceeded maximum iterations \(3\)/); }); test("a timeout fails the call and stops later tools", async ({ mcp }) => { const before = searches.length; const result = await mcp.tools.call("invoke_summarize", { ticketId: "T-1" }); expect(result).toBeError("AGENT_TIMEOUT"); expect(result.text()).toMatch(/^Agent "summarize" execution timed out after 300ms/); expect(result.durationMs).toBeLessThan(400); expect(searches.length - before).toBe(1); // the first search, before the timeout await wait(250); expect(searches.length - before).toBe(1); // no second tool starts after the timeout }); ``` With `maxIterations: 3`, the model is asked three times and the tool runs three times. The last result never reaches the model, and the call fails with `AGENT_LOOP_EXCEEDED`: `Agent "triage" exceeded maximum iterations (3)`. With `timeout: 300`, the call fails with `AGENT_TIMEOUT`: `Agent "summarize" execution timed out after 300ms`. These public messages reach production clients too. Changed in 1.11.3: before, these were `TOOL_EXECUTION_ERROR` failures. > **Pitfall: Pass the signal to work that can be cancelled** > > A timeout aborts the agent's signal and stops later model turns and tool calls. Work already running can finish if it ignores the signal. Pass `this.signal` to requests that support cancellation, and keep tools that change things safe to repeat. Changed in 1.11.3: before, the loop continued after the timeout. Set `maxIterations` from what the task needs. Triage takes four requests on a good day, so 6 leaves room for a retry or two, while the default of 10 lets a confused model make ten paid requests before anyone hears about it. Set `timeout` below the time your clients wait for a tool call. ## Before and after the loop `AgentContext` runs the loop in `execute(input)`. Override it to do something before the model is asked, after it's done, or instead, and call `super.execute(input)` for the loop itself. The model's answer is a sentence; this agent adds the priority the ticket actually has in the store, which a client can rely on: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; const tickets = new Map([["T-1", { id: "T-1", title: "Cannot log in", priority: "none" }]]); @Tool({ name: "set_priority", description: "Set a ticket's priority.", inputSchema: { id: z.string(), priority: z.enum(["high", "normal", "low"]) } }) class SetPriority extends ToolContext { async execute({ id, priority }: { id: string; priority: "high" | "normal" | "low" }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); ticket.priority = priority; return { id, priority }; } } @Agent({ name: "triage", description: "Triage a support ticket and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. Set the ticket's priority with set_priority, then say what you did.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [SetPriority], llm: { adapter: model }, }) export class Triage extends AgentContext { async execute(input: { ticketId: string }) { const answer = await super.execute(input); // the loop return { ...answer, priority: tickets.get(input.ticketId)?.priority ?? "none" }; } } ``` ```ts model.example.ts // Stands in for a real model: sets a priority, then answers in a sentence. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion(prompt) { if (prompt.messages.some((m) => m.role === "tool")) return { content: "I've looked at T-1 and set its priority.", finishReason: "stop" }; return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "call_1", name: "set_priority", arguments: { id: "T-1", priority: "high" } }] }; }, }; ``` ```ts execute.test.ts import { test, expect } from "@frontmcp/testing"; test("the result has the model's answer and the stored priority", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json()).toEqual({ response: "I've looked at T-1 and set its priority.", priority: "high" }); }); ``` What `execute()` returns is the result. Before the loop, `this.fail()` works as in a tool, and ends the call without a single request to the model: the [second challenge](https://frontmcp.dev/learn/giving-an-agent-tools#try-some-challenges) uses it to refuse closed tickets. ### Each request and each tool call Inside the loop, `AgentContext` calls two more methods you can override. `completion(prompt, tools, options)` sends one request to the model, and `executeTool(name, args)` runs one tool call the model asked for. An override of either sees every one, and can change what goes in or what comes back; call `super` to do the work: ```ts triage.agent.ts active import { Agent, AgentContext, Tool, ToolContext, z } from "@frontmcp/sdk"; import type { AgentCompletion, AgentCompletionOptions, AgentPrompt, AgentToolDefinition } from "@frontmcp/sdk"; import { model } from "./model.example"; export const overrides: string[] = []; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string() } }) class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in" }; } } @Agent({ name: "triage", inputSchema: { ticketId: z.string() }, tools: [GetTicket], llm: { adapter: model } }) export class Triage extends AgentContext { protected async completion(prompt: AgentPrompt, tools?: AgentToolDefinition[], options?: AgentCompletionOptions): Promise { overrides.push(`completion: ${prompt.messages.length} message(s)`); // each request to the model return super.completion(prompt, tools, options); } protected async executeTool(name: string, args: Record) { overrides.push(`executeTool: ${name}`); // each tool call return super.executeTool(name, args); } } ``` ```ts model.example.ts // Stands in for a real model: reads the ticket, then answers. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion(prompt) { if (prompt.messages.some((m) => m.role === "tool")) return { content: "T-1 is high priority.", finishReason: "stop" }; return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "call_1", name: "get_ticket", arguments: { id: "T-1" } }] }; }, }; ``` ```ts overrides.test.ts import { test, expect } from "@frontmcp/testing"; import { overrides } from "./triage.agent"; test("the loop calls `completion()` for each request and `executeTool()` for each tool call", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json()).toEqual({ response: "T-1 is high priority." }); expect(overrides).toEqual(["completion: 1 message(s)", "executeTool: get_ticket", "completion: 3 message(s)"]); }); ``` Pass `tools` and `options` on to `super.completion()`: without `tools`, the model isn't offered any. `options` holds what the agent's `llm` sets for every request, `temperature` and `maxTokens`, and is empty for an `adapter` of your own. To change what a tool does for everyone who calls it, change the tool or add a [hook](https://frontmcp.dev/learn/hooking-into-calls) instead. (Changed in 1.9.2: before, the loop called the adapter directly, and a `completion()` override never ran. Before 1.9, an `executeTool()` override never ran either.) ## Progress during the loop An agent's call takes as long as all its requests to the model and all its tool calls together. With a real model that's seconds to minutes, and the client's user waits the whole time. What can the client hear before the answer arrives? Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, Tool, ToolContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string() } }) class GetTicket extends ToolContext { async execute({ id }: { id: string }) { await this.notify(`Reading ticket ${id}`); return { id, title: "Cannot log in", status: "open" }; } } @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket first.", inputSchema: { ticketId: z.string() }, tools: [GetTicket], llm: { adapter: model }, execution: { enableAutoProgress: true }, }) export class Triage extends AgentContext { async execute(input: { ticketId: string }) { await this.notify("Starting triage"); return super.execute(input); } } ``` ```ts model.example.ts // Stands in for a real model: reads the ticket, then answers. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion(prompt) { if (prompt.messages.some((m) => m.role === "tool")) return { content: "T-1 is high priority.", finishReason: "stop" }; return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "call_1", name: "get_ticket", arguments: { id: "T-1" } }] }; }, }; ``` ```ts progress.test.ts import { test, expect } from "@frontmcp/testing"; test("the client hears from the agent and from its tools", async ({ mcp }) => { const notifications = mcp.notifications.collect(); await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); const messages = notifications.received.filter((n) => n.method === "notifications/message"); expect(messages.map((n) => n.params)).toEqual([ { level: "info", logger: "triage", data: { message: "Starting triage" } }, { level: "info", logger: "triage", data: { message: "Identified 1 tool call(s): get_ticket" } }, { level: "info", logger: "triage", data: { message: "Calling tool: get_ticket" } }, { level: "info", logger: "get_ticket", data: { message: "Reading ticket T-1" } }, ]); }); test("`enableAutoProgress` reports the loop's progress", async ({ mcp }) => { const notifications = mcp.notifications.collect(); await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); const progress = notifications.received.filter((n) => n.method === "notifications/progress"); expect(progress.map(({ params: { progress, total, message } }) => ({ progress, total, message }))).toEqual([ { progress: 0, total: 100, message: "Starting LLM call (iteration 1/10)" }, { progress: 100, total: 100, message: "Agent completed" }, ]); }); ``` The client hears from the agent and from the tools it runs, during the call, and the Call tab shows it all above the result: - The agent's own `this.notify()` and `this.progress()` send [notifications](https://frontmcp.dev/learn/reporting-progress) as a tool's do: `Starting triage`. - For each tool call the model asks for, the agent sends `Calling tool: get_ticket`, and `Tool get_ticket failed: …` with the error's public message, at level `error`, when the call fails. `execution: { enableNotifications: false }` turns these off. - The tools send their own, as usual: `Reading ticket T-1`. - `execution: { enableAutoProgress: true }` adds progress updates as the loop goes, out of 100, and an `Identified 1 tool call(s)` message for each reply that asks for tools. It sends at most one update per `execution.notificationInterval`, 1000 ms by default, besides the last, so a loop as quick as this one reports only its start and its end. - `execution: { enableStreaming: true }` sends the model's text as it's written instead, each piece as a progress update, when the model can stream: see [Streaming the reply](https://frontmcp.dev/reference/sdk/agent#streaming-the-reply). (New in 1.9.4: before, the option had no effect.) (Changed in 1.9.2: before, under MCP 2026-07-28, none of the agent's own messages reached the client, only its tools'.) ## Recap - `@Agent({ tools: [...] })` gives the agent's model those tools, and by default no others. The client can't see or call them; list a tool in `@App({ tools })` too when both should have it, or set `execution.inheritParentTools` to offer the model all of the app's. - The loop: FrontMCP sends the conversation and the tools' schemas, runs each tool call the model asks for, one at a time, adds the results as `tool` messages, and asks again, until a reply isn't a tool call. - A failing tool doesn't end the loop: the model reads `{"error": "…"}`. Only a `PublicMcpError` tells it something useful; bad arguments only say `Invalid tool input`. The client's model hears nothing unless the agent's model says so. - `execution.maxIterations` (10) and `execution.timeout` (120000 ms) fail with `AGENT_LOOP_EXCEEDED` and `AGENT_TIMEOUT`. A timeout aborts the signal and stops later model turns and tools. - Override `execute(input)` and call `super.execute(input)` to add steps before and after. Override `completion()` to see each request to the model, and `executeTool()` to see each tool call. - During the loop, the client hears from the agent's `this.notify()` and `this.progress()`, a `Calling tool: …` message per tool call, and the tools' own notifications; `enableAutoProgress` adds progress for each step. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Give the agent the tool it needs The instructions tell the model to look up the customer, but the agent doesn't have `get_customer`, so the model is told the tool doesn't exist and sets every priority to normal. Give the agent the tool, without letting clients call it directly. Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-2" } } ``` ```ts main.ts active import { Agent, AgentContext, App, FrontMcp, z } from "@frontmcp/sdk"; import { model } from "./model.example"; import { GetCustomer, GetTicket, SetPriority } from "./tools"; @Agent({ name: "triage", description: "Triage a support ticket: read it, look up its customer, and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket and look up its customer with get_customer. " + "Then set its priority with set_priority: high for the enterprise plan, normal otherwise.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket, SetPriority], llm: { adapter: model }, }) class Triage extends AgentContext {} @App({ id: "help-desk", name: "Help Desk", agents: [Triage] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { Agent, AgentContext, App, FrontMcp, z } from "@frontmcp/sdk"; import { model } from "./model.example"; import { GetCustomer, GetTicket, SetPriority } from "./tools"; @Agent({ name: "triage", description: "Triage a support ticket: read it, look up its customer, and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket and look up its customer with get_customer. " + "Then set its priority with set_priority: high for the enterprise plan, normal otherwise.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket, GetCustomer, SetPriority], llm: { adapter: model }, }) class Triage extends AgentContext {} @App({ id: "help-desk", name: "Help Desk", agents: [Triage] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { customers, tickets } from "./store"; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return ticket; } } @Tool({ name: "get_customer", description: "Get a customer by id: their name and plan.", inputSchema: { id: z.string() } }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { const customer = customers.get(id); if (!customer) throw new PublicMcpError(`There's no customer ${id}.`); return customer; } } @Tool({ name: "set_priority", description: "Set a ticket's priority.", inputSchema: { id: z.string(), priority: z.enum(["high", "normal", "low"]) } }) export class SetPriority extends ToolContext { async execute({ id, priority }: { id: string; priority: "high" | "normal" | "low" }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); ticket.priority = priority; return { id, priority }; } } ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", customerId: "C-1", priority: "none" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", customerId: "C-2", priority: "none" }], ]); export const customers = new Map([ ["C-1", { id: "C-1", name: "Acme", plan: "business" }], ["C-2", { id: "C-2", name: "Globex", plan: "enterprise" }], ]); ``` ```ts model.example.ts // Stands in for a real model. It follows the instructions, and when a tool // fails, it carries on without it. import type { AgentCompletion, AgentLlmAdapter, AgentToolDefinition } from "@frontmcp/sdk"; export const offered: string[][] = []; export const model: AgentLlmAdapter = { async completion(prompt, tools?: AgentToolDefinition[]) { offered.push((tools ?? []).map((t) => t.name)); const { ticketId } = JSON.parse(prompt.messages[0].content ?? "{}"); const [ticket, customer, updated] = prompt.messages.filter((m) => m.role === "tool").map((m) => JSON.parse(m.content ?? "null")); if (!ticket) return callTool("get_ticket", { id: ticketId }); if (!customer) return callTool("get_customer", { id: ticket.customerId }); if (!updated) return callTool("set_priority", { id: ticketId, priority: customer.plan === "enterprise" ? "high" : "normal" }); return { content: `${ticketId} is now ${updated.priority} priority.`, finishReason: "stop" }; }, }; function callTool(name: string, args: Record): AgentCompletion { return { content: null, finishReason: "tool_calls", toolCalls: [{ id: `call_${name}`, name, arguments: args }] }; } ``` **Hidden fixture/test file (runs with the example):** ```ts tools.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { tickets } from "./store"; import { offered } from "./model.example"; test("the model is offered `get_customer`", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(offered.at(-1)).toContain("get_customer"); }); test("Globex is on enterprise, so T-2 is high", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(result.json()).toEqual({ response: "T-2 is now high priority." }); expect(tickets.get("T-2")?.priority).toBe("high"); }); test("a client still can't call `get_customer`", async ({ mcp }) => { expect(await mcp.tools.list()).not.toContainTool("get_customer"); }); ``` **Hint:** Look at what the agent's `tools` lists. A tool in `@App({ tools })` is the client's, not the agent's. **Solution:** Adding `GetCustomer` to `@Agent({ tools })` offers it to the agent's model, and only to it. Before, the model's call got `Tool "get_customer" not found in agent "triage"` as its result, carried on without a plan, and set `normal`. Adding it to `@App({ tools })` instead would have let clients call it, and still not given it to the agent. ### Challenge: Don't triage closed tickets Triage runs on closed tickets too, which wastes a request to the model and changes the priority of a ticket nobody is working on. Refuse a closed ticket before the model is asked, with a `PublicMcpError` that says it's closed. Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-4" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, PublicMcpError, z } from "@frontmcp/sdk"; import { model } from "./model.example"; import { tickets } from "./store"; import { GetTicket, SetPriority } from "./tools"; @Agent({ name: "triage", description: "Triage an open support ticket and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket, then set its priority with set_priority.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket, SetPriority], llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` **Solution file (alternative to the starter):** ```ts triage.agent.ts solution import { Agent, AgentContext, PublicMcpError, z } from "@frontmcp/sdk"; import { model } from "./model.example"; import { tickets } from "./store"; import { GetTicket, SetPriority } from "./tools"; @Agent({ name: "triage", description: "Triage an open support ticket and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket, then set its priority with set_priority.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket, SetPriority], llm: { adapter: model }, }) export class Triage extends AgentContext { async execute(input: { ticketId: string }) { if (tickets.get(input.ticketId)?.status === "closed") { this.fail(new PublicMcpError(`${input.ticketId} is closed. Reopen it before triaging it.`)); } return super.execute(input); } } ``` ```ts tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return ticket; } } @Tool({ name: "set_priority", description: "Set a ticket's priority.", inputSchema: { id: z.string(), priority: z.enum(["high", "normal", "low"]) } }) export class SetPriority extends ToolContext { async execute({ id, priority }: { id: string; priority: "high" | "normal" | "low" }) { const ticket = tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); ticket.priority = priority; return { id, priority }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { Triage } from "./triage.agent"; @App({ id: "help-desk", name: "Help Desk", agents: [Triage] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open", priority: "none" }], ["T-4", { id: "T-4", title: "Refund not received", status: "closed", priority: "normal" }], ]); ``` ```ts model.example.ts // Stands in for a real model: reads the ticket, sets a priority, answers. import type { AgentCompletion, AgentLlmAdapter } from "@frontmcp/sdk"; /** The ticket ids the model was asked about, oldest first. */ export const asked: string[] = []; export const model: AgentLlmAdapter = { async completion(prompt) { const { ticketId } = JSON.parse(prompt.messages[0].content ?? "{}"); asked.push(ticketId); const [ticket, updated] = prompt.messages.filter((m) => m.role === "tool").map((m) => JSON.parse(m.content ?? "null")); if (!ticket) return callTool("get_ticket", { id: ticketId }); if (!updated) return callTool("set_priority", { id: ticketId, priority: "high" }); return { content: `${ticketId} is now ${updated.priority} priority.`, finishReason: "stop" }; }, }; function callTool(name: string, args: Record): AgentCompletion { return { content: null, finishReason: "tool_calls", toolCalls: [{ id: `call_${name}`, name, arguments: args }] }; } ``` **Hidden fixture/test file (runs with the example):** ```ts closed.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { asked } from "./model.example"; import { tickets } from "./store"; test("a closed ticket fails with `PUBLIC_ERROR`", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-4" }); expect(result).toBeError("PUBLIC_ERROR"); expect(result.text()).toMatch(/closed/i); }); test("the model is never asked about it", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-4" }); expect(asked).not.toContain("T-4"); expect(tickets.get("T-4")?.priority).toBe("normal"); }); test("an open ticket is still triaged", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json()).toEqual({ response: "T-1 is now high priority." }); }); ``` **Hint:** The loop runs in a method you can override. Check the ticket first, and only then call the method you overrode. **Solution:** Overriding `execute(input)` puts your code in front of the loop. `this.fail()` with a `PublicMcpError` ends the call before `super.execute(input)` runs, so no request goes to the model and no tool runs. Leaving the check to the model would cost a request, and depends on the model obeying an instruction it may not follow. --- # Connecting a Real Model > Connect a FrontMCP agent to Anthropic or OpenAI: API keys, requests and replies, provider failures, and what a real model costs in tokens and time. Source: https://frontmcp.dev/learn/connecting-a-real-model [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every agent in this chapter so far has run a `model.example.ts`: a few lines that follow a script. A real agent runs a real model, and FrontMCP comes with adapters for two providers, Anthropic and OpenAI. This lesson connects the triage agent to one, shows exactly what FrontMCP sends the provider and how it reads the answer, and covers what a real model changes: API keys, failures and retries, cost and waiting. **You will learn** - How to connect an agent to Anthropic or OpenAI, and which package each needs - Where the API key comes from, and what happens when it's missing - What FrontMCP sends the provider, and how it reads the reply - What a failing provider does to a call, and how retries add up - What a real model costs in requests, tokens and time > **Note** > > The Playground can't reach a model provider: it runs in your browser, with no network and no API key, and the providers' packages aren't in it. So the configuration in this lesson is plain code, to run on your own machine. The examples that do run use FrontMCP's real adapters, with a stand-in for the provider's client, the way the earlier lessons used a stand-in for the model. ## Choosing a provider Replace the stand-in with `provider`, `model` and `apiKey`: ```ts triage.agent.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { GetCustomer, GetTicket, SetPriority } from "./tools"; @Agent({ name: "triage", description: "Triage a support ticket: read it, look up its customer, and set its priority. Pass the ticket id.", systemInstructions: "You triage support tickets. …", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket, GetCustomer, SetPriority], llm: { provider: "anthropic", model: "claude-opus-5", apiKey: { env: "ANTHROPIC_API_KEY" }, }, }) export class Triage extends AgentContext {} ``` And install the provider's package next to `@frontmcp/sdk`. FrontMCP doesn't depend on either, and loads it the first time an agent asks the model: ```bash yarn add @anthropic-ai/sdk # for provider: "anthropic" yarn add openai # for provider: "openai" ``` If the package is missing, the server still starts, and every call to the agent fails with `The "@anthropic-ai/sdk" package is not installed.`, after about seven seconds of [retries](https://frontmcp.dev/learn/connecting-a-real-model#when-the-provider-fails). That's a Node-only failure, so there's no example of it here. | `llm` option | Type | | | --- | --- | --- | | `provider` | `"anthropic"` or `"openai"` | Which adapter FrontMCP builds. | | `model` | `string` | The provider's model id, sent with every request. | | `apiKey` | `{ env: string }` or `string` | Where the key comes from, [below](https://frontmcp.dev/learn/connecting-a-real-model#where-the-key-comes-from). | | `baseUrl` | `string` | Optional. Another address for the provider's API. | | `maxTokens` | `number` | Optional. The longest reply, in tokens. Anthropic's API requires one, and FrontMCP sends `4096` when you don't. | | `temperature` | `number` | Optional. Sent as is; leave it out for models that don't take it. | `provider` is a shorthand: it builds an `AnthropicAdapter` or an `OpenAIAdapter`, both exported from `@frontmcp/sdk`. Build one yourself for what the shorthand doesn't cover, and pass it as `llm: { adapter }`: ```ts import Anthropic from "@anthropic-ai/sdk"; import { AnthropicAdapter, OpenAIAdapter } from "@frontmcp/sdk"; // OpenAI's Responses API, instead of Chat Completions new OpenAIAdapter({ model: "gpt-5", apiKey: process.env.OPENAI_API_KEY!, api: "responses" }); // Any service with an OpenAI-compatible API new OpenAIAdapter({ model: "my-model", apiKey: process.env.GATEWAY_KEY!, baseUrl: "https://llm-gateway.internal/v1" }); // A client you've configured yourself, and fewer retries new AnthropicAdapter({ model: "claude-opus-5", client: new Anthropic(), maxRetries: 1 }); ``` For anything else, write an adapter: an object with `completion(prompt, tools)`, like the stand-ins in this chapter, that calls your provider. ## Where the key comes from `apiKey: { env: "ANTHROPIC_API_KEY" }` reads the variable once, when the server starts. If it isn't set, the server doesn't start. In the Playground no variable is ever set, so the test builds a second server with a real provider, and watches it fail: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts key.test.ts active import { test, expect } from "@frontmcp/testing"; import { Agent, AgentContext, App, FrontMcpInstance } from "@frontmcp/sdk"; test("without the variable, the server doesn't start", async () => { @Agent({ name: "triage", llm: { provider: "anthropic", model: "claude-opus-5", apiKey: { env: "HELP_DESK_ANTHROPIC_KEY" } }, }) class Triage extends AgentContext {} @App({ id: "help-desk", name: "Help Desk", agents: [Triage] }) class HelpDeskApp {} const starting = FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); await expect(starting).rejects.toThrow("Environment variable HELP_DESK_ANTHROPIC_KEY is not set"); }); ``` ```ts triage.agent.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { model } from "./model.example"; @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", inputSchema: { ticketId: z.string() }, llm: { adapter: model }, }) export class Triage extends AgentContext {} ``` ```ts model.example.ts // Stands in for a real model, so this example's own server starts. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const model: AgentLlmAdapter = { async completion() { return { content: "T-1 is high priority.", finishReason: "stop" }; }, }; ``` That's what you want: a server with a missing key fails at once, when it's deployed, not on the first call a user makes. `apiKey` also takes the key itself as a string, but then it's in your source code and everywhere your source code goes. Keep keys in the environment, or in your platform's secret store, which sets the environment for you. The key is your server's, not the user's. Every call to the agent, from any client, is paid for by that key, so an agent is one more reason to [authenticate clients](https://frontmcp.dev/learn/authenticating-clients) and [limit calls](https://frontmcp.dev/learn/limiting-calls). ## What FrontMCP sends the provider An adapter turns FrontMCP's prompt into the provider's request, and the provider's reply back into `{ content, finishReason, toolCalls }`. `AnthropicAdapter` takes an Anthropic client, so here it gets a stand-in that records each request and answers the way Anthropic's Messages API does. Open the **Tests** tab: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, AnthropicAdapter, Tool, ToolContext, z } from "@frontmcp/sdk"; import { anthropic } from "./anthropic.example"; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") } }) class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket, then give its priority and why.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket], llm: { adapter: new AnthropicAdapter({ model: "claude-opus-5", client: anthropic }) }, }) export class Triage extends AgentContext {} ``` ```ts anthropic.example.ts // Stands in for the client from @anthropic-ai/sdk, which the Playground can't // use: there's no network and no API key. It has the one method FrontMCP calls, // messages.create(), records every request, and answers in the Messages API's // shape: first with a tool call, then with text. A real server passes // `new Anthropic()`, or uses `provider: "anthropic"`. /** Every request "Anthropic" received, oldest first. */ export const requests: any[] = []; export const anthropic = { messages: { async create(params: any): Promise { requests.push(structuredClone(params)); if (params.messages.length === 1) { return { content: [{ type: "tool_use", id: "toolu_01", name: "get_ticket", input: { id: "T-1" } }], stop_reason: "tool_use", usage: { input_tokens: 612, output_tokens: 48 }, }; } return { content: [{ type: "text", text: "High: the customer can't log in." }], stop_reason: "end_turn", usage: { input_tokens: 703, output_tokens: 12 }, }; }, }, }; ``` ```ts anthropic.test.ts import { test, expect } from "@frontmcp/testing"; import { requests } from "./anthropic.example"; test("the first request: instructions, input and tools", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(requests[0]).toEqual({ model: "claude-opus-5", max_tokens: 4096, stream: false, system: "You triage support tickets. Read the ticket with get_ticket, then give its priority and why.", messages: [{ role: "user", content: '{"ticketId":"T-1"}' }], tools: [ { name: "get_ticket", description: "Get a support ticket by its id.", input_schema: { $schema: "https://json-schema.org/draft/2020-12/schema", type: "object", properties: { id: { type: "string", description: "Ticket id, like T-1" } }, required: ["id"], }, }, ], }); }); test("the second request adds the tool call and its result", async ({ mcp }) => { const before = requests.length; await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(requests.length - before).toBe(2); expect(requests.at(-1).messages).toEqual([ { role: "user", content: '{"ticketId":"T-1"}' }, { role: "assistant", content: [{ type: "tool_use", id: "toolu_01", name: "get_ticket", input: { id: "T-1" } }] }, { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_01", content: '{"id":"T-1","title":"Cannot log in","status":"open"}' }], }, ]); }); test("the text reply is the agent's answer", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json()).toEqual({ response: "High: the customer can't log in." }); }); ``` `OpenAIAdapter` does the same for OpenAI's Chat Completions API. Its stand-in has `chat.completions.create()`: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts openai.test.ts active import { test, expect } from "@frontmcp/testing"; import { requests } from "./openai.example"; test("the instructions are the first message, and tools are functions", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(requests[0]).toMatchObject({ model: "gpt-5", stream: false, messages: [ { role: "system", content: "You triage support tickets. Read the ticket with get_ticket, then give its priority and why." }, { role: "user", content: '{"ticketId":"T-1"}' }, ], tools: [{ type: "function", function: { name: "get_ticket", description: "Get a support ticket by its id." } }], }); }); test("a tool result is a `tool` message", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(requests.at(-1).messages.slice(2)).toEqual([ { role: "assistant", content: null, tool_calls: [{ id: "call_01", type: "function", function: { name: "get_ticket", arguments: '{"id":"T-1"}' } }], }, { role: "tool", content: '{"id":"T-1","title":"Cannot log in","status":"open"}', tool_call_id: "call_01" }, ]); }); ``` ```ts triage.agent.ts import { Agent, AgentContext, OpenAIAdapter, Tool, ToolContext, z } from "@frontmcp/sdk"; import { openai } from "./openai.example"; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") } }) class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket, then give its priority and why.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket], llm: { adapter: new OpenAIAdapter({ model: "gpt-5", client: openai }) }, }) export class Triage extends AgentContext {} ``` ```ts openai.example.ts // Stands in for the client from the openai package, which the Playground can't // use. It records every request and answers in the Chat Completions shape. /** Every request "OpenAI" received, oldest first. */ export const requests: any[] = []; export const openai = { chat: { completions: { async create(params: any): Promise { requests.push(structuredClone(params)); const message = params.messages.some((m: any) => m.role === "tool") ? { role: "assistant", content: "High: the customer can't log in." } : { role: "assistant", content: null, tool_calls: [{ id: "call_01", type: "function", function: { name: "get_ticket", arguments: '{"id":"T-1"}' } }] }; return { choices: [{ message, finish_reason: message.content ? "stop" : "tool_calls" }], usage: { prompt_tokens: 540, completion_tokens: 20, total_tokens: 560 }, }; }, }, }, responses: { async create(): Promise { throw new Error("This example uses Chat Completions."); }, }, }; ``` | FrontMCP's prompt | Anthropic request | OpenAI request | | --- | --- | --- | | `system` | `system` | The first message, `role: "system"` | | A `user` message | `role: "user"` | `role: "user"` | | The model's tool calls | `tool_use` blocks in an `assistant` message | `tool_calls` on an `assistant` message, `arguments` as a JSON string | | A tool's result | A `tool_result` block in a `user` message | A `tool` message with `tool_call_id` | | The agent's tools | `tools`, each with `input_schema` | `tools`, each `{ type: "function", function }` | Coming back, a reply with tool calls becomes `finishReason: "tool_calls"`, and the loop runs them; anything else ends it. That includes a reply cut short by the token limit, which [the loop treats as the answer](https://frontmcp.dev/learn/connecting-a-real-model#cost-and-latency). ## When the provider fails Providers fail: they rate-limit you, have outages, or reject your key. An adapter retries a failed request before it gives up, `maxRetries` times, 3 by default, waiting 1 second, then 2, then 4. When it gives up, the agent's call fails with the provider's message. This example keeps the waits short with `maxRetries: 1`: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, OpenAIAdapter, z } from "@frontmcp/sdk"; import { openai } from "./openai.example"; @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", inputSchema: { ticketId: z.string() }, llm: { adapter: new OpenAIAdapter({ model: "gpt-5", client: openai, maxRetries: 1 }) }, }) export class Triage extends AgentContext {} ``` ```ts openai.example.ts // Stands in for the openai client. The first request for T-1 is rate-limited, // and every request for T-2 is refused, as if the key were wrong. export const received: string[] = []; function fail(status: number, message: string) { return Object.assign(new Error(message), { status }); } export const openai = { chat: { completions: { async create(params: any): Promise { const ticket = JSON.parse(params.messages.at(-1).content).ticketId; received.push(ticket); if (ticket === "T-2") throw fail(401, "401 Incorrect API key provided: sk-proj-****. You can find your API key at https://platform.openai.com/account/api-keys."); if (received.filter((t) => t === ticket).length === 1) throw fail(429, "429 Rate limit reached for gpt-5"); return { choices: [{ message: { role: "assistant", content: `${ticket} is high priority.` }, finish_reason: "stop" }] }; }, }, }, responses: { async create(): Promise { throw new Error("This example uses Chat Completions."); }, }, }; ``` ```ts retries.test.ts import { test, expect } from "@frontmcp/testing"; import { received } from "./openai.example"; test("a rate-limited request is tried again a second later", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json()).toEqual({ response: "T-1 is high priority." }); expect(received.filter((t) => t === "T-1")).toHaveLength(2); expect(result.durationMs).toBeGreaterThanOrEqual(1_000); }); test("🚩 a wrong key is tried again too, and then fails the call", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(received.filter((t) => t === "T-2")).toHaveLength(2); expect(result).toBeError("TOOL_EXECUTION_ERROR"); expect(result.text()).toMatch(/^Tool "invoke_triage" execution failed: Agent LLM error: 401 Incorrect API key provided/); }); ``` Retrying a rate limit is right: the second request worked. Retrying a wrong key isn't, because it will never work, but in 1.9.3 the adapter only gives up at once on a few messages, like `invalid api key` or `unauthorized`, and OpenAI's wording is `Incorrect API key provided`. With the default `maxRetries: 3`, a wrong key or a missing package costs every call seven seconds before it fails. Two more things add up: - **Retries are per request.** A loop that makes four requests can wait through retries four times, and all of it counts against the agent's [`execution.timeout`](https://frontmcp.dev/learn/giving-an-agent-tools#limiting-the-loop), 2 minutes by default. - **The client waits.** The client's model called one tool and is waiting for its answer. Keep `maxRetries` low for agents that clients call directly, and set `execution.timeout` below what your clients wait for a tool call. When the call fails, the development message above names the provider's error. In production, FrontMCP hides the message of a `TOOL_EXECUTION_ERROR`, so the client only learns that the call failed. ## Cost and latency Each turn of the loop is one request to the provider, and each request carries everything so far: the system instructions, every tool's schema, the input, and every tool call and result. So the input grows with every turn, and you pay for all of it every time. The adapter reports what each request used, as `usage`, and the loop drops it. To see it, wrap the adapter in one of your own, or override the agent's [`completion()`](https://frontmcp.dev/learn/giving-an-agent-tools#each-request-and-each-tool-call), as the [last challenge](https://frontmcp.dev/learn/connecting-a-real-model#try-some-challenges) does: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, AnthropicAdapter, Tool, ToolContext, z } from "@frontmcp/sdk"; import type { AgentCompletion, AgentLlmAdapter } from "@frontmcp/sdk"; import { anthropic } from "./anthropic.example"; /** What each request to the model used, oldest first. */ export const usage: AgentCompletion["usage"][] = []; function counted(inner: AgentLlmAdapter): AgentLlmAdapter { return { async completion(prompt, tools, options) { const reply = await inner.completion(prompt, tools, options); usage.push(reply.usage); return reply; }, }; } @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") } }) class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open", body: "Since this morning nobody on our team can log in." }; } } @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket, then give its priority and why.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket], llm: { adapter: counted(new AnthropicAdapter({ model: "claude-opus-5", client: anthropic, maxTokens: 12 })) }, }) export class Triage extends AgentContext {} ``` ```ts anthropic.example.ts // Stands in for the Anthropic client. It counts a token as four characters of // the request, and cuts its answer off at max_tokens, as a real model does. export const anthropic = { messages: { async create(params: any): Promise { const input_tokens = Math.ceil(JSON.stringify(params).length / 4); if (params.messages.length === 1) { return { content: [{ type: "tool_use", id: "toolu_01", name: "get_ticket", input: { id: "T-1" } }], stop_reason: "tool_use", usage: { input_tokens, output_tokens: 40 }, }; } const words = "High priority: nobody at the customer can log in, so their whole team is blocked.".split(" "); const cut = words.length > params.max_tokens; return { content: [{ type: "text", text: words.slice(0, params.max_tokens).join(" ") }], stop_reason: cut ? "max_tokens" : "end_turn", usage: { input_tokens, output_tokens: Math.min(words.length, params.max_tokens) }, }; }, }, }; ``` ```ts cost.test.ts import { test, expect } from "@frontmcp/testing"; import { usage } from "./triage.agent"; test("each request reports its usage, and the second is bigger", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); const [first, second] = usage; expect(first).toEqual({ promptTokens: expect.any(Number), completionTokens: 40, totalTokens: expect.any(Number) }); expect(second!.promptTokens).toBeGreaterThan(first!.promptTokens); }); test("🚩 an answer cut off at `maxTokens` is still the answer", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ response: "High priority: nobody at the customer can log in, so their whole" }); }); ``` `maxTokens` caps each reply, and this example sets it far too low on purpose. The provider stopped mid-sentence, and FrontMCP's loop took the half sentence as the answer: it ends at any reply that isn't a tool call, including one that ran out of tokens, and says nothing about it. Leave `maxTokens` at the default, or raise it; lower it only when you know how long answers are. What makes an agent cost more, and take longer: - **The number of requests.** Every turn is a request, and the client waits for all of them. `execution.maxIterations` caps it, [10 by default](https://frontmcp.dev/learn/giving-an-agent-tools#limiting-the-loop). - **What each request repeats.** Instructions, tool descriptions and schemas are sent every turn. Give an agent the tools its task needs, not every tool you have. - **What tools return.** Every result stays in the conversation until the end. A tool an agent uses should return what the model needs, not the whole record: the same advice as for [shaping tool results](https://frontmcp.dev/learn/shaping-tool-results), and it matters more here, because the result is paid for again on every later turn. - **Where it runs.** An agent spends your key on behalf of whoever calls it. Put agents behind [authentication](https://frontmcp.dev/learn/authenticating-clients) and [rate limits](https://frontmcp.dev/learn/limiting-calls). ## The other direction: `connectOpenAI()` and friends FrontMCP also exports `connectOpenAI()`, `connectClaude()`, `connectLangChain()` and `connectVercelAI()`. Despite the names, they don't connect an agent to a model. They go the other way: they connect *your* code to a FrontMCP server, in-process, and hand you its tools in the shape that provider's API or library expects. They're for when your own program runs the model and the loop, and the FrontMCP server is only the tools. [Running FrontMCP Anywhere](https://frontmcp.dev/learn/running-frontmcp-anywhere#calling-your-tools-through-a-client-connect) shows them. | You want | Use | | --- | --- | | Your MCP server to run a model loop of its own, as a tool clients call | `@Agent` with `llm` | | Your own program to run the model loop, with a FrontMCP server's tools | `connectClaude()`, `connectOpenAI()`, … | ## Recap - `llm: { provider: "anthropic" | "openai", model, apiKey: { env } }` connects an agent to a real model. Install `@anthropic-ai/sdk` or `openai`; FrontMCP loads it on the first request. - `apiKey: { env }` is read when the server starts, and a missing variable stops the server from starting. Keep keys out of your source. - `AnthropicAdapter` and `OpenAIAdapter` are what `provider` builds. Build one yourself for `api: "responses"`, `baseUrl`, your own `client`, or `maxRetries`. - Adapters retry a failed request 3 times, waiting 1, 2 and 4 seconds, including failures that can't succeed, like a wrong key. A call that still fails is a `TOOL_EXECUTION_ERROR`. - Every turn is a request carrying the whole conversation. Wrap the adapter, or override the agent's `completion()`, to see `usage`. A reply cut off at `maxTokens` becomes the answer, silently. - `connectOpenAI()` and friends connect your own code to a FrontMCP server; they aren't model adapters. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Fail fast when the provider is busy This agent is called directly by clients, and the provider is rate-limiting every request. With `maxRetries: 2`, each call waits three seconds before it fails. Make a rate-limited call fail at once, after a single request. Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, OpenAIAdapter, z } from "@frontmcp/sdk"; import { openai } from "./openai.example"; @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", inputSchema: { ticketId: z.string() }, llm: { adapter: new OpenAIAdapter({ model: "gpt-5", client: openai, maxRetries: 2 }) }, }) export class Triage extends AgentContext {} ``` **Solution file (alternative to the starter):** ```ts triage.agent.ts solution import { Agent, AgentContext, OpenAIAdapter, z } from "@frontmcp/sdk"; import { openai } from "./openai.example"; @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", inputSchema: { ticketId: z.string() }, llm: { adapter: new OpenAIAdapter({ model: "gpt-5", client: openai, maxRetries: 0 }) }, }) export class Triage extends AgentContext {} ``` ```ts openai.example.ts // Stands in for the openai client, on a bad day: every request is rate-limited. export let requests = 0; export const openai = { chat: { completions: { async create(): Promise { requests++; throw Object.assign(new Error("429 Rate limit reached for gpt-5"), { status: 429 }); }, }, }, responses: { async create(): Promise { throw new Error("This example uses Chat Completions."); }, }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts fast.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { requests } from "./openai.example"; test("the call fails with the provider's message", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result).toBeError("TOOL_EXECUTION_ERROR"); expect(result.text()).toContain("429 Rate limit reached"); }); test("it fails within half a second", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.durationMs).toBeLessThan(500); }); test("the provider gets one request per call", async ({ mcp }) => { const before = requests; await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(requests - before).toBe(1); }); ``` **Hint:** The waits come from the adapter, not from the agent's `execution` options. Count how many requests `maxRetries: 2` makes. **Solution:** `maxRetries` is how many times the adapter tries again after the first request, so `0` means one request and no waiting. The client's model gets the failure straight away and can tell the user, instead of holding the call for 1 + 2 seconds of retries that, during an outage, won't help. Jobs and other background work can afford more retries than a call someone is waiting on. ### Challenge: Report the tokens each call used Support wants to see what triage costs. Add `tokens` to the agent's result: the total tokens, input and output, of every request that call made, even when two calls run at the same time. The model's answer should still be in `response`. Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, AnthropicAdapter, Tool, ToolContext, z } from "@frontmcp/sdk"; import { anthropic } from "./anthropic.example"; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string() } }) class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket, then give its priority and why.", inputSchema: { ticketId: z.string() }, tools: [GetTicket], llm: { adapter: new AnthropicAdapter({ model: "claude-opus-5", client: anthropic }) }, }) export class Triage extends AgentContext {} ``` **Solution file (alternative to the starter):** ```ts triage.agent.ts solution import { Agent, AgentContext, AnthropicAdapter, Tool, ToolContext, z } from "@frontmcp/sdk"; import type { AgentCompletion, AgentCompletionOptions, AgentPrompt, AgentToolDefinition } from "@frontmcp/sdk"; import { anthropic } from "./anthropic.example"; @Tool({ name: "get_ticket", description: "Get a support ticket by its id.", inputSchema: { id: z.string() } }) class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Agent({ name: "triage", description: "Triage a support ticket. Pass the ticket id.", systemInstructions: "You triage support tickets. Read the ticket with get_ticket, then give its priority and why.", inputSchema: { ticketId: z.string() }, tools: [GetTicket], llm: { adapter: new AnthropicAdapter({ model: "claude-opus-5", client: anthropic }) }, }) export class Triage extends AgentContext { private tokens = 0; protected async completion(prompt: AgentPrompt, tools?: AgentToolDefinition[], options?: AgentCompletionOptions): Promise { const reply = await super.completion(prompt, tools, options); this.tokens += reply.usage?.totalTokens ?? 0; return reply; } async execute(input: { ticketId: string }) { const answer = await super.execute(input); return { ...answer, tokens: this.tokens }; } } ``` ```ts anthropic.example.ts // Stands in for the Anthropic client: a tool call, then an answer, with the // usage a real response reports. export const anthropic = { messages: { async create(params: any): Promise { if (params.messages.length === 1) { return { content: [{ type: "tool_use", id: "toolu_01", name: "get_ticket", input: { id: "T-1" } }], stop_reason: "tool_use", usage: { input_tokens: 600, output_tokens: 40 }, }; } return { content: [{ type: "text", text: "High: the customer can't log in." }], stop_reason: "end_turn", usage: { input_tokens: 700, output_tokens: 15 }, }; }, }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts tokens.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the result has `tokens`: 600 + 40 + 700 + 15", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json().tokens).toBe(1355); }); test("it's counted per call, not in total", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json().tokens).toBe(1355); }); test("two calls at once count their own", async ({ mcp }) => { const [a, b] = await Promise.all([mcp.tools.call("invoke_triage", { ticketId: "T-1" }), mcp.tools.call("invoke_triage", { ticketId: "T-1" })]); expect([a.json().tokens, b.json().tokens]).toEqual([1355, 1355]); }); test("the answer is still in `response`", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json().response).toBe("High: the customer can't log in."); }); ``` **Hint:** The loop drops each reply's `usage`, so catch it on the way, in a method the loop calls for every request. Keep the count where each call has its own, and add it to the result where the agent's result is made. **Solution:** The loop calls the agent's `completion()` for every request, so an override sees every reply, and adds up `usage.totalTokens`, which `AnthropicAdapter` fills in from the response's `input_tokens` and `output_tokens`. FrontMCP creates the agent's class for each call, so `this.tokens` belongs to one call, even when two run at once. Overriding `execute()` adds it to the result after `super.execute(input)`. A wrapping adapter, as in [Cost and latency](https://frontmcp.dev/learn/connecting-a-real-model#cost-and-latency), sees the same replies, but it's shared by every call, so it can't tell two calls at once apart. --- # Agents That Call Agents > How one FrontMCP agent hands a task to another: nested agents, swarm handoffs, this.callTool() from execute(), handling failures, and the handoff depth limit. Source: https://frontmcp.dev/learn/agents-that-call-agents [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 The triage agent reads a ticket and decides who should handle it. When the ticket is about an invoice, the best one to answer it is another agent: a billing agent, with billing's tools and billing's rules. This lesson connects the two on one FrontMCP server, in two ways: by letting triage's model call billing, and by handing the ticket to billing from triage's own code, where your code decides. **You will learn** - What two agents on one server see of each other, and what the client sees - How `agents: [...]` and `swarm` let one agent's model call another - How to hand a task to another agent from `execute()` with `this.callTool()` - What to do when the other agent fails - How FrontMCP stops handoffs that never end, and how to stop them sooner ## Two agents on one server Billing questions need an invoice tool and billing's rules, which triage shouldn't carry around. So the help desk gets a second agent, `billing`, with its own tool and its own instructions, registered on the app next to `triage`. As in the rest of this chapter, `model.example.ts` stands in for the models, which the Playground can't reach; with two agents, it has one model for each. Open the **Tests** tab: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-2" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { BillingAgent, TriageAgent } from "./agents"; @App({ id: "help-desk", name: "Help Desk", agents: [TriageAgent, BillingAgent] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts agents.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { billingModel, triageModel } from "./model.example"; import { GetInvoice, GetTicket } from "./tools"; @Agent({ name: "triage", description: "Read a support ticket and say who should handle it.", systemInstructions: "Read the ticket with get_ticket, then say who should handle it.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket], llm: { adapter: triageModel }, }) export class TriageAgent extends AgentContext {} @Agent({ name: "billing", description: "Answer a customer's question about an invoice or a charge.", systemInstructions: "Look the invoice up with get_invoice. Refund duplicate charges; never refund more than was charged.", inputSchema: { question: z.string().describe("The customer's question, with the invoice number") }, tools: [GetInvoice], llm: { adapter: billingModel }, }) export class BillingAgent extends AgentContext {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets: Record = { "T-1": "I can't log in since this morning.", "T-2": "I was charged twice for invoice INV-7.", }; @Tool({ name: "get_ticket", description: "Get a support ticket by id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, text: tickets[id] ?? "" }; } } @Tool({ name: "get_invoice", description: "Get an invoice, with how many times it was charged.", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, amount: "49 EUR", charges: 2 }; } } ``` ```ts model.example.ts // Stand-ins for the models the two agents would call. The Playground can't reach a // real model, so each one follows a script: on the first turn it calls its tool, and // on the second it answers from the tool's result. `seen` records the tools each // model was offered. A real server doesn't need this file: see Connecting a Real Model. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const seen: Record = { triage: [], billing: [] }; export const triageModel: AgentLlmAdapter = { async completion(prompt, tools = []) { seen.triage.push(tools.map((tool) => tool.name)); const last = prompt.messages.at(-1)!; if (last.role === "user") { const { ticketId } = JSON.parse(last.content!); return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "c1", name: "get_ticket", arguments: { id: ticketId } }] }; } const ticket = JSON.parse(last.content!); if (/invoice|charge/i.test(ticket.text)) { return { content: `${ticket.id} is a billing question: ask the billing agent about it.`, finishReason: "stop" }; } return { content: `${ticket.id} is a login problem: the accounts team should take it.`, finishReason: "stop" }; }, }; export const billingModel: AgentLlmAdapter = { async completion(prompt, tools = []) { seen.billing.push(tools.map((tool) => tool.name)); const last = prompt.messages.at(-1)!; if (last.role === "user") { const invoiceId = last.content!.match(/INV-\d+/)?.[0]; return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "c1", name: "get_invoice", arguments: { id: invoiceId } }] }; } const invoice = JSON.parse(last.content!); return { content: `${invoice.id} was charged twice: refund the second charge of ${invoice.amount}.`, finishReason: "stop" }; }, }; ``` ```ts agents.test.ts import { test, expect } from "@frontmcp/testing"; import { seen } from "./model.example"; test("the client sees both agents, and none of their tools", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name).sort(); expect(names).toEqual(["invoke_billing", "invoke_triage"]); }); test("the client's model can chain the two", async ({ mcp }) => { const triage = await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(triage.json()).toEqual({ response: "T-2 is a billing question: ask the billing agent about it." }); const billing = await mcp.tools.call("invoke_billing", { question: "I was charged twice for invoice INV-7." }); expect(billing.json()).toEqual({ response: "INV-7 was charged twice: refund the second charge of 49 EUR." }); }); test("each model is offered only its own agent's tools", async () => { expect(seen.triage).toEqual([["get_ticket"], ["get_ticket"]]); expect(seen.billing).toEqual([["get_invoice"], ["get_invoice"]]); }); ``` Each agent is a tool for the client, `invoke_triage` and `invoke_billing`, and a closed room inside: triage's model is offered `get_ticket` and nothing else, billing's is offered `get_invoice`. Neither model knows the other agent exists. So the client's model does the connecting. It calls `invoke_triage`, reads that T-2 is a billing question, and calls `invoke_billing` with the customer's words. That's often enough, and it's the simplest arrangement. It costs a round trip through the client's model, though, and only works if that model thinks of it. For the help desk, a ticket should go in and an answer come out, so the next step is to let triage ask billing itself. ## Letting triage's model call billing `@Agent({ agents })` lists the agents an agent may call. Here billing moves into triage's `agents`, and out of the app's: it's triage's helper now, not the client's. Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-2" } } ``` ```ts agents.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { billingModel, triageModel } from "./model.example"; import { GetInvoice, GetTicket } from "./tools"; @Agent({ name: "billing", description: "Answer a customer's question about an invoice or a charge.", systemInstructions: "Look the invoice up with get_invoice. Refund duplicate charges; never refund more than was charged.", inputSchema: { question: z.string().describe("The customer's question, with the invoice number") }, tools: [GetInvoice], llm: { adapter: billingModel }, }) export class BillingAgent extends AgentContext {} @Agent({ name: "triage", description: "Read a support ticket and answer it, asking the billing agent about invoices and charges.", systemInstructions: "Read the ticket with get_ticket. Ask the billing agent about invoices and charges, and pass on its answer.", inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket], agents: [BillingAgent], // triage's model may call billing llm: { adapter: triageModel }, }) export class TriageAgent extends AgentContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { TriageAgent } from "./agents"; @App({ id: "help-desk", name: "Help Desk", agents: [TriageAgent] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets: Record = { "T-1": "I can't log in since this morning.", "T-2": "I was charged twice for invoice INV-7.", }; @Tool({ name: "get_ticket", description: "Get a support ticket by id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, text: tickets[id] ?? "" }; } } @Tool({ name: "get_invoice", description: "Get an invoice, with how many times it was charged.", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, amount: "49 EUR", charges: 2 }; } } ``` ```ts model.example.ts // Stand-ins for the two agents' models. Triage's reads the ticket, asks billing // about charges, and passes billing's answer on; billing's looks the invoice up. // `seen` records the tools each model was offered. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const seen: Record = { triage: [], billing: [] }; export const triageModel: AgentLlmAdapter = { async completion(prompt, tools = []) { seen.triage.push(tools.map((tool) => tool.name)); const last = prompt.messages.at(-1)!; if (last.role === "user") { const { ticketId } = JSON.parse(last.content!); return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "c1", name: "get_ticket", arguments: { id: ticketId } }] }; } if (last.name === "get_ticket") { const ticket = JSON.parse(last.content!); if (!/invoice|charge/i.test(ticket.text)) { return { content: `${ticket.id} is a login problem: the accounts team should take it.`, finishReason: "stop" }; } return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "c2", name: "invoke_billing", arguments: { question: ticket.text } }] }; } return { content: JSON.parse(last.content!).response, finishReason: "stop" }; }, }; export const billingModel: AgentLlmAdapter = { async completion(prompt, tools = []) { seen.billing.push(tools.map((tool) => tool.name)); const last = prompt.messages.at(-1)!; if (last.role === "user") { const invoiceId = last.content!.match(/INV-\d+/)?.[0]; return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "c1", name: "get_invoice", arguments: { id: invoiceId } }] }; } const invoice = JSON.parse(last.content!); return { content: `${invoice.id} was charged twice: refund the second charge of ${invoice.amount}.`, finishReason: "stop" }; }, }; ``` ```ts nested.test.ts import { test, expect } from "@frontmcp/testing"; import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { BillingAgent } from "./agents"; import { seen, triageModel } from "./model.example"; test("a billing ticket comes back with billing's answer", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(result.json()).toEqual({ response: "INV-7 was charged twice: refund the second charge of 49 EUR." }); }); test("triage's model is offered billing as a tool, and billing's model its own", async ({ mcp }) => { await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(seen.triage[0]).toEqual(["get_ticket", "invoke_billing"]); expect(seen.billing[0]).toEqual(["get_invoice"]); }); test("the client sees triage only", async ({ mcp }) => { expect((await mcp.tools.list()).map((t) => t.name)).toEqual(["invoke_triage"]); expect(await mcp.tools.call("invoke_billing", { question: "Was INV-7 charged twice?" })).toBeError("TOOL_NOT_FOUND"); }); test("an agent class in another agent's `tools` is refused when the agent is declared", () => { expect(() => { @Agent({ name: "triage", inputSchema: { ticketId: z.string() }, tools: [BillingAgent as never], llm: { adapter: triageModel } }) class Triage extends AgentContext {} }).toThrow("tools items must be annotated with @Tool()"); }); ``` Triage's model is offered a third tool now, `invoke_billing`, with billing's `description` and input. When it calls it, FrontMCP runs billing's whole loop, with billing's model, tools and instructions, and hands billing's answer back to triage's model as the call's result. The client made one call. It can't call billing itself: an agent in another agent's `agents` belongs to that agent. List agents in `agents`, not in `tools`, which only takes tools, as the last test shows. When billing should stay a tool of the server, which clients can call too, register both agents on the app, side by side, and give triage `swarm: { canSeeOtherAgents: true }`. Its model is then offered the app's other agents, and `visibleAgents: ["billing"]` narrows them to the ones you name. The [`@Agent` reference](https://frontmcp.dev/reference/sdk/agent#calling-other-agents) shows both. Changed in 1.9: before, FrontMCP accepted `agents` and `swarm` on an `@Agent` and ignored them, so triage's model was offered `get_ticket` and nothing else. > **Pitfall: The model decides whether to call billing** > > Triage's instructions ask its model to ask billing about charges, and this stand-in always does. A real model usually will, and sometimes won't: it may answer a billing question itself, or ask billing something else. When a billing ticket must reach billing, don't leave it to the model. Do it in code, as the next section does. ## Handing a task off from code An agent can call another the way it would call any tool on the server. It has [`this.callTool(name, args)`](https://frontmcp.dev/reference/sdk/call-tool), which runs a tool through the server's normal call flow, and to the server, an agent on the app is the tool `invoke_`. So billing goes back on the app, next to triage, and triage keeps its model loop and adds a step [after it, in `execute()`](https://frontmcp.dev/learn/giving-an-agent-tools#before-and-after-the-loop). Its instructions now ask the model to answer with a *handoff* when a ticket is about billing, and `execute()` acts on it: *[Illustration: A handoff from code. The MCP client makes one call, invoke_triage. Triage asks its model which team should take the ticket, and the model answers with a handoff to billing. Triage's execute() then calls this.callTool with invoke_billing; billing runs its own loop with its own model and tools and returns its answer as a CallToolResult; triage returns billing's answer to the client, which only ever saw the one call.]* Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-2" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { triageModel } from "./model.example"; import { GetTicket } from "./tools"; type Answer = { response?: string; handoff?: "billing"; question?: string }; @Agent({ name: "triage", description: "Read a support ticket and answer it, or hand billing questions to the billing agent.", systemInstructions: "Read the ticket with get_ticket, then say who should handle it. If it's about an invoice or a " + 'charge, answer only with {"handoff": "billing", "question": ""}.', inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket], llm: { adapter: triageModel }, }) export class TriageAgent extends AgentContext { async execute(input: { ticketId: string }) { const answer = (await super.execute(input)) as Answer; // triage's own model loop if (answer.handoff === "billing") { const result = await this.callTool("invoke_billing", { question: answer.question }); return result.structuredContent as Answer; } return answer; } } ``` ```ts billing.agent.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { billingModel } from "./model.example"; @Agent({ name: "billing", description: "Answer a customer's question about an invoice or a charge.", inputSchema: { question: z.string().describe("The customer's question, with the invoice number") }, hideFromDiscovery: true, // triage is the way in llm: { adapter: billingModel }, }) export class BillingAgent extends AgentContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { BillingAgent } from "./billing.agent"; import { TriageAgent } from "./triage.agent"; @App({ id: "help-desk", name: "Help Desk", agents: [TriageAgent, BillingAgent] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets: Record = { "T-1": "I can't log in since this morning.", "T-2": "I was charged twice for invoice INV-7.", }; @Tool({ name: "get_ticket", description: "Get a support ticket by id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, text: tickets[id] ?? "" }; } } ``` ```ts model.example.ts // Stand-ins for the two agents' models. Triage's model follows its instructions: // billing tickets get a handoff. Billing's model answers at once here. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const triageModel: AgentLlmAdapter = { async completion(prompt) { const last = prompt.messages.at(-1)!; if (last.role === "user") { const { ticketId } = JSON.parse(last.content!); return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "c1", name: "get_ticket", arguments: { id: ticketId } }] }; } const ticket = JSON.parse(last.content!); if (/invoice|charge/i.test(ticket.text)) { return { content: JSON.stringify({ handoff: "billing", question: ticket.text }), finishReason: "stop" }; } return { content: `${ticket.id} is a login problem: the accounts team should take it.`, finishReason: "stop" }; }, }; export const billingModel: AgentLlmAdapter = { async completion() { return { content: "INV-7 was charged twice: refund the second charge of 49 EUR.", finishReason: "stop" }; }, }; ``` ```ts handoff.test.ts import { test, expect } from "@frontmcp/testing"; test("a billing ticket comes back with billing's answer", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(result.json()).toEqual({ response: "INV-7 was charged twice: refund the second charge of 49 EUR." }); }); test("any other ticket comes back with triage's answer", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json()).toEqual({ response: "T-1 is a login problem: the accounts team should take it." }); }); test("only triage is listed, but billing can still be called by name", async ({ mcp }) => { expect((await mcp.tools.list()).map((t) => t.name)).toEqual(["invoke_triage"]); expect(await mcp.tools.call("invoke_billing", { question: "Was INV-7 charged twice?" })).toBeSuccessful(); }); ``` Read `execute()` from the top: 1. **`super.execute(input)`** runs triage's own loop: its model reads the ticket and answers. For T-2 the answer is the text `{"handoff": "billing", "question": "I was charged twice for invoice INV-7."}`, and FrontMCP turns a final answer that parses as JSON into an object, so `answer.handoff` is `"billing"`. 2. **`this.callTool("invoke_billing", { question })`** runs the billing agent, with its own model, tools and instructions, as if a client had called `invoke_billing`. 3. **`result.structuredContent`** is billing's answer, `{ response: "…" }`, and triage returns it as its own. The model decides *whether* to hand off, and the code does the handing. That split is the point: the model is good at reading a ticket, and the code makes sure a handoff goes to an agent that exists, with the input it expects, and that billing's answer reaches the client as billing gave it. The client sees one call, `invoke_triage`, and one answer. `this.callTool()` reaches agents on the app, and also the agents in triage's own `agents`: with billing nested in triage, as in the [last section](https://frontmcp.dev/learn/agents-that-call-agents#letting-triages-model-call-billing), `this.callTool("invoke_billing")` finds it too. So does [`this.invokeAgent("billing", input)`](https://frontmcp.dev/reference/sdk/agent#calling-other-agents), which returns billing's answer itself rather than a `CallToolResult`. (Changed in 1.9.2: before, `this.callTool()` didn't reach a nested agent, and answered `Tool "invoke_billing" not found`.) Now that triage hands billing questions off, the client doesn't need `invoke_billing`, so `billing.agent.ts` sets `hideFromDiscovery: true`, which takes it out of `tools/list`. It hides the agent; it doesn't lock it. The last test calls `invoke_billing` by name, and it works, so an agent whose work needs protecting still needs [authorization](https://frontmcp.dev/learn/authorizing-calls) like any tool. ## When the other agent fails When the agent you call fails, `this.callTool()` doesn't return an error result: it throws. Here the model provider behind billing is overloaded, which `model.example.ts` switches on with `provider.overloaded`. Open the **Tests** tab: Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-2" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { triageModel } from "./model.example"; import { GetTicket } from "./tools"; type Answer = { response?: string; handoff?: "billing"; question?: string }; @Agent({ name: "triage", description: "Read a support ticket and answer it, or hand billing questions to the billing agent.", systemInstructions: "Read the ticket with get_ticket, then say who should handle it. If it's about an invoice or a " + 'charge, answer only with {"handoff": "billing", "question": ""}.', inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket], llm: { adapter: triageModel }, }) export class TriageAgent extends AgentContext { async execute(input: { ticketId: string }) { const answer = (await super.execute(input)) as Answer; if (answer.handoff !== "billing") return answer; try { const result = await this.callTool("invoke_billing", { question: answer.question }); return result.structuredContent as Answer; } catch (error) { this.logger.warn(`Billing couldn't answer ${input.ticketId}: ${(error as Error).message}`); return { response: `${input.ticketId} is a billing question, and the billing agent can't answer right now. A person from billing will pick it up.` }; } } } ``` ```ts billing.agent.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { billingModel } from "./model.example"; @Agent({ name: "billing", description: "Answer a customer's question about an invoice or a charge.", inputSchema: { question: z.string().describe("The customer's question, with the invoice number") }, hideFromDiscovery: true, llm: { adapter: billingModel }, }) export class BillingAgent extends AgentContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { BillingAgent } from "./billing.agent"; import { TriageAgent } from "./triage.agent"; @App({ id: "help-desk", name: "Help Desk", agents: [TriageAgent, BillingAgent] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets: Record = { "T-1": "I can't log in since this morning.", "T-2": "I was charged twice for invoice INV-7.", }; @Tool({ name: "get_ticket", description: "Get a support ticket by id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, text: tickets[id] ?? "" }; } } ``` ```ts model.example.ts // Stand-ins for the two agents' models, as in the example above. // `provider.overloaded` makes billing's model fail, as a real provider does when it's busy. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const provider = { overloaded: true }; export const triageModel: AgentLlmAdapter = { async completion(prompt) { const last = prompt.messages.at(-1)!; if (last.role === "user") { const { ticketId } = JSON.parse(last.content!); return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "c1", name: "get_ticket", arguments: { id: ticketId } }] }; } const ticket = JSON.parse(last.content!); if (/invoice|charge/i.test(ticket.text)) { return { content: JSON.stringify({ handoff: "billing", question: ticket.text }), finishReason: "stop" }; } return { content: `${ticket.id} is a login problem: the accounts team should take it.`, finishReason: "stop" }; }, }; export const billingModel: AgentLlmAdapter = { async completion() { if (provider.overloaded) throw new Error("The model provider is overloaded. Try again in 30 seconds."); return { content: "INV-7 was charged twice: refund the second charge of 49 EUR.", finishReason: "stop" }; }, }; ``` ```ts failure.test.ts import { test, expect } from "@frontmcp/testing"; import { provider } from "./model.example"; test("triage answers anyway when billing fails", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ response: "T-2 is a billing question, and the billing agent can't answer right now. A person from billing will pick it up.", }); }); test("billing's answer comes through when billing is up", async ({ mcp }) => { provider.overloaded = false; const result = await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(result.json()).toEqual({ response: "INV-7 was charged twice: refund the second charge of 49 EUR." }); }); ``` The error's message is `Tool "invoke_billing" execution failed: ` followed by billing's own error. Take the `try` out and run the tests: triage's call fails too, and the client gets `Tool "invoke_triage" execution failed: Tool "invoke_billing" execution failed: The model provider is overloaded…`, which tells the client's model nothing it can act on. So catch it. What triage answers instead is up to the help desk; here it says who will pick the ticket up, and logs the real error for whoever runs the server (open the **Logs** tab). ## Handoffs that never stop A handoff can lead to another handoff. The help desk has support tiers, and `escalate` passes a ticket up one tier at a time, calling itself, until a tier's model can solve it. Only tier 4 can solve T-5. FrontMCP limits how many calls from one agent to another a chain may make, with `swarm.maxCallDepth`, 3 by default. Here it's 2: Initial call configuration: ```js { tool: "invoke_escalate", arguments: { ticketId: "T-5", tier: 1 } } ``` ```ts escalate.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { tierModel } from "./model.example"; type Answer = { response?: string; escalate?: boolean }; @Agent({ name: "escalate", description: "Work on a ticket at one support tier, and pass it up a tier if this one can't solve it.", systemInstructions: 'Try to solve the ticket. If you can\'t, answer only with {"escalate": true}.', inputSchema: { ticketId: z.string().describe("Ticket id, like T-5"), tier: z.number().int().min(1).describe("The support tier working on it, from 1"), }, swarm: { maxCallDepth: 2 }, llm: { adapter: tierModel }, }) export class EscalateAgent extends AgentContext { async execute(input: { ticketId: string; tier: number }) { const answer = (await super.execute(input)) as Answer; if (answer.escalate) { const result = await this.callTool("invoke_escalate", { ticketId: input.ticketId, tier: input.tier + 1 }); return result.structuredContent as Answer; } return answer; } } ``` ```ts model.example.ts // A stand-in for the model at each tier: only tier 4 can solve T-5, and every tier // below escalates. `tiers` records which tiers worked on a ticket. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const tiers: number[] = []; export const tierModel: AgentLlmAdapter = { async completion(prompt) { const { ticketId, tier } = JSON.parse(prompt.messages[0].content!); tiers.push(tier); if (tier < 4) return { content: JSON.stringify({ escalate: true }), finishReason: "stop" }; return { content: `Tier ${tier} solved ${ticketId}: the customer's SSO certificate had expired.`, finishReason: "stop" }; }, }; ``` ```ts escalate.test.ts import { test, expect } from "@frontmcp/testing"; import { tiers } from "./model.example"; test("the ticket stops at tier 3, and the call fails", async ({ mcp }) => { const result = await mcp.tools.call("invoke_escalate", { ticketId: "T-5", tier: 1 }); expect(result).toBeError("AGENT_CALL_DEPTH_EXCEEDED"); expect(result.text()).toBe( 'Agent "escalate" can\'t be called from "escalate" -> "escalate" -> "escalate": that would be agent call 3, deeper than maxCallDepth 2', ); expect(tiers).toEqual([1, 2, 3]); }); ``` Tier 1 called tier 2, and tier 2 called tier 3: two calls from one agent to another. Tier 3's call to tier 4 would have been the third, so FrontMCP refused it, with `AGENT_CALL_DEPTH_EXCEEDED`. Tier 3's `this.callTool()` threw, and so did tier 2's and tier 1's, so the client's whole call failed, with the message above. The limit counts every way one agent calls another: a model's call, `this.invokeAgent()`, and `this.callTool("invoke_")`, as here. Changed in 1.9: before, `maxCallDepth` wasn't enforced, and the ticket went up all four tiers. The limit keeps a chain from running forever, whether an agent calls itself or two agents hand a ticket back and forth ("that's billing", "that's not billing"). But it stops the chain by failing the call, after every tier below it has paid for its model call, and the client gets an error instead of an answer. With the default of 3, T-5 would have reached tier 4 and been solved; a ticket no tier can solve would fail the same way at tier 4. So write a limit of your own, that ends the chain with an answer: - **Hand off in one direction.** Triage hands off to billing; billing answers, and never hands back. A helper agent that can't answer says so, and the agent that called it decides what happens next. - **Count the steps when an agent calls itself.** `escalate` knows its tier, so it can stop at a fixed one and hand the ticket to a person. The [second challenge](https://frontmcp.dev/learn/agents-that-call-agents#try-some-challenges) adds that check. The [Research Assistant](https://frontmcp.dev/examples/research-assistant) example is a coordinator that calls a narrower agent, checks what comes back, and refuses an answer that cites something it wasn't given. ## Recap - Agents registered on the same app don't see each other: each agent's model is offered only its own tools. The client sees each agent as `invoke_`, and its model can chain them. - `agents: [...]` on an `@Agent` offers its model those agents as `invoke_` tools, and keeps them from the client. `swarm: { canSeeOtherAgents: true }` offers the app's other agents instead. Either way, the model decides whether to call them. (Before 1.9, both were ignored.) - An agent hands a task to another from `execute()`: `super.execute(input)` runs its own model, and `this.callTool("invoke_", args)` runs the other agent, whose answer is the result's `structuredContent`. Let the model decide whether to hand off, and the code do it. - `hideFromDiscovery: true` takes a helper agent out of `tools/list`; a client can still call it by name. - When the other agent fails, `this.callTool()` throws. Catch it, and answer something the client's model can use. - `swarm.maxCallDepth`, 3 by default, fails a chain of agent calls that goes deeper, by failing the client's whole call. Hand off in one direction, or count the steps, so a chain ends with an answer first. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Hand off to the right specialist The help desk has a second specialist now: `accounts`, for login problems. Triage's model answers with `{"handoff": "billing"}` or `{"handoff": "accounts"}` and the customer's question, but `execute()` only knows about billing. Make triage hand each ticket to the agent its model names. Initial call configuration: ```js { tool: "invoke_triage", arguments: { ticketId: "T-1" } } ``` ```ts triage.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { triageModel } from "./model.example"; import { GetTicket } from "./tools"; type Answer = { response?: string; handoff?: "billing" | "accounts"; question?: string }; @Agent({ name: "triage", description: "Read a support ticket and hand it to the specialist agent who should answer it.", systemInstructions: 'Read the ticket with get_ticket. Answer only with {"handoff": "billing" or "accounts", "question": ""}.', inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket], llm: { adapter: triageModel }, }) export class TriageAgent extends AgentContext { async execute(input: { ticketId: string }) { const answer = (await super.execute(input)) as Answer; if (answer.handoff === "billing") { const result = await this.callTool("invoke_billing", { question: answer.question }); return result.structuredContent as Answer; } return answer; } } ``` **Solution file (alternative to the starter):** ```ts triage.agent.ts solution import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { triageModel } from "./model.example"; import { GetTicket } from "./tools"; type Answer = { response?: string; handoff?: "billing" | "accounts"; question?: string }; const specialists = { billing: "invoke_billing", accounts: "invoke_accounts" }; @Agent({ name: "triage", description: "Read a support ticket and hand it to the specialist agent who should answer it.", systemInstructions: 'Read the ticket with get_ticket. Answer only with {"handoff": "billing" or "accounts", "question": ""}.', inputSchema: { ticketId: z.string().describe("Ticket id, like T-1") }, tools: [GetTicket], llm: { adapter: triageModel }, }) export class TriageAgent extends AgentContext { async execute(input: { ticketId: string }) { const answer = (await super.execute(input)) as Answer; const tool = answer.handoff && specialists[answer.handoff]; if (tool) { const result = await this.callTool(tool, { question: answer.question }); return result.structuredContent as Answer; } return answer; } } ``` ```ts specialists.agent.ts import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { accountsModel, billingModel } from "./model.example"; @Agent({ name: "billing", description: "Answer a customer's question about an invoice or a charge.", inputSchema: { question: z.string() }, llm: { adapter: billingModel }, }) export class BillingAgent extends AgentContext {} @Agent({ name: "accounts", description: "Help a customer who can't log in.", inputSchema: { question: z.string() }, llm: { adapter: accountsModel }, }) export class AccountsAgent extends AgentContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { AccountsAgent, BillingAgent } from "./specialists.agent"; import { TriageAgent } from "./triage.agent"; @App({ id: "help-desk", name: "Help Desk", agents: [TriageAgent, BillingAgent, AccountsAgent] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets: Record = { "T-1": "I can't log in since this morning.", "T-2": "I was charged twice for invoice INV-7.", }; @Tool({ name: "get_ticket", description: "Get a support ticket by id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, text: tickets[id] ?? "" }; } } ``` ```ts model.example.ts // Stand-ins for the three agents' models. Triage hands billing questions to // billing and everything else to accounts; the specialists answer at once. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const triageModel: AgentLlmAdapter = { async completion(prompt) { const last = prompt.messages.at(-1)!; if (last.role === "user") { const { ticketId } = JSON.parse(last.content!); return { content: null, finishReason: "tool_calls", toolCalls: [{ id: "c1", name: "get_ticket", arguments: { id: ticketId } }] }; } const ticket = JSON.parse(last.content!); const handoff = /invoice|charge/i.test(ticket.text) ? "billing" : "accounts"; return { content: JSON.stringify({ handoff, question: ticket.text }), finishReason: "stop" }; }, }; export const billingModel: AgentLlmAdapter = { async completion() { return { content: "INV-7 was charged twice: refund the second charge of 49 EUR.", finishReason: "stop" }; }, }; export const accountsModel: AgentLlmAdapter = { async completion() { return { content: "The account was locked after 5 failed logins. Send a reset link.", finishReason: "stop" }; }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts route.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("a login ticket gets the accounts agent's answer", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-1" }); expect(result.json()).toEqual({ response: "The account was locked after 5 failed logins. Send a reset link." }); }); test("a billing ticket still gets the billing agent's answer", async ({ mcp }) => { const result = await mcp.tools.call("invoke_triage", { ticketId: "T-2" }); expect(result.json()).toEqual({ response: "INV-7 was charged twice: refund the second charge of 49 EUR." }); }); ``` **Hint:** Each specialist is the tool `invoke_` plus its name. Which of the two names comes from the model? **Solution:** The model's `handoff` names the specialist, and a small map turns it into the tool to call. You could build the name with `` `invoke_${answer.handoff}` ``, but the map keeps the model from choosing any tool on the server: a handoff to a name that isn't in it is ignored, and triage returns its model's answer as it is. ### Challenge: Stop escalating at tier 3 `escalate` passes a ticket up the support tiers until one solves it, and only FrontMCP's depth limit stops it, by failing the call. Tier 3 is the last tier with agents; above it are people. Change `execute()` so that when tier 3 can't solve a ticket, the call answers `{ "response": "No tier could solve T-5. An engineer will take it." }` (with the ticket's id) instead of escalating again. Initial call configuration: ```js { tool: "invoke_escalate", arguments: { ticketId: "T-5", tier: 1 } } ``` ```ts escalate.agent.ts active import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { tierModel } from "./model.example"; type Answer = { response?: string; escalate?: boolean }; @Agent({ name: "escalate", description: "Work on a ticket at one support tier, and pass it up a tier if this one can't solve it.", systemInstructions: 'Try to solve the ticket. If you can\'t, answer only with {"escalate": true}.', inputSchema: { ticketId: z.string().describe("Ticket id, like T-5"), tier: z.number().int().min(1).describe("The support tier working on it, from 1"), }, llm: { adapter: tierModel }, }) export class EscalateAgent extends AgentContext { async execute(input: { ticketId: string; tier: number }) { const answer = (await super.execute(input)) as Answer; if (answer.escalate) { const result = await this.callTool("invoke_escalate", { ticketId: input.ticketId, tier: input.tier + 1 }); return result.structuredContent as Answer; } return answer; } } ``` **Solution file (alternative to the starter):** ```ts escalate.agent.ts solution import { Agent, AgentContext, z } from "@frontmcp/sdk"; import { tierModel } from "./model.example"; type Answer = { response?: string; escalate?: boolean }; const LAST_TIER = 3; @Agent({ name: "escalate", description: "Work on a ticket at one support tier, and pass it up a tier if this one can't solve it.", systemInstructions: 'Try to solve the ticket. If you can\'t, answer only with {"escalate": true}.', inputSchema: { ticketId: z.string().describe("Ticket id, like T-5"), tier: z.number().int().min(1).describe("The support tier working on it, from 1"), }, llm: { adapter: tierModel }, }) export class EscalateAgent extends AgentContext { async execute(input: { ticketId: string; tier: number }) { const answer = (await super.execute(input)) as Answer; if (!answer.escalate) return answer; if (input.tier >= LAST_TIER) { return { response: `No tier could solve ${input.ticketId}. An engineer will take it.` }; } const result = await this.callTool("invoke_escalate", { ticketId: input.ticketId, tier: input.tier + 1 }); return result.structuredContent as Answer; } } ``` ```ts model.example.ts // A stand-in for the model at each tier. Tier 2 can solve T-4; no tier can solve // T-5, so it escalates until FrontMCP's depth limit fails the call. `tiers` records which tiers worked. import type { AgentLlmAdapter } from "@frontmcp/sdk"; export const tiers: number[] = []; export const tierModel: AgentLlmAdapter = { async completion(prompt) { const { ticketId, tier } = JSON.parse(prompt.messages[0].content!); tiers.push(tier); if (ticketId === "T-4" && tier === 2) { return { content: "Tier 2 solved T-4: the customer's cache needed clearing.", finishReason: "stop" }; } return { content: JSON.stringify({ escalate: true }), finishReason: "stop" }; }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts escalate.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { tiers } from "./model.example"; test("a ticket no tier can solve stops at tier 3", async ({ mcp }) => { const result = await mcp.tools.call("invoke_escalate", { ticketId: "T-5", tier: 1 }); expect(result.json()).toEqual({ response: "No tier could solve T-5. An engineer will take it." }); expect(tiers).toEqual([1, 2, 3]); }); test("a ticket tier 2 can solve still gets tier 2's answer", async ({ mcp }) => { const result = await mcp.tools.call("invoke_escalate", { ticketId: "T-4", tier: 1 }); expect(result.json()).toEqual({ response: "Tier 2 solved T-4: the customer's cache needed clearing." }); }); ``` **Hint:** `execute()` knows its tier from its input. Check it after the model has answered, and before calling the next tier. **Solution:** Each call knows its tier, so the tier that would escalate past 3 answers instead of calling `invoke_escalate` again. The check comes after the model's answer, so tier 3 still gets its chance to solve the ticket, and before the call, so tier 4 never starts. Without it, T-5 climbs to tier 4, whose call to tier 5 is past the default `maxCallDepth` of 3, so the whole call fails with `AGENT_CALL_DEPTH_EXCEEDED`, after four paid model calls and with no answer for the client. --- # Teaching the Model Skills > Write a FrontMCP skill with @Skill, how clients find and load it via skill:// resources and skills/search, and when to use a skill instead of an agent or prompt. Source: https://frontmcp.dev/learn/teaching-the-model-skills [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Some of what a support agent knows isn't a single action but a procedure: to refund a duplicate charge, read the invoice, refund every charge after the first and never the first, then tell the customer how long it takes. The tools for each step already exist. What the client's model lacks is the order and the rules. A **skill** is that procedure, written down: instructions, the tools they use, and when to use them, served by your FrontMCP server for the client's model to read and follow itself. This lesson writes one, and shows how a client finds and reads it. **You will learn** - How to write a skill with `@Skill`: description, instructions, tools, parameters and examples - What a skill adds to your server, and how a client finds and reads it - How to search for and load skills with FrontMCP's `skills/search` and `skills/load` - Where a skill's instructions can come from: inline, a file or a URL - When to write a skill, an agent or a prompt ## Writing a skill The help desk has the three tools a duplicate-charge refund needs. Here's the procedure that ties them together. Open the **Tests** tab: Initial call configuration: ```js { resource: "skill://refund-duplicate-charge/SKILL.md" } ``` ```ts refund.skill.ts active import { Skill, SkillContext } from "@frontmcp/sdk"; @Skill({ name: "refund-duplicate-charge", description: "Refund a customer who was charged more than once for the same invoice, and tell them on their ticket.", instructions: `1. Read the invoice with get_invoice. Refund only if it has more than one charge. 2. Refund every charge after the first with refund_charge. Never refund the first charge. 3. Reply on the ticket with reply_to_ticket: say how much was refunded, and that it takes 3 to 5 business days.`, tools: [ "get_invoice", { name: "refund_charge", purpose: "Refund one duplicate charge", required: true }, "reply_to_ticket", ], parameters: [ { name: "ticketId", description: "The customer's ticket, like T-2", required: true }, { name: "invoiceId", description: "The invoice that was charged twice, like INV-7", required: true }, ], examples: [ { scenario: "A customer writes on T-2 that INV-7 was charged twice", parameters: { ticketId: "T-2", invoiceId: "INV-7" }, expectedOutcome: "The second charge is refunded, and T-2 says so", }, ], }) export class RefundDuplicateCharge extends SkillContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { RefundDuplicateCharge } from "./refund.skill"; import { GetInvoice, RefundCharge, ReplyToTicket } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetInvoice, RefundCharge, ReplyToTicket], skills: [RefundDuplicateCharge], }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; export const refunded: string[] = []; export const replies: string[] = []; @Tool({ name: "get_invoice", description: "Get an invoice, with its charges.", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, charges: [{ id: "ch_1", amount: "49 EUR" }, { id: "ch_2", amount: "49 EUR" }] }; } } @Tool({ name: "refund_charge", description: "Refund one charge.", inputSchema: { chargeId: z.string() } }) export class RefundCharge extends ToolContext { async execute({ chargeId }: { chargeId: string }) { refunded.push(chargeId); return { refunded: chargeId }; } } @Tool({ name: "reply_to_ticket", description: "Reply to the customer on a ticket.", inputSchema: { ticketId: z.string(), message: z.string() } }) export class ReplyToTicket extends ToolContext { async execute({ ticketId, message }: { ticketId: string; message: string }) { replies.push(`${ticketId}: ${message}`); return { sent: true }; } } ``` ```ts skill.test.ts import { test, expect } from "@frontmcp/testing"; test("a skill adds no tools", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).toEqual(["get_invoice", "refund_charge", "reply_to_ticket"]); }); test("it adds two resources: the skill's SKILL.md, and an index", async ({ mcp }) => { const resources = await mcp.resources.list(); expect(resources.map((r) => r.uri).sort()).toEqual(["skill://index.json", "skill://refund-duplicate-charge/SKILL.md"]); expect(resources.find((r) => r.uri.endsWith("SKILL.md"))).toMatchObject({ mimeType: "text/markdown", annotations: { audience: ["assistant"] }, }); }); test("SKILL.md is the skill's metadata, then its instructions", async ({ mcp }) => { const md = (await mcp.resources.read("skill://refund-duplicate-charge/SKILL.md")).text(); expect(md).toBe(`--- name: refund-duplicate-charge description: Refund a customer who was charged more than once for the same invoice, and tell them on their ticket. tools: - get_invoice - name: refund_charge purpose: Refund one duplicate charge required: true - reply_to_ticket parameters: - name: ticketId description: The customer's ticket, like T-2 required: true type: string - name: invoiceId description: The invoice that was charged twice, like INV-7 required: true type: string examples: - scenario: A customer writes on T-2 that INV-7 was charged twice parameters: ticketId: T-2 invoiceId: INV-7 expectedOutcome: The second charge is refunded, and T-2 says so --- 1. Read the invoice with get_invoice. Refund only if it has more than one charge. 2. Refund every charge after the first with refund_charge. Never refund the first charge. 3. Reply on the ticket with reply_to_ticket: say how much was refunded, and that it takes 3 to 5 business days. `); }); ``` A skill is a class, like a tool, with no code of its own: - **`name`** is its id, in kebab-case: lowercase letters, numbers and hyphens. - **`description`** is what a model reads when it decides whether this skill fits the task, so say when to use it. - **`instructions`** are the procedure. Write them for a model that has never seen your help desk: the steps in order, the tool for each, and the rules it mustn't break. - **`tools`** names the tools the procedure uses. A name is enough; `{ name, purpose, required }` adds why the tool is there and whether the skill works without it. - **`parameters`** and **`examples`** say what the model needs to know before it starts, and show one case from start to end. - **`skills: [...]`** on `@App` registers it. **`SkillContext`** is the base class, and the class body stays empty. The first test is the one to notice: a skill adds no tools. It doesn't *do* anything. FrontMCP serves it as a document, `SKILL.md`: the metadata as YAML, then the instructions. That's the format of the [Agent Skills](https://agentskills.io/specification) standard, so a model that knows skills from elsewhere knows how to read it. > **Note** > > `tools` also takes tool classes, `tools: [GetInvoice]`, or `{ tool: GetInvoice, purpose }`, and FrontMCP lists each by the tool's name. A class can't leave a skill behind when the tool is renamed, the way a name in a string can. The [search and load](https://frontmcp.dev/learn/teaching-the-model-skills#searching-and-loading-skills) example has one. Changed in 1.9: before, a tool class stopped the server from starting. ## How a client finds a skill A skill reaches the client as [resources](https://frontmcp.dev/learn/exposing-data-with-resources), following the proposed MCP skills extension (SEP-2640): `skill://index.json` lists every skill with its description and address, and `skill:///SKILL.md` is each one. A client that supports skills reads the index, picks a skill by its description, reads its `SKILL.md`, and then its model follows the steps with your tools. This test plays that client: *[Illustration: How a client uses a skill. The MCP client reads skill://index.json from your server and gets each skill's name and description. It picks refund-duplicate-charge by its description and reads skill://refund-duplicate-charge/SKILL.md, getting the instructions, which it puts in its model's context. The client's model then calls get_invoice, refund_charge and reply_to_ticket on your server. The server only answered reads and tool calls; it never ran the skill.]* Initial call configuration: ```js { resource: "skill://index.json" } ``` ```ts client.test.ts active import { test, expect } from "@frontmcp/testing"; import { refunded, replies } from "./tools"; test("a client finds the skill, reads it, and follows it", async ({ mcp }) => { // 1. Read the index, and pick the skill whose description fits the task. const index = (await mcp.resources.read("skill://index.json")).json(); const skill = index.skills.find((s: { description?: string }) => s.description?.includes("charged more than once")); expect(skill).toEqual({ type: "skill-md", name: "refund-duplicate-charge", description: "Refund a customer who was charged more than once for the same invoice, and tell them on their ticket.", url: "skill://refund-duplicate-charge/SKILL.md", }); // 2. Read its SKILL.md. const md = (await mcp.resources.read(skill.url)).text(); expect(md).toContain("Never refund the first charge."); // 3. Follow the steps with the server's tools, as the model would. const invoice = (await mcp.tools.call("get_invoice", { id: "INV-7" })).json(); for (const charge of invoice.charges.slice(1)) { await mcp.tools.call("refund_charge", { chargeId: charge.id }); } await mcp.tools.call("reply_to_ticket", { ticketId: "T-2", message: "We refunded the duplicate charge of 49 EUR. It takes 3 to 5 business days." }); expect(refunded).toEqual(["ch_2"]); expect(replies).toHaveLength(1); }); test("the server says it has skills, and its instructions point to the index", async ({ mcp }) => { const { result } = (await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "server/discover" })) as any; expect(result.capabilities.extensions).toEqual({ "io.modelcontextprotocol/tasks": {}, "io.modelcontextprotocol/skills": {}, }); expect(result.instructions).toBe( "Help desk tools.\n\n---\n\nThis server has 1 skill: the `skill://index.json` resource lists each skill's `SKILL.md` URI.", ); }); ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { RefundDuplicateCharge } from "./refund.skill"; import { GetInvoice, RefundCharge, ReplyToTicket } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetInvoice, RefundCharge, ReplyToTicket], skills: [RefundDuplicateCharge], }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, instructions: "Help desk tools.", apps: [HelpDeskApp], }) export default class Server {} ``` ```ts refund.skill.ts import { Skill, SkillContext } from "@frontmcp/sdk"; @Skill({ name: "refund-duplicate-charge", description: "Refund a customer who was charged more than once for the same invoice, and tell them on their ticket.", instructions: `1. Read the invoice with get_invoice. Refund only if it has more than one charge. 2. Refund every charge after the first with refund_charge. Never refund the first charge. 3. Reply on the ticket with reply_to_ticket: say how much was refunded, and that it takes 3 to 5 business days.`, tools: ["get_invoice", { name: "refund_charge", purpose: "Refund one duplicate charge", required: true }, "reply_to_ticket"], }) export class RefundDuplicateCharge extends SkillContext {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; export const refunded: string[] = []; export const replies: string[] = []; @Tool({ name: "get_invoice", description: "Get an invoice, with its charges.", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, charges: [{ id: "ch_1", amount: "49 EUR" }, { id: "ch_2", amount: "49 EUR" }] }; } } @Tool({ name: "refund_charge", description: "Refund one charge.", inputSchema: { chargeId: z.string() } }) export class RefundCharge extends ToolContext { async execute({ chargeId }: { chargeId: string }) { refunded.push(chargeId); return { refunded: chargeId }; } } @Tool({ name: "reply_to_ticket", description: "Reply to the customer on a ticket.", inputSchema: { ticketId: z.string(), message: z.string() } }) export class ReplyToTicket extends ToolContext { async execute({ ticketId, message }: { ticketId: string; message: string }) { replies.push(`${ticketId}: ${message}`); return { sent: true }; } } ``` The skill never runs. The client's model reads it and does the work, with your tools and its own tokens, and FrontMCP checks each tool call as it would any other: the skill's rules are advice to the model, not limits on the tools. "Never refund the first charge" is only as strong as the model that reads it, so a rule that must hold belongs in `refund_charge` itself. The second test is how a client learns the server has skills. `server/discover` lists the extension `io.modelcontextprotocol/skills`, and a client that knows it looks for `skill://index.json`. A client that doesn't know it still sees the `SKILL.md` resources in `resources/list`, marked for the assistant. FrontMCP adds one line to the server's `instructions`, after your own, with the number of skills the caller can see and a pointer to the index. Changed in 1.10.16: before, the default instructions listed every skill's name and description. Set [`skillsConfig.injectInstructions: "append"`](https://frontmcp.dev/reference/sdk/skill#server-options-skillsconfig) to include that catalog again. ## Searching and loading skills FrontMCP also answers requests of its own for skills: `skills/search` finds skills by the words in a task, and `skills/load` returns skills ready to use. They're JSON-RPC methods, not tools, so they're for clients written to use them, like your own. They aren't in `tools/list`. Here a second skill names a tool the server doesn't have: ```ts search.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { byClassConfig, strictConfig } from "./other-servers"; test("skills/search finds skills by the words in a task", async ({ mcp }) => { const { result } = (await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "skills/search", params: { query: "customer was charged twice" }, })) as any; expect(result.skills).toEqual([ expect.objectContaining({ name: "refund-duplicate-charge", score: expect.any(Number), source: "local" }), ]); expect(result.guidance).toBe("Found 1 matching skill(s). Use skills/load with skill IDs to load full content."); }); test("skills/load returns instructions, and which tools are missing", async ({ mcp }) => { const { result } = (await mcp.raw.request({ jsonrpc: "2.0", id: 2, method: "skills/load", params: { skillIds: ["refund-duplicate-charge", "escalate-outage"] }, })) as any; const [refund, outage] = result.skills; expect(refund).toMatchObject({ isComplete: true, missingTools: [] }); expect(refund.instructions).toContain("Never refund the first charge."); expect(outage).toMatchObject({ isComplete: false, availableTools: ["get_invoice"], missingTools: ["page_on_call"], }); expect(outage.tools).toEqual([ { name: "get_invoice", available: true, inputSchema: expect.objectContaining({ type: "object" }) }, { name: "page_on_call", purpose: "Wake the on-call engineer", available: false }, ]); expect(outage.formattedContent).toMatch(/^# Skill: escalate-outage\n/); expect(result.summary.combinedWarnings).toEqual([ 'Skill "escalate-outage" references missing tools: page_on_call. Some functionality may be limited.', ]); }); test('`toolValidation: "strict"` stops a server that lacks a tool', async () => { await expect(FrontMcpInstance.createDirect(strictConfig)).rejects.toThrow( "Skill 'escalate-outage' failed tool validation: missing tools [page_on_call]", ); }); test("a tool class in `tools` works like its name", async () => { const server = await FrontMcpInstance.createDirect(byClassConfig); try { const { contents } = await server.readResource("skill://check-invoice/SKILL.md"); expect(contents[0].text).toContain("tools:\n - get_invoice\n - name: refund_charge\n purpose: Refund one duplicate charge\n"); } finally { await server.dispose(); } }); ``` ```ts skills.ts import { Skill, SkillContext } from "@frontmcp/sdk"; @Skill({ name: "refund-duplicate-charge", description: "Refund a customer who was charged more than once for the same invoice, and tell them on their ticket.", instructions: `1. Read the invoice with get_invoice. Refund only if it has more than one charge. 2. Refund every charge after the first with refund_charge. Never refund the first charge. 3. Reply on the ticket with reply_to_ticket: say how much was refunded, and that it takes 3 to 5 business days.`, tools: ["get_invoice", { name: "refund_charge", purpose: "Refund one duplicate charge", required: true }], }) export class RefundDuplicateCharge extends SkillContext {} @Skill({ name: "escalate-outage", description: "Escalate a ticket that reports an outage to the on-call engineer.", instructions: "1. Check the customer's invoices with get_invoice to see their plan.\n2. Page the on-call engineer with page_on_call.", tools: ["get_invoice", { name: "page_on_call", purpose: "Wake the on-call engineer", required: true }], }) export class EscalateOutage extends SkillContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { EscalateOutage, RefundDuplicateCharge } from "./skills"; import { GetInvoice, RefundCharge } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetInvoice, RefundCharge], skills: [RefundDuplicateCharge, EscalateOutage], }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts other-servers.ts import { App, Skill, SkillContext } from "@frontmcp/sdk"; import { GetInvoice, RefundCharge } from "./tools"; @Skill({ name: "escalate-outage", description: "Escalate a ticket that reports an outage to the on-call engineer.", instructions: "1. Check the customer's invoices with get_invoice to see their plan.\n2. Page the on-call engineer with page_on_call.", tools: ["get_invoice", "page_on_call"], toolValidation: "strict", }) class StrictEscalateOutage extends SkillContext {} @App({ id: "strict", name: "Strict", tools: [GetInvoice], skills: [StrictEscalateOutage] }) class StrictApp {} export const strictConfig = { info: { name: "strict", version: "1.0.0" }, apps: [StrictApp] }; @Skill({ name: "check-invoice", description: "Check an invoice for duplicate charges, and refund them.", instructions: "Read the invoice with get_invoice. Refund every charge after the first with refund_charge.", tools: [GetInvoice, { tool: RefundCharge, purpose: "Refund one duplicate charge" }], }) class CheckInvoice extends SkillContext {} @App({ id: "by-class", name: "By class", tools: [GetInvoice, RefundCharge], skills: [CheckInvoice] }) class ByClassApp {} export const byClassConfig = { info: { name: "by-class", version: "1.0.0" }, apps: [ByClassApp] }; ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_invoice", description: "Get an invoice, with its charges.", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, charges: [{ id: "ch_1", amount: "49 EUR" }, { id: "ch_2", amount: "49 EUR" }] }; } } @Tool({ name: "refund_charge", description: "Refund one charge.", inputSchema: { chargeId: z.string() } }) export class RefundCharge extends ToolContext { async execute({ chargeId }: { chargeId: string }) { return { refunded: chargeId }; } } ``` `skills/load` answers with more than `SKILL.md`: each tool the skill names, with `available` and, if it's there, its input schema; `availableTools` and `missingTools`; `isComplete`, false when a named tool is missing; and `formattedContent`, all of it as one markdown document a client can hand its model. A skill that names a missing tool is still served and still loads, and the server starts anyway, so check `missingTools` in your tests, as the [first challenge](https://frontmcp.dev/learn/teaching-the-model-skills#try-some-challenges) does. Or set `toolValidation: "strict"` on the skill: then a missing tool stops the server from starting, as the third test shows. (Changed in 1.9: before, `"strict"` didn't stop it.) The last test names the tools by class. ## Where instructions come from Instructions can be written inline, as so far, or kept in a markdown file next to the code: `{ file: "./refund.md" }`, relative to the file that declares the skill. Long procedures are easier to write and review as markdown. The Playground has no files, so here's what it looks like on a real server: ```ts refund.skill.ts @Skill({ name: "refund-duplicate-charge", description: "Refund a customer who was charged more than once for the same invoice, and tell them on their ticket.", instructions: { file: "./refund-duplicate-charge.md" }, tools: ["get_invoice", "refund_charge", "reply_to_ticket"], }) export class RefundDuplicateCharge extends SkillContext {} ``` The third source is a URL, for procedures that live somewhere else, like the support team's handbook. `docs.example.ts` stands in for that site, as `billing.example.ts` does for billing in [Calling Other Services](https://frontmcp.dev/learn/calling-other-services): Initial call configuration: ```js { resource: "skill://refund-duplicate-charge/SKILL.md" } ``` ```ts refund.skill.ts active import { Skill, SkillContext } from "@frontmcp/sdk"; @Skill({ name: "refund-duplicate-charge", description: "Refund a customer who was charged more than once for the same invoice, and tell them on their ticket.", instructions: { url: "https://handbook.help-desk.example/refunds/duplicate-charge.md" }, tools: ["get_invoice", "refund_charge", "reply_to_ticket"], }) export class RefundDuplicateCharge extends SkillContext {} ``` ```ts docs.example.ts // Stands in for the support handbook at https://handbook.help-desk.example, which the // Playground can't reach. It answers requests for that host in-process, records them, // and passes everything else to the real fetch. A real server doesn't need this file. /** Every handbook page that was fetched, oldest first. */ export const fetched: string[] = []; const pages: Record = { "/refunds/duplicate-charge.md": "1. Read the invoice with get_invoice.\n2. Refund every charge after the first with refund_charge.\n3. Tell the customer with reply_to_ticket.\n", }; const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = async (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input)); if (url.host !== "handbook.help-desk.example") return realFetch(input, init); fetched.push(url.pathname); const page = pages[url.pathname]; return page ? new Response(page, { headers: { "content-type": "text/markdown" } }) : new Response("Not found", { status: 404 }); }; ``` ```ts main.ts import "./docs.example"; import { App, FrontMcp } from "@frontmcp/sdk"; import { RefundDuplicateCharge } from "./refund.skill"; @App({ id: "help-desk", name: "Help Desk", skills: [RefundDuplicateCharge] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts url.test.ts import { test, expect } from "@frontmcp/testing"; import { fetched } from "./docs.example"; test("the page is fetched when the server starts, and then kept", async ({ mcp }) => { expect(fetched).toEqual(["/refunds/duplicate-charge.md"]); const md = (await mcp.resources.read("skill://refund-duplicate-charge/SKILL.md")).text(); expect(md).toContain("2. Refund every charge after the first with refund_charge."); await mcp.resources.read("skill://refund-duplicate-charge/SKILL.md"); await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "skills/load", params: { skillIds: ["refund-duplicate-charge"] } }); expect(fetched).toEqual(["/refunds/duplicate-charge.md"]); }); ``` FrontMCP fetches the page when the server starts, and then keeps it: three reads, one fetch. If the handbook is down then, the server still starts: it logs `Failed to load skill refund-duplicate-charge: …` and tries again the next time it needs the page. A page that changes later isn't picked up until the server restarts. A file is also read at startup; a missing one is logged then, and reading the skill fails with `ENOENT: no such file or directory`. ## Skill, agent or prompt? A skill, an [agent](https://frontmcp.dev/learn/your-first-agent) and a [prompt](https://frontmcp.dev/learn/reusable-prompts) all hand a model some instructions. What differs is whose model follows them, and who picks them: | | Skill | Agent | Prompt | | --- | --- | --- | --- | | The client sees | Resources, `skill://…/SKILL.md` | A tool, `invoke_` | An entry in `prompts/list` | | Who picks it | The client's model, from its description | The client's model, like any tool | The user, from a menu | | Who does the work | The client's model, with your tools | Your server's model, with the agent's own tools | The client's model | | Who pays for the model | The client | You | The client | | Use it when | The client's model can do the job if it knows the steps | The job needs its own model, tools the client shouldn't have, or should run the same way for every client | The user starts a task and fills in a form | The same procedure can be served both ways: the refund steps as a skill for clients whose model should do the work, and as an agent's `systemInstructions` for clients that would rather hand it off. Put the text in one constant, and give it to both. ## Recap - `@Skill({ name, description, instructions, tools, parameters, examples })` writes a procedure down, and `@App({ skills })` registers it. A skill adds no tools and runs no code: the client's model reads it and does the work. - FrontMCP serves each skill as `skill:///SKILL.md`, its metadata as YAML and then its instructions, and lists them all in `skill://index.json`. `server/discover` lists the extension `io.modelcontextprotocol/skills`, and FrontMCP adds a count and a pointer to the index to the server's `instructions`. - `skills/search` and `skills/load` are FrontMCP's own JSON-RPC requests, not tools. `skills/load` says which of a skill's tools are missing; a skill with missing tools still loads. - Name a skill's tools as strings, as `{ name, purpose, required }`, or by class (since 1.9). `toolValidation: "strict"` stops the server from starting when one is missing. - Instructions can be inline, `{ file }` or `{ url }`. Files and URLs are read when the server starts (a failure is logged, not fatal), and a URL is fetched once. - Write a skill when the client's model can do the job once it knows the steps, an agent when your server's model should do it, and a prompt when the user starts it. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Point the skill at the right tools `close-solved-ticket` loads, but `skills/load` says it's incomplete: one of the tools it names doesn't exist on the server. Find it, and fix the skill so every tool it names is available. Initial call configuration: ```js { resource: "skill://close-solved-ticket/SKILL.md" } ``` ```ts close.skill.ts active import { Skill, SkillContext } from "@frontmcp/sdk"; @Skill({ name: "close-solved-ticket", description: "Close a ticket the customer confirmed is solved, and thank them.", instructions: "1. Read the ticket with get_ticket and check the customer said it's solved.\n2. Thank them with reply_to_ticket.\n3. Close it with close_ticket.", tools: ["get_ticket", "reply_to_ticket", "close_tickets"], }) export class CloseSolvedTicket extends SkillContext {} ``` **Solution file (alternative to the starter):** ```ts close.skill.ts solution import { Skill, SkillContext } from "@frontmcp/sdk"; @Skill({ name: "close-solved-ticket", description: "Close a ticket the customer confirmed is solved, and thank them.", instructions: "1. Read the ticket with get_ticket and check the customer said it's solved.\n2. Thank them with reply_to_ticket.\n3. Close it with close_ticket.", tools: ["get_ticket", "reply_to_ticket", "close_ticket"], }) export class CloseSolvedTicket extends SkillContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { CloseSolvedTicket } from "./close.skill"; import { CloseTicket, GetTicket, ReplyToTicket } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, ReplyToTicket, CloseTicket], skills: [CloseSolvedTicket], }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get a ticket.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, text: "Thanks, it works again!" }; } } @Tool({ name: "reply_to_ticket", description: "Reply to the customer on a ticket.", inputSchema: { ticketId: z.string(), message: z.string() } }) export class ReplyToTicket extends ToolContext { async execute() { return { sent: true }; } } @Tool({ name: "close_ticket", description: "Close a ticket.", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts tools.test.ts hidden import { test, expect } from "@frontmcp/testing"; const load = async (mcp: any) => (await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "skills/load", params: { skillIds: ["close-solved-ticket"] } })).result.skills[0]; test("the skill is complete: no tool is missing", async ({ mcp }) => { expect(await load(mcp)).toMatchObject({ isComplete: true, missingTools: [] }); }); test("it names get_ticket, reply_to_ticket and close_ticket", async ({ mcp }) => { expect((await load(mcp)).availableTools).toEqual(["get_ticket", "reply_to_ticket", "close_ticket"]); }); ``` **Hint:** Compare the names in the skill's `tools` with the `name` of each tool in `tools.ts`. `skills/load` would name the missing one in `missingTools`. **Solution:** The skill named `close_tickets`, and the tool is `close_ticket`. FrontMCP serves the skill anyway, so a typo like this reaches clients unless something checks `missingTools`, or the skill sets `toolValidation: "strict"`. A test like the hidden one catches it the moment a tool is renamed. ### Challenge: Say what the skill needs A model that loads `close-solved-ticket` has to guess which ticket to close. Add a required parameter `ticketId`, described as `The ticket to close, like T-2`, and an example: the scenario `The customer on T-2 writes that it works again`, with `ticketId` `T-2`, and the expected outcome `T-2 is thanked and closed`. Initial call configuration: ```js { resource: "skill://close-solved-ticket/SKILL.md" } ``` ```ts close.skill.ts active import { Skill, SkillContext } from "@frontmcp/sdk"; @Skill({ name: "close-solved-ticket", description: "Close a ticket the customer confirmed is solved, and thank them.", instructions: "1. Read the ticket with get_ticket and check the customer said it's solved.\n2. Thank them with reply_to_ticket.\n3. Close it with close_ticket.", tools: ["get_ticket", "reply_to_ticket", "close_ticket"], }) export class CloseSolvedTicket extends SkillContext {} ``` **Solution file (alternative to the starter):** ```ts close.skill.ts solution import { Skill, SkillContext } from "@frontmcp/sdk"; @Skill({ name: "close-solved-ticket", description: "Close a ticket the customer confirmed is solved, and thank them.", instructions: "1. Read the ticket with get_ticket and check the customer said it's solved.\n2. Thank them with reply_to_ticket.\n3. Close it with close_ticket.", tools: ["get_ticket", "reply_to_ticket", "close_ticket"], parameters: [{ name: "ticketId", description: "The ticket to close, like T-2", required: true }], examples: [ { scenario: "The customer on T-2 writes that it works again", parameters: { ticketId: "T-2" }, expectedOutcome: "T-2 is thanked and closed", }, ], }) export class CloseSolvedTicket extends SkillContext {} ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { CloseSolvedTicket } from "./close.skill"; @App({ id: "help-desk", name: "Help Desk", skills: [CloseSolvedTicket] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts params.test.ts hidden import { test, expect } from "@frontmcp/testing"; const read = async (mcp: any) => (await mcp.resources.read("skill://close-solved-ticket/SKILL.md")).text(); test("SKILL.md lists `ticketId` as a required parameter", async ({ mcp }) => { expect(await read(mcp)).toContain(`parameters: - name: ticketId description: The ticket to close, like T-2 required: true type: string`); }); test("SKILL.md has the example", async ({ mcp }) => { expect(await read(mcp)).toContain(`examples: - scenario: The customer on T-2 writes that it works again parameters: ticketId: T-2 expectedOutcome: T-2 is thanked and closed`); }); ``` **Hint:** Both are arrays on `@Skill`. A parameter is `{ name, description, required }`; an example is `{ scenario, parameters, expectedOutcome }`. **Solution:** `parameters` and `examples` go into the front matter of `SKILL.md`, which is what a client's model reads before it starts. A parameter's `type` defaults to `string`, which is why the check expects `type: string` though the solution doesn't set it. The example's `parameters` are the values for that case, so a model sees what a real `ticketId` looks like. --- # Tools with a UI > How a FrontMCP tool gives its result a widget, an HTML page a host shows next to the answer. Writing one with a template, choosing how it's served, and building it in React, with what works today. Source: https://frontmcp.dev/learn/tools-with-a-ui [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every tool so far answers the model, and the model tells the person what it found. Some results are for the person more than the model: a ticket they want to see at a glance, a queue they want to sort, a button they'd rather press than type "close it". A FrontMCP tool's `ui` option gives its result a **widget**, an HTML page that a host able to show one renders next to the answer, while the model reads the same result as before. The widget can call your tools through the host, follow its theme and fit its frame. This chapter builds widgets for the help desk, and points out what a widget can't do there yet. **In this chapter** - [How to give a tool a widget, and make it call a tool back](https://frontmcp.dev/learn/your-first-widget) - [How a widget reaches the host, what it may load, and what data it carries](https://frontmcp.dev/learn/choosing-how-a-widget-is-served) - [How to build a widget as a React component](https://frontmcp.dev/learn/building-widgets-with-react) ## Your first widget `ui.template` is a function FrontMCP calls after every call, with the call's input and output. What it returns, built with `ctx.helpers.html` so every value is escaped, becomes the page. The result's `content` and `structuredContent` don't change, and the page travels next to them, in `_meta["ui/html"]`. The Playground's **Widget** tab shows the page as an MCP Apps host would. Press **Close ticket**: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; import { tickets, type Ticket } from "./tickets"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id, with its status and customer.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { template: (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

${ctx.output.id} · ${ctx.output.customer}

${ctx.output.title}

Status: ${ctx.output.status}

`, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); if (ticket.status === "closed") this.fail(new PublicMcpError(`${id} is already closed.`)); ticket.status = "closed"; return { id, status: ticket.status }; } } ``` ```ts tickets.ts export type Ticket = { id: string; title: string; status: "open" | "closed"; customer: string }; export const tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open", customer: "Acme Corp" }, { id: "T-2", title: "Invoice total is wrong", status: "closed", customer: "Globex" }, ]; ``` ```ts widget.test.ts import { test, expect } from "@frontmcp/testing"; test("the model's result is unchanged", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result.json()).toEqual({ id: "T-1", title: "Cannot log in", status: "open", customer: "Acme Corp" }); }); test("the page travels next to it", async ({ mcp }) => { const html: string = (await mcp.tools.call("get_ticket", { id: "T-1" })).raw._meta["ui/html"]; expect(html).toContain("

Cannot log in

"); }); ``` The button's click goes from the page's bridge script to the host, and from the host to your server as an ordinary `tools/call`: the **Wire** tab has it, tagged **widget**. ### [Your First Widget](https://frontmcp.dev/learn/your-first-widget) Learn when a result deserves a widget, how to write a template and why to escape with `html`, what a host receives, how a widget calls tools, and how to follow the host's theme, fit the frame and open links. ## Choosing how a widget is served The default `auto` mode sends a page rendered with the call's data, about 38 KB, except to OpenAI clients, which use the widget resource. Explicit `inline` sends the page there too. A **static** widget is rendered once, when the server starts, and served as the resource `ui://widget/.html`. The host reads it once, then hands the page each result, which the page draws itself: Initial call configuration: ```js { tool: "list_queue", arguments: {} } ``` ```ts list-queue.tool.ts active import { Tool, ToolContext, type TemplateContext } from "@frontmcp/sdk"; type Queue = { tickets: { id: string; title: string }[] }; @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, ui: { servingMode: "static", // Runs once, at startup, with ctx.output = {}. template: (ctx: TemplateContext<{}, Partial>) => ctx.helpers.html`

Open tickets

    `, }, }) export class ListQueue extends ToolContext { async execute(): Promise { return { tickets: [{ id: "T-1", title: "Cannot log in" }, { id: "T-3", title: "Login link expired" }] }; } } ``` ```ts static.test.ts import { test, expect } from "@frontmcp/testing"; test("results carry no page", async ({ mcp }) => { const result = await mcp.tools.call("list_queue", {}); expect(Object.keys(result.raw._meta).filter((k) => k.startsWith("ui/"))).toEqual([]); }); test("the resource is the page", async ({ mcp }) => { expect((await mcp.resources.read("ui://widget/list_queue.html")).text()).toContain('
      '); }); ``` Those are the two real choices: `"hybrid"` is static with a small extra object for a few platforms, and the URL modes are served inline, and the server warns about both at startup. A server that serves every widget one way says so once, with `@FrontMcp({ ui: { servingMode: "static" } })` or `@App({ ui: { servingMode } })`, and a tool's own `servingMode` still wins. Two more things matter wherever the page comes from. The page's own Content Security Policy lets it reach a few CDNs and the origins the tool lists in `ui.csp`, so list the ones the widget calls. And with an `outputSchema`, the widget gets only the fields it declares, as the model does: declare every field the widget shows. ### [Choosing How a Widget Is Served](https://frontmcp.dev/learn/choosing-how-a-widget-is-served) Learn what inline and static widgets cost, how a static widget reads each result and why it reads `structuredContent`, how to set one mode for every tool, what every serving mode does, what the widget's Content Security Policy allows, and why the widget's data has to be declared in `outputSchema`. ## Building widgets with React A widget with state, like a queue with filters and a Close button on each row, is easier as a React component than as a script in a string. Point `ui.template` at a `.tsx` file and FrontMCP bundles it, and mounts the default export with the call's data. Hooks from `@frontmcp/ui/react` read the result and call tools through the host: ```ts list-queue.tool.ts ui: { template: { file: join(__dirname, "queue.widget.tsx") } }, ``` ```tsx queue.widget.tsx type Ticket = { id: string; title: string; priority: "high" | "normal" | "low" }; type Queue = { tickets: Ticket[] }; export default function QueueWidget({ output }: { output: Queue | null }) { if (!output?.tickets) return

      Loading the queue…

      ; return (
        {output.tickets.map((t) => (
      • {t.id} {t.title} ({t.priority})
      • ))}
      ); } ``` The Playground can't run this: FrontMCP bundles widget files from the file system, on a Node server, and the Playground runs FrontMCP in your browser. The lesson's widgets were run in Node projects with FrontMCP 1.9.4, CommonJS and ES module, and rendered in Chromium, and its Playgrounds cover what runs here: the tools, and the calls a widget makes. ### [Building Widgets with React](https://frontmcp.dev/learn/building-widgets-with-react) Learn what a project needs to bundle a widget file, what the component gets as props and why to check for the fields it needs, how to call tools with `useCallTool()` and handle each outcome, and how to handle the theme, the size and where React is loaded from. ## Template or React? | If the widget… | Write | | --- | --- | | Shows a result, maybe with a button or two that call tools | A template function, served inline | | Is large, or shows many results with one page | A template function, served static, that draws each result | | Has state: filters, per-row actions, loading and error states | A React component in a `.tsx` file, on a Node server | Whatever you choose, the result is still what the model reads, and many hosts show no widget at all. Make the tool useful without its page first. ## What's next? Start the chapter with [Your First Widget](https://frontmcp.dev/learn/your-first-widget). Every `ui` option is in the [Tool UI reference](https://frontmcp.dev/reference/ui), what each host and platform gets is on [Hosts and platforms](https://frontmcp.dev/reference/ui/hosts), and the React hooks and components are in [Widget components](https://frontmcp.dev/reference/ui/components). After this chapter, [Built-in Plugins and Adapters](https://frontmcp.dev/learn/built-in-plugins-and-adapters) covers the plugins that come with FrontMCP: caching, memory, approval, feature flags, CodeCall and OpenAPI. --- # Your First Widget > Give a FrontMCP tool's result a UI with the ui option: an HTML template rendered on every call, what the host receives, calling tools back, and theme and size. Source: https://frontmcp.dev/learn/your-first-widget [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A support agent asks about ticket T-1. The model calls `get_ticket`, reads the JSON and writes a sentence about it. That works for the model, but the person asking would rather see the ticket, with a button to close it, than read a paraphrase and type "close it" back. With FrontMCP, a tool's `ui` option gives its result a **widget**: an HTML page that a host able to show one renders next to the answer, while the model reads the same result as before. This lesson gives `get_ticket` a widget, looks at what the host receives, and makes the widget call a tool, follow the host's theme and fit its frame. **You will learn** - When a tool's result is worth a widget - How to add one with the `ui` option and an HTML template - What a host receives, and what the model still sees - How a widget calls a tool on your server - How to follow the host's theme and fit the widget's frame ## When a result deserves a UI Most tools don't need a widget. The model reads a result and tells the user what matters, and for "how many tickets are open?" that's all anyone wants. A widget earns its place when a person, not the model, is the one reading: | A widget helps with | Leave it out for | | --- | --- | | A record someone checks at a glance: a ticket, an invoice, a customer | Answers of a line or two | | A list to scan or sort, like a queue of tickets | Data only the model uses to decide what to call next | | An action the person should confirm with a click, like closing a ticket | Anything the model has to see: it never sees the page | Two things stay true for every tool with a widget. The model gets the same `content` and `structuredContent` it got without one, so the result still has to make sense as text. And many hosts can't show widgets at all: they ignore the page and use the result as it is. ## Adding a widget with `ui` Here is `get_ticket` with a `ui` option. The Playground below opens on its **Widget** tab, which works like a small host: it puts the page into a sandboxed frame, gives it the call's input and result, and passes the page's tool calls to the server. Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; status: "open" | "closed"; priority: "high" | "normal"; customer: string }; const tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open", priority: "high", customer: "Acme Corp" }, { id: "T-2", title: "Invoice total is wrong", status: "closed", priority: "normal", customer: "Globex" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id, with its status, priority and customer.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { template: (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

      ${ctx.output.id} · ${ctx.output.customer} · ${ctx.output.priority} priority

      ${ctx.output.title}

      Status: ${ctx.output.status}

      `, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` ```ts widget.test.ts import { test, expect } from "@frontmcp/testing"; test("the model's result is the same as without ui", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result.json()).toEqual({ id: "T-1", title: "Cannot log in", status: "open", priority: "high", customer: "Acme Corp" }); }); test("tools/list says the tool has a widget", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool._meta).toEqual({ ui: { resourceUri: "ui://widget/get_ticket.html" }, "frontmcp/type": "html" }); }); test("the result carries the page", async ({ mcp }) => { const { _meta } = (await mcp.tools.call("get_ticket", { id: "T-1" })).raw; expect(_meta["ui/type"]).toBe("html"); expect(_meta["ui/mimeType"]).toBe("text/html;profile=mcp-app"); expect(_meta["ui/html"]).toMatch(/^/); expect(_meta["ui/html"]).toContain("

      Cannot log in

      "); }); ``` `template` is a function that FrontMCP calls on every call, after `execute()`, with `ctx`: - **`ctx.output`** is what `execute()` returned, and **`ctx.input`** is the call's arguments. - **`ctx.helpers.html`** builds the markup. Every value you put in `${…}` is escaped, so a ticket title can't add tags to the page (more on this [below](https://frontmcp.dev/learn/your-first-widget#escaping-what-customers-wrote)). - **What it returns** becomes the page's ``. FrontMCP wraps it in a whole HTML document. Annotate `ctx` with `TemplateContext`. `template` accepts several kinds of value, so TypeScript can't infer the parameter's type, and under `strict` a bare `(ctx) => …` fails with `TS7006: Parameter 'ctx' implicitly has an 'any' type`. > **Pitfall: A React component isn't a template function** > > `template: TicketCard`, where `TicketCard` returns JSX, sends an empty page, and the server logs `ui.template is a React component reference, which cannot be bundled` when it starts: FrontMCP has no file to bundle, so the widget shows "Loading widget..." forever. A template function returns markup, as above. React widgets go in a `.tsx` file, and are a lesson of their own, [Building Widgets with React](https://frontmcp.dev/learn/building-widgets-with-react). ### What the host receives Open the **Tests** tab, or the **Wire** tab, to see what a client gets: - **In `tools/list`**, before any call, the tool carries `_meta.ui.resourceUri`, `ui://widget/get_ticket.html`. That's how a host knows the tool has a widget. - **In the `tools/call` result**, `content` and `structuredContent` are what they'd be without `ui`, `outputSchema` included (the [next lesson](https://frontmcp.dev/learn/choosing-how-a-widget-is-served#the-widget-gets-what-outputschema-declares) shows what that means for the page). That's the model's part. - **Next to them, in `_meta`**, is the page: `ui/html` holds a whole HTML document, `ui/type` is `"html"` and `ui/mimeType` is `"text/html;profile=mcp-app"`. The page is about 38 KB even for a card this small. Most of it is **the bridge**, a script FrontMCP puts in every page so the widget can talk to the host it runs in. The page also carries the call's data: a script at the top sets `window.__mcpToolOutput` to what `execute()` returned. ## Escaping what customers wrote Ticket titles are typed by customers, so they're text, not markup. Customers paste error messages, and error messages have angle brackets. A template has to keep the two apart: its own tags are markup, and the values it puts between them are text. Here are two templates for the same title. Only the second one shows a heading: ```ts // 🚩 A plain template string: FrontMCP can't tell your tags from the title, and escapes it all template: (ctx: TemplateContext<{ id: string }, Ticket>) => `

      ${ctx.output.title}

      `, // The page shows the text "

      Export fails with

      ", tags and all. // ✅ html keeps your markup and escapes every value you interpolate template: (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

      ${ctx.output.title}

      `, //

      Export fails with <no data>

      : a heading with the title as the customer wrote it. ``` For the plain string, the server also logs a notice, `The UI template of tool "get_ticket" returned a plain string containing markup. Since 1.9.2, FrontMCP HTML-escapes plain string results by default, so it is shown as text.` Escaping the whole string is the safe choice: if FrontMCP rendered it as markup, a title like `

      `, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); if (ticket.status === "closed") this.fail(new PublicMcpError(`${id} is already closed.`)); ticket.status = "closed"; return { id, status: ticket.status }; } } ``` ```ts tickets.ts export type Ticket = { id: string; title: string; status: "open" | "closed"; priority: "high" | "normal"; customer: string }; export const tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open", priority: "high", customer: "Acme Corp" }, { id: "T-2", title: "Invoice total is wrong", status: "closed", priority: "normal", customer: "Globex" }, ]; ``` ```ts close.test.ts import { test, expect } from "@frontmcp/testing"; test("the button carries the ticket's id", async ({ mcp }) => { const html: string = (await mcp.tools.call("get_ticket", { id: "T-1" })).raw._meta["ui/html"]; expect(html).toContain(``, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); if (ticket.status === "closed") this.fail(new PublicMcpError(`${id} is already closed.`)); ticket.status = "closed"; return { id, status: ticket.status }; } } ``` ```ts tickets.ts export type Ticket = { id: string; title: string; status: "open" | "closed" }; export const tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; ``` **Hidden fixture/test file (runs with the example):** ```ts button.test.ts hidden import { test, expect } from "@frontmcp/testing"; // The arguments of the page's close_ticket button, as the bridge reads them. async function closeButtonArgs(mcp: any, id: string) { const html: string = (await mcp.tools.call("get_ticket", { id })).raw._meta["ui/html"]; const body = html.slice(html.indexOf("")); const tag = body.match(/]*data-tool-call=["']close_ticket["'][^>]*>/)?.[0]; if (!tag) return "no close_ticket button"; const raw = tag.match(/data-tool-args=(?:"([^"]*)"|'([^']*)')/); if (!raw) return "no data-tool-args"; return JSON.parse((raw[1] ?? raw[2]).replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&")); } test("T-1's widget has a button that calls `close_ticket` for T-1", async ({ mcp }) => { expect(await closeButtonArgs(mcp, "T-1")).toEqual({ id: "T-1" }); }); test("T-3's widget closes T-3, not T-1", async ({ mcp }) => { expect(await closeButtonArgs(mcp, "T-3")).toEqual({ id: "T-3" }); }); ``` **Hint:** The bridge reads two attributes on the button: the tool's name, and its arguments as JSON. Build the JSON from `ctx.output` so each ticket's button closes that ticket. **Solution:** `data-tool-call="close_ticket"` names the tool, and `data-tool-args="${JSON.stringify({ id: ctx.output.id })}"` gives it the id of the ticket on screen. `html` escapes the JSON's quotes, and the browser restores them when the bridge reads the attribute. Press the button in the Widget tab to see the call in the Wire tab. ### Challenge: Make the widget fit in The widget is a white card in a frame that's always 240 pixels tall, and in a dark host it stays white. Make it report its height to the host, and give the card colors that follow the host's light or dark theme. Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; status: string }; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { template: (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

      ${ctx.output.title}

      ${ctx.output.id} · ${ctx.output.status}

      `, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } ``` **Solution file (alternative to the starter):** ```ts get-ticket.tool.ts solution import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; type Ticket = { id: string; title: string; status: string }; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { autoResize: true, template: (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

      ${ctx.output.title}

      ${ctx.output.id} · ${ctx.output.status}

      `, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts fit.test.ts hidden import { test, expect } from "@frontmcp/testing"; const page = async (mcp: any): Promise => (await mcp.tools.call("get_ticket", { id: "T-1" })).raw._meta["ui/html"]; test("`get_ticket` has a size hint, so the widget reports its height", async ({ mcp }) => { const [tool] = await mcp.tools.list(); const ui = tool._meta.ui; const hinted = ui.autoResize === true || ["preferredHeight", "minHeight", "maxHeight", "aspectRatio"].some((k) => k in ui); expect(hinted && ui.autoResize !== false).toBe(true); }); test("the card's colors come in a light and a dark version (`light-dark()`)", async ({ mcp }) => { expect(await page(mcp)).toMatch(/\.ticket\s*\{[^}]*light-dark\(/); }); test("the page sets no `color-scheme` of its own, so the bridge's applies", async ({ mcp }) => { const html = await page(mcp); const styles = html.slice(html.indexOf("")).match(/

      Open tickets

        ${ctx.output.tickets.map((t) => ctx.helpers.html`
      • ${t.id} ${t.title} (${t.priority})
      • `)}
      `, }, }) export class ListQueue extends ToolContext { async execute(): Promise { return { tickets: openTickets() }; } } ``` ```ts tickets.ts export type QueueItem = { id: string; title: string; priority: "high" | "normal" }; export type Queue = { tickets: QueueItem[] }; const tickets = [ { id: "T-1", title: "Cannot log in", priority: "high", status: "open" }, { id: "T-2", title: "Invoice total is wrong", priority: "normal", status: "closed" }, { id: "T-3", title: "Login link expired", priority: "normal", status: "open" }, ] as const; export function openTickets(): QueueItem[] { return tickets.filter((t) => t.status === "open").map(({ id, title, priority }) => ({ id, title, priority })); } ``` ```ts inline.test.ts import { test, expect } from "@frontmcp/testing"; test("every result carries a whole page", async ({ mcp }) => { const html: string = (await mcp.tools.call("list_queue", {})).raw._meta["ui/html"]; expect(html.length).toBeGreaterThan(25_000); expect(html).toContain("
    • T-1 Cannot log in (high)
    • "); }); test("the widget's resource is a page without the data", async ({ mcp }) => { await mcp.tools.call("list_queue", {}); const page = (await mcp.resources.read("ui://widget/list_queue.html")).text(); expect(page).toContain("window.__mcpToolOutput = null;"); expect(page).not.toContain("Cannot log in"); }); ``` Inline is the simplest mode. The page has the data in its markup before any script runs, and the line under the widget says where the Playground took it from: `_meta["ui/html"]`. It costs two things: 1. **Size.** About 38 KB goes out with every result, most of it the bridge script. When the widget calls the tool itself to refresh, the bridge marks the call as its own and the answer comes back without a page, and the default `auto` mode sends no per-call page to OpenAI Apps SDK clients. Explicit `inline` keeps per-call pages there. 2. **Hosts that read the resource.** `tools/list` points every host at `ui://widget/list_queue.html`, and a host that loads the widget from there, as the MCP Apps extension describes, gets a page with the bridge and nothing else: FrontMCP only renders an inline template with a call's data, and a resource read has no call. ## Static: one page, the data from the host With `servingMode: "static"`, FrontMCP renders the template once, when the server starts, and serves that page as the resource. Results carry no page at all. The host reads the resource, then sends the page each call's result, and a script in the page draws it: Initial call configuration: ```js { tool: "list_queue", arguments: {} } ``` ```ts list-queue.tool.ts active import { Tool, ToolContext, type TemplateContext } from "@frontmcp/sdk"; import { openTickets, type Queue } from "./tickets"; @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, ui: { servingMode: "static", autoResize: true, // Rendered once, at startup: nothing here depends on a call. template: (ctx: TemplateContext<{}, Partial>) => ctx.helpers.html`

      Open tickets

        `, }, }) export class ListQueue extends ToolContext { async execute(): Promise { return { tickets: openTickets() }; } } ``` ```ts tickets.ts export type QueueItem = { id: string; title: string; priority: "high" | "normal" }; export type Queue = { tickets: QueueItem[] }; const tickets = [ { id: "T-1", title: "Cannot log in", priority: "high", status: "open" }, { id: "T-2", title: "Invoice total is wrong", priority: "normal", status: "closed" }, { id: "T-3", title: "Login link expired", priority: "normal", status: "open" }, ] as const; export function openTickets(): QueueItem[] { return tickets.filter((t) => t.status === "open").map(({ id, title, priority }) => ({ id, title, priority })); } ``` ```ts static.test.ts import { test, expect } from "@frontmcp/testing"; test("results carry no page", async ({ mcp }) => { const result = await mcp.tools.call("list_queue", {}); expect(Object.keys(result.raw._meta).filter((k) => k.startsWith("ui/"))).toEqual([]); expect(result.raw.structuredContent.tickets).toHaveLength(2); }); test("the resource is the page, rendered once with empty data", async ({ mcp }) => { const page = (await mcp.resources.read("ui://widget/list_queue.html")).text(); expect(page).toContain('
          '); expect(page).toContain("window.__mcpToolOutput = null;"); }); test("tools/list points hosts at it, as before", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool._meta.ui.resourceUri).toBe("ui://widget/list_queue.html"); }); ``` The widget looks the same, but the line under it now says the page came from `resources/read ui://widget/list_queue.html`. Open the **Wire** tab: the Playground read the resource once, and the `tools/call` result has no `ui/html` in it. Here is what happened: 1. When the server started, FrontMCP called the template with `ctx.output` set to `{}` and kept the page. The page carries no data of its own: `window.__mcpToolOutput` is `null`, as the second test checks. 2. The call's result went out without a page. 3. The host read the tool's `resourceUri` and put that page in a frame. The Playground reads it once per server start, since it's the same for every call. 4. When the bridge had finished its handshake, the host sent the page the call's result, and the bridge fired `tool:result` with it. `event.detail.structuredContent` is the object `execute()` returned. The script builds the list with `textContent`, not `innerHTML`. `ctx.helpers.html` escaped what the template put in the page, but the data a static widget shows arrives later, in the browser, where nothing escapes it for you. > **Pitfall: A static template runs with empty data** > > At startup there's no call, so `ctx.output` is `{}`. A static template that reads deeper, like `ctx.output.tickets.map(…)`, throws. The server logs `Failed to compile static widget for tool "list_queue": Cannot read properties of undefined (reading 'map')`, starts anyway, and serves the empty page for that tool. Type the output as `Partial<…>` so TypeScript reminds you, and render anything that depends on a call from the host's result. > **Note** > > The bridge also has `FrontMcpBridge.getToolOutput()`. In an inline page it returns what `execute()` returned, and in a static page `null`, until an MCP Apps host sends the result. Then it returns the result's `structuredContent`, the same object the event carries. A result that failed has none, and the output is the error's message as a string, so a widget that shows failures checks for a missing `structuredContent`, as the Expense Dashboard's script does. Before 1.8.7 the output became the result's `content` array, `[{ type: "text", text: "{…}" }]`, and widgets had to read `getStructuredContent()` or the event instead. Choose static when the page is big, when the same widget shows many results, or when hosts that load widgets from the resource matter to you. Choose inline when the page is small and simplest wins, or when the widget needs the data before its scripts run. The [Expense Dashboard](https://frontmcp.dev/examples/expense-dashboard) is a static widget whose filters call the tool again for another month or team. ## One mode for every tool A server whose widgets are all static would need `servingMode: "static"` on every tool, and a tool that forgets it goes out inline. Set it once instead. `@FrontMcp({ ui: { servingMode: "static" } })` is the mode of every tool that doesn't choose its own, and `@App({ ui: { servingMode } })` is the mode of one app's tools. A tool's own `servingMode` wins, then its app's, then the server's. Here the help desk serves everything static, except a small badge that is cheap enough to send inline: Initial call configuration: ```js { tool: "list_queue", arguments: {} } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, type TemplateContext } from "@frontmcp/sdk"; @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, ui: { template: (ctx: TemplateContext<{}, {}>) => ctx.helpers.html`

          Open tickets

          ` }, }) class ListQueue extends ToolContext { async execute() { return { open: 2 }; } } @Tool({ name: "team_stats", description: "How many tickets each agent closed this week.", inputSchema: {}, ui: { template: (ctx: TemplateContext<{}, {}>) => ctx.helpers.html`

          This week

          ` }, }) class TeamStats extends ToolContext { async execute() { return { closed: { sam: 4, nour: 6 } }; } } @Tool({ name: "ticket_badge", description: "A one-line badge for a ticket.", inputSchema: {}, ui: { servingMode: "inline", template: (ctx: TemplateContext<{}, { id: string }>) => ctx.helpers.html`${ctx.output.id}` }, }) class TicketBadge extends ToolContext { async execute() { return { id: "T-1" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ListQueue, TeamStats, TicketBadge] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], ui: { servingMode: "static" }, }) export default class Server {} ``` ```ts defaults.test.ts import { test, expect } from "@frontmcp/testing"; async function uiKeys(mcp: any, name: string) { const result = await mcp.tools.call(name, {}); return Object.keys(result.raw._meta).filter((k) => k.startsWith("ui/")); } test("tools that don't choose are served static", async ({ mcp }) => { expect(await uiKeys(mcp, "list_queue")).toEqual([]); expect(await uiKeys(mcp, "team_stats")).toEqual([]); expect((await mcp.resources.read("ui://widget/team_stats.html")).text()).toContain("

          This week

          "); }); test("a tool's own servingMode wins", async ({ mcp }) => { expect(await uiKeys(mcp, "ticket_badge")).toEqual(["ui/html", "ui/type", "ui/mimeType"]); }); ``` A tool that takes `"static"` from the server is rendered at startup, like one that sets it, so the [pitfall above](https://frontmcp.dev/learn/choosing-how-a-widget-is-served#static-one-page-the-data-from-the-host) applies to it too: its template gets `ctx.output` set to `{}`. Both options take the same six values as a tool, and anything else stops the server at startup with `Invalid option: expected one of "auto"|"inline"|"static"|"hybrid"|"direct-url"|"custom-url"`. Before 1.9.4, `@FrontMcp` and `@App` accepted a `ui.servingMode` and ignored it. ## What the other modes do `servingMode` accepts six values, and FrontMCP handles them like this: | `servingMode` | The `tools/call` result | The resource | | --- | --- | --- | | `"auto"` (the default) | The page, except for OpenAI clients, which get no inline page | A page without data | | `"inline"` | The page rendered with this call's data, including for OpenAI | A page without data | | `"static"` | No page | The page, rendered once at startup | | `"hybrid"` | For clients detected as MCP Apps hosts (the `"ext-apps"` platform) and two other platforms, a small `ui/component` object with no HTML or code in it. For every other client, no page. | As `"static"` | | `"direct-url"`, `"custom-url"` | No page | A shell framing the server's `directPath` or `customWidgetUrl` | Inline renders with each call's data; static builds once and receives data from the host. Hybrid adds a reference object for a few platforms. URL modes frame a page served by the server or another deployment. Changed in 1.11.3: before, both URL modes fell back to inline and ignored their URL options. FrontMCP guesses a client's platform from the name it sends. A client that declares the MCP Apps extension is `"ext-apps"` whatever its name, unless a mapping of yours says otherwise. The server below has a host that doesn't declare it, so it maps the host's name, `acme-desk`, to `"ext-apps"`. The tests call the tools as `acme-desk` and as another client: Initial call configuration: ```js { tool: "hybrid_queue", arguments: {} } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, type TemplateContext } from "@frontmcp/sdk"; const heading = (ctx: TemplateContext<{}, {}>) => ctx.helpers.html`

          Open tickets

          `; @Tool({ name: "hybrid_queue", description: "Open tickets, served hybrid.", inputSchema: {}, ui: { template: heading, servingMode: "hybrid" } }) class HybridQueue extends ToolContext { async execute() { return { open: 2 }; } } @Tool({ name: "url_queue", description: "Open tickets, served from a URL.", inputSchema: {}, ui: { template: heading, servingMode: "direct-url", directPath: "/widgets/queue" }, }) class UrlQueue extends ToolContext { async execute() { return { open: 2 }; } } @App({ id: "help-desk", name: "Help Desk", tools: [HybridQueue, UrlQueue] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], transport: { platformDetection: { mappings: [{ pattern: "acme-desk", platform: "ext-apps" }] } }, }) export default class Server {} ``` ```ts modes.test.ts import { test, expect } from "@frontmcp/testing"; // Calls a tool as the client named `client`, and returns its result's ui/* keys. async function uiKeys(mcp: any, client: string, name: string) { const body = await mcp.raw.request({ method: "tools/call", params: { name, arguments: {}, _meta: { "io.modelcontextprotocol/clientInfo": { name: client, version: "1.0.0" } } }, }); return Object.fromEntries(Object.entries(body.result._meta).filter(([k]) => k.startsWith("ui/"))); } test("hybrid: an MCP Apps host gets a component object, with no page", async ({ mcp }) => { const keys = await uiKeys(mcp, "acme-desk", "hybrid_queue"); expect(keys["ui/component"]).toEqual({ type: "html", hash: expect.any(String), toolName: "hybrid_queue" }); expect(keys["ui/html"]).toBeUndefined(); }); test("hybrid: other clients get nothing at all, as with static", async ({ mcp }) => { expect(await uiKeys(mcp, "my-mcp-client", "hybrid_queue")).toEqual({}); }); test("direct-url: the result carries no inline page", async ({ mcp }) => { const keys = await uiKeys(mcp, "my-mcp-client", "url_queue"); expect(keys["ui/html"]).toBeUndefined(); expect(JSON.stringify(keys)).not.toContain("/widgets/queue"); }); ``` The object holds no HTML and no code, so a host still needs the page from the resource to show anything. How FrontMCP recognizes a platform, and what each one gets, is on [Hosts and platforms](https://frontmcp.dev/reference/ui/hosts#how-frontmcp-recognizes-the-client). ## What a widget can load The page FrontMCP renders has a Content Security Policy of its own, in a `` tag. Unless the tool says otherwise, it allows scripts and styles written in the page or loaded from five CDNs (`cdn.jsdelivr.net`, `cdnjs.cloudflare.com`, `fonts.googleapis.com`, `fonts.gstatic.com` and `esm.sh`), images and fonts from those CDNs or `data:` URLs, and network requests to those CDNs only. So a widget can't `fetch()` your API until the tool lists it. Say the ticket widget should show a ticket's history, which lives at `https://api.helpdesk.example`. The tool's `ui.csp` option is where you list that origin, and FrontMCP puts it into the page's policy. The widget below prints the `connect-src` its own page ended up with: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts active import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; type Ticket = { id: string; title: string }; const template = (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

          ${ctx.output.title}

          This page lets fetch() reach:

          `; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { autoResize: true, // ✅ The widget may call the help desk's API itself csp: { connectDomains: ["https://api.helpdesk.example"] }, template, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in" }; } } @Tool({ name: "get_ticket_plain", description: "The same tool, with no csp.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { template }, }) export class GetTicketPlain extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in" }; } } ``` ```ts csp.test.ts import { test, expect } from "@frontmcp/testing"; const connectSrc = async (mcp: any, name: string) => { const html: string = (await mcp.tools.call(name, { id: "T-1" })).raw._meta["ui/html"]; const policy = html.match(/Content-Security-Policy" content="([^"]*)"/)![1]; return policy.match(/connect-src ([^;]*)/)![1].split(" "); }; test("tools/list lists the origin for the host", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "get_ticket"); expect(tool._meta.ui.csp).toEqual({ connectDomains: ["https://api.helpdesk.example"] }); }); test("the page's own policy allows it, next to the CDNs", async ({ mcp }) => { expect(await connectSrc(mcp, "get_ticket")).toEqual([ "https://cdn.jsdelivr.net", "https://cdnjs.cloudflare.com", "https://fonts.googleapis.com", "https://fonts.gstatic.com", "https://esm.sh", "https://api.helpdesk.example", ]); }); test("without csp, the page can reach the CDNs and nothing else", async ({ mcp }) => { expect(await connectSrc(mcp, "get_ticket_plain")).toEqual([ "https://cdn.jsdelivr.net", "https://cdnjs.cloudflare.com", "https://fonts.googleapis.com", "https://fonts.gstatic.com", "https://esm.sh", ]); }); ``` With the origin listed, a `fetch("https://api.helpdesk.example/tickets/T-1/history")` in the page is allowed through. Without it, the browser blocks the request before it leaves: `fetch()` rejects with `Failed to fetch`, and the console says `Connecting to 'https://api.helpdesk.example/tickets/T-1/history' violates the following Content Security Policy directive: "connect-src https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://fonts.googleapis.com https://fonts.gstatic.com https://esm.sh". The action has been blocked.` This was checked in Chromium, with a local server standing in for the API. A few details of `ui.csp` matter: - **Secure origins count, and local ones.** `https://api.helpdesk.example`, a path like `https://api.helpdesk.example/v1`, a wildcard like `https://*.helpdesk.example` and a WebSocket like `wss://live.helpdesk.example` do, and so does `http://localhost:3000` while you develop. Plain `http://` to any other host doesn't: the server names it in a warning at startup and leaves it out of the page's policy. - **Both lists add to the CDNs**, which is why the test above sees six entries. `connectDomains` goes into `connect-src`. `resourceDomains` goes into the script, style, image and font sources, which is how an image from your own domain loads, and into `connect-src` too. - **The browser isn't the only one asking.** A host may build a policy of its own around the frame from the lists `csp` puts in `tools/list` and on the resource (`_meta.ui.csp` and `_meta["ui/csp"]`, with your keys and snake-case copies, and `_meta["openai/widgetCSP"]` for the OpenAI Apps SDK, from the moment the server starts). The page's policy is what FrontMCP controls; a host's is the host's. - **The API still has to allow the request.** The widget's page doesn't share your API's origin, so a `fetch()` needs the API's CORS headers (`Access-Control-Allow-Origin`), whatever the policy says. Changed in 1.9: `connectDomains` replaced the CDNs in `connect-src`, `esm.sh` apart, and only `https:` origins counted. When the API needs a secret, or doesn't send CORS headers, a tool is the better route: the widget asks the host to call one, and your server, which can reach the API, answers. Press **Show history**: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts active import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; type Ticket = { id: string; title: string }; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { template: (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

          ${ctx.output.title}

            `, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in" }; } } ``` ```ts history.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket_history", description: "What happened to a support ticket, oldest first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { readOnlyHint: true }, }) export class GetTicketHistory extends ToolContext { async execute({ id }: { id: string }) { // On a real server: this.fetch(`https://api.helpdesk.example/tickets/${id}/history`) return { events: [ { at: "09:12", what: `${id} opened by Acme Corp` }, { at: "09:40", what: "Assigned to Nour" }, ], }; } } ``` ```ts history.test.ts import { test, expect } from "@frontmcp/testing"; test("the history comes through a tool", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket_history", { id: "T-1" }); expect(result.json().events[0]).toEqual({ at: "09:12", what: "T-1 opened by Acme Corp" }); }); test("the widget never calls the API itself, so the tool lists no origin", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "get_ticket"); expect(tool._meta.ui.csp).toBeUndefined(); }); ``` Images follow `resourceDomains`: an image from your own domain loads once it's listed there. Without that, send small images as `data:` URLs, or use one of the CDNs. The [Tool UI reference](https://frontmcp.dev/reference/ui#content-security-policy) has the whole policy. ## The widget gets what `outputSchema` declares A widget shows the tool's result, and the result is also what the model reads. `outputSchema` keeps them tidy: fields it doesn't declare are dropped before the result goes out, from `structuredContent`, from the text the model reads and from the data the page gets. `get_ticket` below declares four fields and returns the whole row from its store, internal notes included. Open the **Tests** tab: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts active import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; import { rows } from "./rows"; const Ticket = { id: z.string(), title: z.string(), status: z.enum(["open", "closed"]), priority: z.enum(["high", "normal"]) }; type Card = { id: string; title: string; status: string; priority: string }; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, outputSchema: Ticket, ui: { template: (ctx: TemplateContext<{ id: string }, Card>) => ctx.helpers.html`

            ${ctx.output.title}

            ${ctx.output.status}

            ` }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return rows[id]; // the whole row } } ``` ```ts rows.ts // Rows as the help desk's database returns them. export const rows: Record = { "T-1": { id: "T-1", title: "Cannot log in", status: "open", priority: "high", internalNotes: "Acme is late on two invoices" }, "T-2": { id: "T-2", title: "Invoice total is wrong", status: "closed", internalNotes: "Third time this month" }, }; ``` ```ts fields.test.ts import { test, expect } from "@frontmcp/testing"; test("the notes never reach the model", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result.raw.structuredContent).toEqual({ id: "T-1", title: "Cannot log in", status: "open", priority: "high" }); expect(result.text()).not.toContain("Acme is late on two invoices"); }); test("or the page", async ({ mcp }) => { const html: string = (await mcp.tools.call("get_ticket", { id: "T-1" })).raw._meta["ui/html"]; expect(html).toContain("

            Cannot log in

            "); expect(html).not.toContain("internalNotes"); }); test("a declared field the row doesn't have fails the call", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-2" }); expect(result).toBeError("INVALID_OUTPUT"); expect(result.raw._meta["ui/html"]).toBeUndefined(); }); ``` The widget shows a title and a status, and the notes are nowhere: not in `structuredContent`, not in the text block the model reads, and not in the page, in `window.__mcpToolOutput`, where anyone who opens the frame's source could read them. `outputSchema` also still checks the fields it declares: `T-2` has no `priority`, so its call fails with `INVALID_OUTPUT`, as it would without `ui`. The other side of the same rule is that the widget gets nothing the schema leaves out. A template that reads `ctx.output.priority` shows nothing when `priority` isn't in `outputSchema`, even though the row has it. Declare every field the widget shows, and then the model gets it too: design one result that's right for both, and keep what neither should have out of it. Changed in 1.8.7: with `ui` set, FrontMCP used to skip this step. A tool with an `outputSchema` sent whatever `execute()` returned, notes included, to the model and into the page, and the fix was to return only the declared fields, like `Ticket.parse(row)` with a Zod object. That's no longer needed, and a widget that read a field the schema doesn't declare now gets `undefined` for it. ## Recap - The default `auto` mode sends the page with each call except for OpenAI clients. Explicit `inline` sends it there too. Its resource is a page without call data. - Static renders the page once at startup, with `ctx.output` set to `{}`, and serves it as the resource. The host sends each result, and the page draws it from the `tool:result` event's `structuredContent`, with `textContent`. - `@FrontMcp({ ui: { servingMode } })` sets the mode of every tool that doesn't choose its own, and `@App({ ui: { servingMode } })` that of one app's tools. The tool wins, then the app, then the server. - `"hybrid"` adds a code-free `ui/component` reference for a few platforms. URL modes frame a page served at `directPath` or `customWidgetUrl`. - The page's own Content Security Policy allows the five CDNs, and the origins in `ui.csp`, secure or local: `connectDomains` for `fetch()`, `resourceDomains` for images, scripts and fonts. The API still needs CORS headers. A tool the widget calls avoids both. - `outputSchema` drops the fields it doesn't declare from the result, the text the model reads and the page, `ui` or not. Declare every field the widget shows. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Serve the queue once The queue widget is served inline, so every call carries a page. Serve it statically: results should carry no page, and the page the host reads should still show the heading and draw the tickets the host sends it. Initial call configuration: ```js { tool: "list_queue", arguments: {} } ``` ```ts list-queue.tool.ts import { Tool, ToolContext, type TemplateContext } from "@frontmcp/sdk"; type Queue = { tickets: { id: string; title: string }[] }; @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, ui: { template: (ctx: TemplateContext<{}, Queue>) => ctx.helpers.html`

            Open tickets

              ${ctx.output.tickets.map((t) => ctx.helpers.html`
            • ${t.id} ${t.title}
            • `)}
            `, }, }) export class ListQueue extends ToolContext { async execute(): Promise { return { tickets: [{ id: "T-1", title: "Cannot log in" }, { id: "T-3", title: "Login link expired" }] }; } } ``` **Solution file (alternative to the starter):** ```ts list-queue.tool.ts solution import { Tool, ToolContext, type TemplateContext } from "@frontmcp/sdk"; type Queue = { tickets: { id: string; title: string }[] }; @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, ui: { servingMode: "static", template: (ctx: TemplateContext<{}, Partial>) => ctx.helpers.html`

            Open tickets

              `, }, }) export class ListQueue extends ToolContext { async execute(): Promise { return { tickets: [{ id: "T-1", title: "Cannot log in" }, { id: "T-3", title: "Login link expired" }] }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts static.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`list_queue` results carry no page", async ({ mcp }) => { const result = await mcp.tools.call("list_queue", {}); expect(result).toBeSuccessful(); expect(Object.keys(result.raw._meta).filter((k) => k.startsWith("ui/"))).toEqual([]); }); test("the page the host reads has the heading", async ({ mcp }) => { const page = (await mcp.resources.read("ui://widget/list_queue.html")).text(); expect(page).toContain("

              Open tickets

              "); }); test("the page draws the tickets from the host's `structuredContent`", async ({ mcp }) => { const page = (await mcp.resources.read("ui://widget/list_queue.html")).text(); const body = page.slice(page.lastIndexOf("

              ")); expect(body).toContain("structuredContent"); }); ``` **Hint:** Setting `servingMode` is half of it. A static template runs once, at startup, with `ctx.output` set to `{}`: what does `ctx.output.tickets.map` do then? Draw the list in the browser instead, when the host sends the result. **Solution:** `servingMode: "static"` takes the page out of the results and serves it as the resource. The template no longer reads `ctx.output`, which is `{}` at startup, so it renders; before, it threw and the server served an empty page. The script listens for `tool:result` and builds the list from `event.detail.structuredContent` with `textContent`, so ticket titles stay text. ### Challenge: Show the priority The ticket widget shows a title, a status and a priority line, but the priority line is always empty, though every ticket has one. Make the widget show it, without sending the internal notes. Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-3" } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; import { rows } from "./rows"; const Ticket = z.object({ id: z.string(), title: z.string(), status: z.enum(["open", "closed"]) }); type Card = z.infer & { priority?: string }; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, outputSchema: Ticket, ui: { template: (ctx: TemplateContext<{ id: string }, Card>) => ctx.helpers.html`

              ${ctx.output.title}

              Status: ${ctx.output.status}

              Priority: ${ctx.output.priority}

              `, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return rows[id]; } } ``` **Solution file (alternative to the starter):** ```ts get-ticket.tool.ts solution import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; import { rows } from "./rows"; const Ticket = z.object({ id: z.string(), title: z.string(), status: z.enum(["open", "closed"]), priority: z.enum(["high", "normal"]) }); type Ticket = z.infer; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, outputSchema: Ticket, ui: { template: (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

              ${ctx.output.title}

              Status: ${ctx.output.status}

              Priority: ${ctx.output.priority}

              `, }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return rows[id]; } } ``` ```ts rows.ts export const rows: Record = { "T-1": { id: "T-1", title: "Cannot log in", status: "open", priority: "high", internalNotes: "Acme is late on two invoices" }, "T-3": { id: "T-3", title: "Login link expired", status: "open", priority: "normal", internalNotes: "Third time this month" }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts fields.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("the widget shows the ticket's priority", async ({ mcp }) => { const html: string = (await mcp.tools.call("get_ticket", { id: "T-3" })).raw._meta["ui/html"]; expect(html).toContain("

              Priority: normal

              "); }); test("`priority` is in the result the model reads", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result.raw.structuredContent.priority).toBe("high"); }); test("the internal notes still go nowhere", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-3" }); expect(result.text()).not.toContain("Third time this month"); expect((result.raw._meta["ui/html"] as string)).not.toContain("Third time this month"); }); ``` **Hint:** The template reads `ctx.output.priority`, and the row has it. What decides which fields of the row reach the template? **Solution:** The template gets what the tool's `outputSchema` declares, and `Ticket` leaves `priority` out, so `ctx.output.priority` is `undefined` and `html` renders nothing for it. Adding `priority` to the schema puts it in the result, the text the model reads and the page's data, while `internalNotes`, which the schema still doesn't declare, goes nowhere. --- # Building Widgets with React > Build FrontMCP widgets as React components: bundling, props, @frontmcp/ui/react hooks, calling tools with useCallTool, theme and size. Runs on Node, not the Playground. Source: https://frontmcp.dev/learn/building-widgets-with-react [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A template function builds a page from a string, and for a card that's all it takes. A widget with state is different: a queue you can filter, buttons that show they're working, an error next to the row it belongs to. As a template, that becomes a script inside a string, with no types and every change to the page made by hand. FrontMCP can build a widget from a React component in a `.tsx` file instead. It bundles the file, mounts the component with the call's data, and `@frontmcp/ui/react` gives it hooks to read the result and call tools through the host. The Playground can't run React widgets: FrontMCP bundles a widget file from the file system, on a Node server, and the Playground runs FrontMCP in your browser ([below](https://frontmcp.dev/learn/building-widgets-with-react#pointing-a-tool-at-a-widget-file), it shows what happens). So the widget files in this lesson are code blocks, and each one was run for real: bundled by a FrontMCP 1.9.3 server on Node, and rendered in Chromium in an MCP Apps host like the Playground's. The Playgrounds run what does run here: the tools, and the calls widgets make to them. **You will learn** - When a widget is worth writing in React - How to point a tool at a `.tsx` file, and what the project needs to bundle it - What the component gets as props, and what to check before it draws them - How to call a tool with `useCallTool()`, and handle each way a call can end - How to follow the host's theme, size the widget, and choose where React is loaded from ## When a template gets too big Here is the queue widget as a template function. It lists the open tickets, filters them to high priority, and closes a ticket from its row. Try it: Initial call configuration: ```js { tool: "list_queue", arguments: {} } ``` ```ts list-queue.tool.ts active import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; import { openTickets, type Queue } from "./tickets"; @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, ui: { template: (ctx: TemplateContext<{}, Queue>) => ctx.helpers.html`
                ${ctx.output.tickets.map((t) => ctx.helpers.html`
              • ${t.id} ${t.title}
              • `)}
              `, }, }) export class ListQueue extends ToolContext { async execute(): Promise { return { tickets: openTickets() }; } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); if (ticket.status === "closed") this.fail(new PublicMcpError(`${id} is already closed.`)); ticket.status = "closed"; return { id, status: "closed" as const }; } } ``` ```ts tickets.ts export type Ticket = { id: string; title: string; priority: "high" | "normal" | "low"; status: "open" | "closed" }; export type Queue = { tickets: Omit[] }; export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", priority: "high", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", priority: "normal", status: "closed" }], ["T-3", { id: "T-3", title: "Login link expired", priority: "normal", status: "open" }], ["T-4", { id: "T-4", title: "Password reset email missing", priority: "high", status: "open" }], ]); export function openTickets(): Queue["tickets"] { return [...tickets.values()].filter((t) => t.status === "open").map(({ id, title, priority }) => ({ id, title, priority })); } ``` It works, and it's already hard to change. The rows are written twice: once as HTML on the server, and again, piece by piece, by the script as they change. Each state a row can be in, closing, closed or failed, is a DOM edit made by hand, and the filter is a loop over elements. None of the script is type-checked, because it's a string. Add a "reassign" button and a count of open tickets, and it gets worse. That's the kind of widget worth writing in React. ## Pointing a tool at a widget file Put the component in a file of its own, export it as the default, and point `ui.template` at the file with `{ file }` and an absolute path: ```ts list-queue.tool.ts import { join } from "node:path"; import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { openTickets } from "./tickets"; const QueueItem = z.object({ id: z.string(), title: z.string(), priority: z.enum(["high", "normal", "low"]) }); @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, outputSchema: { tickets: z.array(QueueItem) }, ui: { template: { file: join(__dirname, "queue.widget.tsx") } }, }) export class ListQueue extends ToolContext { async execute() { return { tickets: openTickets() }; } } ``` ```tsx queue.widget.tsx type Ticket = { id: string; title: string; priority: "high" | "normal" | "low" }; type Queue = { tickets: Ticket[] }; export default function QueueWidget({ output }: { output: Queue | null }) { if (!output?.tickets) return

              Loading the queue…

              ; return (
                {output.tickets.map((t) => (
              • {t.id} {t.title} ({t.priority})
              • ))}
              ); } ``` When the tool is called, FrontMCP bundles the file with esbuild, wraps the component in `McpBridgeProvider` from `@frontmcp/ui/react`, and sends a page that mounts it into `
              `, with `ui/type` set to `"react"`. The component gets three props: `output`, the call's result as `execute()` returned it; `input`, the call's arguments; and `loading`, which is `true` for the first render only. The project needs a few things for this to work: - **`@frontmcp/ui`**, even for a widget that imports nothing from it, because the code FrontMCP adds to mount your component does: `npm install @frontmcp/ui`. It brings React, React DOM, MUI and Emotion along as its peers. - **`esbuild`**, which a project made with `frontmcp create` already has, through the `frontmcp` CLI. In any other project, install it too, as a dependency and not a dev dependency, since FrontMCP loads it when the tool is called and `@frontmcp/uipack` only lists it as an optional peer. Without it every call logs `applyUI: UI rendering failed` with `FileSource widget "…/queue.widget.tsx" needs esbuild, which is not installed`, and the result has no page. - **A Node server**: CommonJS, which is what `frontmcp create` makes, or an ES module (`"type": "module"`), with `import.meta.dirname` in place of `__dirname`. Changed in 1.9: an ES module server couldn't bundle widget files, and logged `Dynamic require of "path" is not supported`. - **An absolute path.** A relative `file` is resolved from the process's working directory, not from the tool's file, so use `join(__dirname, …)`. `__dirname` is the folder the compiled tool runs from: `frontmcp build` copies the `.widget.tsx` files into its output, next to the bundle for `--target node`, but if you compile with `tsc`, copy them next to the output yourself. Otherwise the call logs `applyUI: UI rendering failed` with `FileSource widget not found (ENOENT): no file at "…/dist/queue.widget.tsx"`, and the message names the file under `src/` when the same path exists there. - **Keep widget files out of the server's own build.** The server's `tsc` doesn't need them, and would need JSX settings and React's types. A `frontmcp create` project's `tsconfig.json` already excludes `**/*.widget.tsx`. This is what the Playground does with that tool. It runs FrontMCP in your browser, which has no file system to bundle a widget from. The **Logs** tab counts one error: Initial call configuration: ```js { tool: "list_queue", arguments: {} } ``` ```ts list-queue.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { openTickets } from "./tickets"; const QueueItem = z.object({ id: z.string(), title: z.string(), priority: z.enum(["high", "normal", "low"]) }); @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, outputSchema: { tickets: z.array(QueueItem) }, // In a project: join(__dirname, "queue.widget.tsx") ui: { template: { file: "/help-desk/src/queue.widget.tsx" } }, }) export class ListQueue extends ToolContext { async execute() { return { tickets: openTickets() }; } } ``` ```ts tickets.ts type Ticket = { id: string; title: string; priority: "high" | "normal" | "low"; status: "open" | "closed" }; const tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", priority: "high", status: "open" }, { id: "T-2", title: "Invoice total is wrong", priority: "normal", status: "closed" }, { id: "T-3", title: "Login link expired", priority: "normal", status: "open" }, ]; export function openTickets() { return tickets.filter((t) => t.status === "open").map(({ id, title, priority }) => ({ id, title, priority })); } ``` ```ts no-page.test.ts import { test, expect } from "@frontmcp/testing"; test("the call succeeds, but its result has no page", async ({ mcp }) => { const result = await mcp.tools.call("list_queue", {}); expect(result).toBeSuccessful(); expect(result.raw._meta["ui/html"]).toBeUndefined(); }); test("tools/list still says the tool has a React widget", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool._meta).toEqual({ ui: { resourceUri: "ui://widget/list_queue.html" }, "frontmcp/type": "react" }); }); ``` The log has `applyUI: UI rendering failed` with `Dynamic require of "path" is not supported`, and the result went out without a page: a widget that can't be built costs the widget, not the call. On a Node server the same tool sends a page of about 59 KB. ## Reading the call's data The widget above shows the open tickets in Chromium, in an MCP Apps host like the Playground's. The page starts with `output` set to what `execute()` returned. Then the host sends the call's result, as MCP Apps hosts do, and the bridge replaces the output with that result's `structuredContent`: the same object, so the component renders the same tickets again. The check is on the field the widget needs, `output?.tickets`, and not on `output` itself. A static widget's `output` is `null` until the host sends a result, which `?.` handles, but a result that failed makes it a string, the error's message, which is truthy. `useStructuredContent()` returns the host's object too: the result's `structuredContent` from an MCP Apps host, `window.openai.toolOutput` from the OpenAI Apps SDK, and `undefined` before the host has sent anything. Widgets written for 1.8 read it first, since a static page started with `output` set to `{}`, which in the OpenAI Apps SDK stayed `{}` until the host assigned a new output ([Hosts and platforms](https://frontmcp.dev/reference/ui/hosts#the-openai-apps-sdk)). In 1.9.3 `output` is enough, and this still works: ```tsx queue.widget.tsx import { useStructuredContent } from "@frontmcp/ui/react"; type Ticket = { id: string; title: string; priority: "high" | "normal" | "low" }; type Queue = { tickets: Ticket[] }; export default function QueueWidget({ output }: { output: Queue | null }) { const queue = useStructuredContent() ?? (output?.tickets ? output : null); if (!queue) return

              Loading the queue…

              ; return (
                {queue.tickets.map((t) => (
              • {t.id} {t.title} ({t.priority})
              • ))}
              ); } ``` The widget reads the object the tool returned, so that's what the tool has to get right. The Playground can run this side: Initial call configuration: ```js { tool: "list_queue", arguments: {} } ``` ```ts list-queue.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { openTickets } from "./tickets"; const QueueItem = z.object({ id: z.string(), title: z.string(), priority: z.enum(["high", "normal", "low"]) }); @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, outputSchema: { tickets: z.array(QueueItem) }, }) export class ListQueue extends ToolContext { async execute() { return { tickets: openTickets() }; } } ``` ```ts tickets.ts type Ticket = { id: string; title: string; priority: "high" | "normal" | "low"; status: "open" | "closed" }; const tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", priority: "high", status: "open" }, { id: "T-2", title: "Invoice total is wrong", priority: "normal", status: "closed" }, { id: "T-3", title: "Login link expired", priority: "normal", status: "open" }, ]; export function openTickets() { return tickets.filter((t) => t.status === "open").map(({ id, title, priority }) => ({ id, title, priority })); } ``` ```ts data.test.ts import { test, expect } from "@frontmcp/testing"; const queue = { tickets: [{ id: "T-1", title: "Cannot log in", priority: "high" }, { id: "T-3", title: "Login link expired", priority: "normal" }] }; test("structuredContent is the object the widget gets as `output`", async ({ mcp }) => { const result = await mcp.tools.call("list_queue", {}); expect(result.raw.structuredContent).toEqual(queue); }); test("the model reads the same object, as text", async ({ mcp }) => { const result = await mcp.tools.call("list_queue", {}); expect(result.raw.content).toEqual([{ type: "text", text: JSON.stringify(queue) }]); }); ``` Return an object, not an array: a tool that returns an array sends `structuredContent` as `{ "value": [...] }` ([Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results#what-comes-back-from-toolscall)), and the widget has to know that. The other hooks for the call's data, `useToolOutput()` and `useToolInput()`, are in the [Widget components reference](https://frontmcp.dev/reference/ui/components#hooks). Changed in 1.8.7: after the host's result, `output` used to be the result's `content` array, `[{ type: "text", text: "{\"tickets\":[…]}" }]`, and a widget that checked `output?.tickets` showed `Loading the queue…` for good. Widgets read `useStructuredContent()` first to get around it. Both work now. ## Calling a tool with `useCallTool` Each row gets a Close button. `useCallTool(name)` returns a function that calls the tool through the host, and the state of the last call: ```tsx function TicketRow({ ticket }: { ticket: Ticket }) { const [close, { data, loading, error }] = useCallTool<{ id: string }, { id: string; status: "closed" }>("close_ticket"); const closed = data?.structuredContent?.status === "closed"; return (
            • {ticket.id} {ticket.title}{" "} {closed ? ( Closed ) : ( )} {data?.isError &&

              {data.content[0]?.text}

              } {error &&

              {error.message}

              }
            • ); } ``` A call can end three ways, and each has its place in the state: - **It succeeds.** `data` is the host's whole result, so the tool's object is `data.structuredContent`. - **The tool fails.** That's still a result: `data.isError` is `true` and the message is in `data.content`. Closing a ticket someone else closed a minute ago shows `T-1 is already closed.` under its row. - **The call can't be made**, like in a host that didn't finish its handshake. Then `error` is set, with a message like `Tool calls not supported on this platform (ext-apps)`, and `close()` resolves with `null`. > **Pitfall: useCallTool returns a tuple** > > `useCallTool()` returns an array, not an object, so `const { call, loading } = useCallTool("close_ticket")` gives `undefined` for both. Destructure an array: `const [close, { data, loading, error }, reset] = useCallTool("close_ticket")`. The widget gets back whatever the host got from your server, so what `close_ticket` returns matters here too. Its errors should be `PublicMcpError`s, so the message the widget shows survives production. And it's better without a `ui` of its own. The bridge marks the widget's call with `_meta["frontmcp/widgetCall"]`, and when a tool with a widget gets a marked call, FrontMCP answers with the data and no page, provided the host passes that marker on. Under the OpenAI Apps SDK, `callTool()` can't send it, and there a tool with a widget sends its page, about 38 KB, into the widget on every click. This Playground has one tool of each kind, and the last test calls `get_ticket` the way the bridge does: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); if (ticket.status === "closed") this.fail(new PublicMcpError(`${id} is already closed.`)); ticket.status = "closed"; return { id, status: "closed" as const }; } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; import { tickets, type Ticket } from "./tickets"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { template: (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

              ${ctx.output.title}

              ` }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return tickets.get(id)!; } } ``` ```ts tickets.ts export type Ticket = { id: string; title: string; priority: "high" | "normal" | "low"; status: "open" | "closed" }; export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", priority: "high", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", priority: "normal", status: "closed" }], ]); ``` ```ts calls.test.ts import { test, expect } from "@frontmcp/testing"; test("success: data.structuredContent is the tool's object", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result.raw.structuredContent).toEqual({ id: "T-1", status: "closed" }); }); test("a failed tool: data.isError, with the message in content", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-2" }); expect(result.raw.isError).toBe(true); expect(result.raw.content).toEqual([{ type: "text", text: "T-2 is already closed." }]); }); test("close_ticket has no ui, so its results carry no page", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result.raw._meta["ui/html"]).toBeUndefined(); }); test("a tool with ui sends its page with a model's call", async ({ mcp }) => { const html: string = (await mcp.tools.call("get_ticket", { id: "T-1" })).raw._meta["ui/html"]; expect(html.length).toBeGreaterThan(25_000); }); test("a call the bridge marks as the widget's gets the data without the page", async ({ mcp }) => { const body = await mcp.raw.request({ method: "tools/call", params: { name: "get_ticket", arguments: { id: "T-1" }, _meta: { "frontmcp/widgetCall": true } }, }); expect(body.result.structuredContent.title).toBe("Cannot log in"); expect(body.result._meta["ui/html"]).toBeUndefined(); }); ``` For the server, a call from a widget is an ordinary `tools/call` from the host, with the host's identity and every check your tools already have ([Calling a tool from a widget](https://frontmcp.dev/reference/ui/hosts#calling-a-tool-from-a-widget)). ## The theme, the size, and where React comes from The bridge sets the page's `` and `` from the host's theme, as it does for a template ([Your First Widget](https://frontmcp.dev/learn/your-first-widget#following-the-hosts-theme)), so the browser's default colors and `light-dark()` in your CSS follow the host without code. When the component has to know, `useTheme()` returns `"light"` or `"dark"`: the host's answer to the handshake, then each change the host sends. In an MCP Apps host the component renders once before the host has answered the handshake, and again with its answer: `useTheme()`, `useCapability("canCallTools")` and `useHostContext()` start as `"light"`, `false` and the page's defaults, and update by themselves. A button that waits for `useCapability("canCallTools")` shows once the host can call tools, and stays away in a host that never answers. Handling `error` from `call()`, as above, covers the rest. Here is the whole widget, with the color of a high priority ticket picked from `useTheme()`: ```tsx queue.widget.tsx import { useState } from "react"; import { useCallTool, useTheme } from "@frontmcp/ui/react"; type Ticket = { id: string; title: string; priority: "high" | "normal" | "low" }; type Queue = { tickets: Ticket[] }; export default function QueueWidget({ output }: { output: Queue | null }) { const [highOnly, setHighOnly] = useState(false); const theme = useTheme(); if (!output?.tickets) return

              Loading the queue…

              ; const shown = highOnly ? output.tickets.filter((t) => t.priority === "high") : output.tickets; const urgent = theme === "dark" ? "#ff8a80" : "#b42318"; return (
                {shown.map((ticket) => ( ))}
              ); } function TicketRow({ ticket, urgent }: { ticket: Ticket; urgent: string }) { const [close, { data, loading, error }] = useCallTool<{ id: string }, { id: string; status: "closed" }>("close_ticket"); const closed = data?.structuredContent?.status === "closed"; return (
            • {ticket.id} {ticket.title} ({ticket.priority}){" "} {closed ? ( Closed ) : ( )} {data?.isError &&

              {data.content[0]?.text}

              } {error &&

              {error.message}

              }
            • ); } ``` With `autoResize: true` added to the tool's `ui`, this widget reports its height when it starts, and again when the filter or a closed ticket changes it. Nothing in the file is there for the size: the page measures its whole `` from outside, margins included, so the body's margin and the list's own count. In a dark host the text and the buttons use the dark scheme, and `useTheme()` is `"dark"` as soon as the host has answered, with no code to ask the bridge. Changed in 1.8.6: `useTheme()` used to stay `"light"` in an MCP Apps host until the host sent a change, because the handshake's context was merged without telling anyone. Widgets asked the bridge themselves, with `useMcpBridge()` on `bridge:ready`. The page also measured `#root`, which left out the body's margin, and could lose its first height, so widgets set `document.body.style.margin = "0"` and sent the first height themselves. None of that is needed now. Changed in 1.8.7: `useCapability()` and `useHostContext()` update too. They used to stay at `false` and `null`. Where React comes from is the other thing to decide, with `ui.resourceMode`: | `resourceMode` | The page | When to use it | | --- | --- | --- | | `"cdn"`, the default for most clients | About 59 KB. An import map loads React 19.2.4 from `esm.sh`. | Hosts whose frames can reach `esm.sh` | | `"inline"` | About 730 KB, React bundled in. Nothing is loaded from outside. | Hosts that block outside scripts, and static widgets meant for them | A `"cdn"` page whose frame can't reach `esm.sh` stays on `Loading widget...` for good, with nothing in the page to say why. Both were run in Chromium, with `esm.sh` blocked for the second. `@frontmcp/ui` also has React components built on MUI, like `Card`, `Badge`, `Button` and `Table`, with a theme provider for them. They make a page of about 460 KB. They're in the [Widget components reference](https://frontmcp.dev/reference/ui/components#components), with every hook. The [Expense Dashboard](https://frontmcp.dev/examples/expense-dashboard#running-it-for-real) shows a whole dashboard written this way, and what it took to run it. > **Note** > > `@frontmcp/react` sounds like it belongs on this page, but it's something else: a React client that runs a FrontMCP server inside a React app. It isn't for widgets. It has [a reference of its own](https://frontmcp.dev/reference/react). Widgets use `@frontmcp/ui/react`. ## Recap - Write a widget in React when it has state: filters, per-row actions, loading and error states. A card is fine as a template function. - `ui: { template: { file: join(__dirname, "queue.widget.tsx") } }` points a tool at a component file, exported as the default. The server, CommonJS or ES module, needs `@frontmcp/ui`, `esbuild`, and the widget file next to the compiled tool, which `frontmcp build` copies for you. The Playground can't bundle one. - The component gets `output`, `input` and `loading`. In an MCP Apps host, `output` becomes the result's `structuredContent` once the host sends the result. Check for the fields you need, not for `output`: an error's text is truthy. `useStructuredContent()` is the host's object too. - `const [call, { data, loading, error }] = useCallTool(name)`: `data` is the whole result, `data.isError` means the tool failed, and `error` means the call couldn't be made. Give the tools a widget calls `PublicMcpError`s and no `ui`: the bridge marks a widget's own calls so they come back without a page, but not under the OpenAI Apps SDK. - In an MCP Apps host, `useTheme()`, `useCapability()` and `useHostContext()` follow the host's handshake, and the page follows its theme by itself with `light-dark()` colors. Handle `error` from `call()` for a host that never answers. `autoResize: true` sizes the frame, with no margin or first-report code. - `resourceMode: "cdn"` loads React from `esm.sh`; `"inline"` bundles it, for hosts that can't reach it. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Return an object the widget can read The queue widget reads the tickets like this: ```tsx const queue = useStructuredContent<{ tickets: Ticket[] }>(); return
                {queue?.tickets.map((t) =>
              • {t.title}
              • )}
              ; ``` But `list_queue` returns an array, and the widget shows nothing. Make the tool return what the widget reads, and declare that shape so clients see it in `tools/list`. Initial call configuration: ```js { tool: "list_queue", arguments: {} } ``` ```ts list-queue.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { openTickets } from "./tickets"; @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, }) export class ListQueue extends ToolContext { async execute() { return openTickets(); } } ``` **Solution file (alternative to the starter):** ```ts list-queue.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { openTickets } from "./tickets"; const QueueItem = z.object({ id: z.string(), title: z.string(), priority: z.enum(["high", "normal", "low"]) }); @Tool({ name: "list_queue", description: "List the open support tickets, most urgent first.", inputSchema: {}, outputSchema: { tickets: z.array(QueueItem) }, }) export class ListQueue extends ToolContext { async execute() { return { tickets: openTickets() }; } } ``` ```ts tickets.ts type Ticket = { id: string; title: string; priority: "high" | "normal" | "low"; status: "open" | "closed" }; const tickets: Ticket[] = [ { id: "T-1", title: "Cannot log in", priority: "high", status: "open" }, { id: "T-2", title: "Invoice total is wrong", priority: "normal", status: "closed" }, { id: "T-4", title: "Password reset email missing", priority: "high", status: "open" }, ]; export function openTickets() { return tickets.filter((t) => t.status === "open").map(({ id, title, priority }) => ({ id, title, priority })); } ``` **Hidden fixture/test file (runs with the example):** ```ts shape.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`structuredContent.tickets` holds the open tickets", async ({ mcp }) => { const result = await mcp.tools.call("list_queue", {}); expect(result.raw.structuredContent).toEqual({ tickets: [ { id: "T-1", title: "Cannot log in", priority: "high" }, { id: "T-4", title: "Password reset email missing", priority: "high" }, ], }); }); test("`tools/list` declares `tickets` as an array", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool.outputSchema?.properties?.tickets?.type).toBe("array"); }); ``` **Hint:** What does FrontMCP put in `structuredContent` when `execute()` returns an array? The widget wants an object with a `tickets` field. **Solution:** An array arrives as `{ "value": [...] }`, so `queue.tickets` was `undefined`. Returning `{ tickets: openTickets() }` gives the widget the object it reads, and `outputSchema: { tickets: z.array(QueueItem) }` shows its shape in `tools/list` and checks every result against it. ### Challenge: Fail so the widget can say why The widget shows `data.content[0].text` under a row when `data.isError` is set. But `close_ticket` reports success for a ticket that's already closed, and for one that doesn't exist. Make it fail for both, with messages the widget can show as they are, in production too. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (ticket) ticket.status = "closed"; return { id, status: "closed" as const }; } } ``` **Solution file (alternative to the starter):** ```ts close-ticket.tool.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); if (ticket.status === "closed") this.fail(new PublicMcpError(`${id} is already closed.`)); ticket.status = "closed"; return { id, status: "closed" as const }; } } ``` ```ts tickets.ts type Ticket = { id: string; title: string; status: "open" | "closed" }; export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ]); ``` **Hidden fixture/test file (runs with the example):** ```ts close.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("closing an open ticket returns `{ id, status: \"closed\" }`", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result).toBeSuccessful(); expect(result.raw.structuredContent).toEqual({ id: "T-1", status: "closed" }); }); test("closing T-2, which is closed, fails with `T-2 is already closed.`", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-2" }); expect(result).toBeError("PUBLIC_ERROR"); expect(result.text()).toBe("T-2 is already closed."); }); test("closing T-9 fails with `There's no ticket T-9.`", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-9" }); expect(result).toBeError("PUBLIC_ERROR"); expect(result.text()).toBe("There's no ticket T-9."); }); ``` **Hint:** A tool fails with `this.fail()`. Which error class keeps its message in production, where FrontMCP hides the message of a plain `Error`? **Solution:** `this.fail(new PublicMcpError(…))` ends the call with `isError: true` and the message as the result's only text block, so the widget's `data.content[0].text` is exactly `T-2 is already closed.` A plain `Error` would work in development, but in production FrontMCP hides its message, and the widget would show a generic one. ### Challenge: Keep the widget's calls small Someone copied `get_ticket`'s `ui` onto `close_ticket`, so every result of `close_ticket` now carries a whole page. With explicit `servingMode: "inline"`, that includes OpenAI Apps SDK calls, whose bridge cannot mark a call as the widget's own. The default `auto` mode omits their inline page. Make `close_ticket` results small again, and keep `get_ticket`'s widget. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { template: (ctx: TemplateContext<{ id: string }, { id: string }>) => ctx.helpers.html`

              ${ctx.output.id} closed

              ` }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "closed"; return { id, status: "closed" as const }; } } ``` **Solution file (alternative to the starter):** ```ts close-ticket.tool.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "close_ticket", description: "Close a support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "closed"; return { id, status: "closed" as const }; } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z, type TemplateContext } from "@frontmcp/sdk"; import { tickets, type Ticket } from "./tickets"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, ui: { template: (ctx: TemplateContext<{ id: string }, Ticket>) => ctx.helpers.html`

              ${ctx.output.title}

              ${ctx.output.status}

              ` }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return tickets.get(id)!; } } ``` ```ts tickets.ts export type Ticket = { id: string; title: string; status: "open" | "closed" }; export const tickets = new Map([["T-1", { id: "T-1", title: "Cannot log in", status: "open" }]]); ``` **Hidden fixture/test file (runs with the example):** ```ts small.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`close_ticket` results carry no page", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result).toBeSuccessful(); expect(Object.keys(result.raw._meta ?? {}).filter((k) => k.startsWith("ui/"))).toEqual([]); }); test("`close_ticket` isn't listed with a widget", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "close_ticket"); expect(tool?._meta?.ui).toBeUndefined(); }); test("`get_ticket` still has its widget", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result.raw._meta["ui/html"]).toContain("

              Cannot log in

              "); }); ``` **Hint:** Which tool does a person look at, and which one does only the widget call? **Solution:** Without `ui`, `close_ticket` answers with its `content` and `structuredContent` only, a few dozen bytes instead of about 38 KB, whatever the host. The widget reads `data.structuredContent.status` and never needed the page. `get_ticket`, which people look at, keeps its widget. --- # Built-in Plugins and Adapters > The plugins and the adapter the FrontMCP team publishes, and when to reach for each. Caching results, remembering values across calls, asking for approval, feature flags, CodeCall, and turning an OpenAPI spec into tools. Source: https://frontmcp.dev/learn/built-in-plugins-and-adapters [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 In [Extending with Plugins](https://frontmcp.dev/learn/extending-with-plugins) you wrote a plugin that records every change in an audit log. Some jobs come up on almost every server, and for those the FrontMCP team publishes plugins of its own: answering a repeated lookup without running it again, remembering a user's preference, making sure a person agreed before something is deleted, shipping a tool to some users before the rest. There's also CodeCall, for servers with more tools than a model can read, and an adapter that turns an OpenAPI description of a REST API into tools. This chapter teaches each one with the help desk, and points out where FrontMCP behaves differently from what an option's name suggests. **In this chapter** - [How to answer repeated calls from a cache](https://frontmcp.dev/learn/caching-results) - [How tools remember values from one call to the next](https://frontmcp.dev/learn/remembering-across-calls) - [How to require a person's approval before a tool runs](https://frontmcp.dev/learn/asking-for-approval) - [How to turn tools on and off with feature flags](https://frontmcp.dev/learn/turning-features-on-and-off) - [How to let the model find tools and call them from a short script](https://frontmcp.dev/learn/letting-the-model-write-code-with-codecall) - [How to turn an OpenAPI spec into tools](https://frontmcp.dev/learn/wrapping-an-openapi-service) ## Using an official plugin Each is its own npm package. The plugins are registered like the one you wrote, with `SomePlugin.init({ ... })` in the `plugins` of an `@App`, for that app's tools, or of `@FrontMcp`, for every app's, and each adds something your code opts in to. What a plugin adds to `this`, like `this.remember`, reaches only the tools of the apps it's registered for: | Package | Adds | Lesson | | --- | --- | --- | | `@frontmcp/plugin-cache` | `cache` on `@Tool` | [Caching Results](https://frontmcp.dev/learn/caching-results) | | `@frontmcp/plugin-remember` | `this.remember`, and four memory tools you can turn on | [Remembering Across Calls](https://frontmcp.dev/learn/remembering-across-calls) | | `@frontmcp/plugin-approval` | `approval` on `@Tool`, and `this.approval` | [Asking for Approval](https://frontmcp.dev/learn/asking-for-approval) | | `@frontmcp/plugin-feature-flags` | `featureFlag` on tools, resources, prompts, skills and agents, and `this.featureFlags` | [Turning Features On and Off](https://frontmcp.dev/learn/turning-features-on-and-off) | | `@frontmcp/plugin-codecall` | Six `codecall:*` tools in front of yours | [Letting the Model Write Code with CodeCall](https://frontmcp.dev/learn/letting-the-model-write-code-with-codecall) | | `@frontmcp/adapters` | `OpenapiAdapter`: a tool for each operation in a spec | [Wrapping an OpenAPI Service](https://frontmcp.dev/learn/wrapping-an-openapi-service) | A few rules hold for all of them: - **Register a plugin with `init()`.** With no argument it's the same as `init({})`, the defaults, for the plugins whose options all have defaults. Feature flags need an `adapter`: `FeatureFlagPlugin.init()` throws a `FeatureFlagConfigurationError` without it. The bare class, `plugins: [SomePlugin]`, is the same as `init()` with no argument, so `plugins: [FeatureFlagPlugin]` stops the server with that error. Before 1.9.4 the bare class worked for the cache plugin only. - **`approval` and `featureFlag` need their plugin.** A server with a tool that declares one of them, and no plugin to enforce it, refuses to start, so a gate can't be left off by accident. `cache` and `codecall` without their plugin do nothing. - **Adapters go in `adapters`**, not in `plugins`: an app's, for that app, or `@FrontMcp`'s, whose adapter tools every app serves. - **Every package loads in CommonJS and ES module projects alike.** Before 1.9, an ES module project (`"type": "module"`) couldn't import the cache and CodeCall plugins: see [ES module projects](https://frontmcp.dev/reference/plugins#es-module-projects). ## Caching results A lookup the model repeats, like a customer's account from a slow CRM, doesn't need to run twice. With the cache plugin on the app and `cache: { ttl }` on the tool, the next call with the same arguments is answered from a store, without running `execute()`: Initial call configuration: ```js { tool: "get_customer", arguments: { id: "C-1" } } ``` ```ts help-desk.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { crm } from "./crm"; @Tool({ name: "get_customer", description: "Get a customer account by its id. May be up to 5 minutes old.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true }, cache: { ttl: 300 }, // seconds }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return crm.getCustomer(id); } } @App({ id: "help-desk", name: "Help Desk", tools: [GetCustomer], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], // the same answer for every caller }) export class HelpDeskApp {} ``` ```ts crm.ts // Stands in for a CRM that is slow to answer, and counts the requests it gets. export const crm = { requests: 0, async getCustomer(id: string) { crm.requests++; await new Promise((resolve) => setTimeout(resolve, 200)); return { id, name: id === "C-1" ? "Acme Corp" : "Globex", plan: "enterprise" }; }, }; ``` ```ts cache.test.ts import { test, expect } from "@frontmcp/testing"; import { crm } from "./crm"; test("the second call is answered from the cache", async ({ mcp }) => { const before = crm.requests; await mcp.tools.call("get_customer", { id: "C-2" }); const second = await mcp.tools.call("get_customer", { id: "C-2" }); expect(second.raw._meta?.cache).toBe("hit"); expect(crm.requests - before).toBe(1); }); ``` By default each caller has entries of their own. That keeps one user's answer from reaching another, and it also means an anonymous caller under MCP 2026-07-28, who is new on every request, is never answered from the cache. `keyByIdentity: false` shares entries, and is only safe for answers that are the same for everyone. ### [Caching Results](https://frontmcp.dev/learn/caching-results) Learn how to turn the cache on, why it answers nothing for anonymous callers, how to keep per-caller answers apart and share the rest, what makes two calls the same, how long an entry lives and why it can't be cleared, and what not to cache. ## Remembering across calls A tool forgets everything when its call ends. The Remember plugin gives every tool `this.remember`, a key-value memory whose **scope** decides who reads a value back. `user` scope keeps a value for the caller. The tests call the server in-process with [`createDirect()`](https://frontmcp.dev/learn/running-frontmcp-anywhere) as two signed-in agents, and as the Playground's anonymous client, which `user` scope refuses: Initial call configuration: ```js { tool: "draft_reply", arguments: { ticketId: "T-1", text: "You can log in again." } } ``` ```ts signature.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @Tool({ name: "set_signature", description: "Set the signature your replies end with.", inputSchema: { signature: z.string() } }) export class SetSignature extends ToolContext { async execute({ signature }: { signature: string }) { await this.remember.set("signature", signature, { scope: "user" }); return { signature }; } } @Tool({ name: "draft_reply", description: "Draft a reply, signed with your signature.", inputSchema: { ticketId: z.string(), text: z.string() } }) export class DraftReply extends ToolContext { async execute({ ticketId, text }: { ticketId: string; text: string }) { const signature = await this.remember.get("signature", { scope: "user", defaultValue: "The Help Desk" }); return { ticketId, reply: `${text}\n\n${signature}` }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetSignature, DraftReply], plugins: [RememberPlugin.init({ type: "memory" })] }) export class HelpDeskApp {} ``` ```ts remember.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { HelpDeskApp } from "./signature.app"; test("each signed-in agent's signature is their own", async () => { const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); const nour = { authContext: { user: { sub: "nour" } } }; const sam = { authContext: { user: { sub: "sam" } } }; await server.callTool("set_signature", { signature: "Nour, Tier 2 support" }, nour); const nours = await server.callTool("draft_reply", { ticketId: "T-1", text: "Fixed." }, nour); const sams = await server.callTool("draft_reply", { ticketId: "T-2", text: "Fixed." }, sam); expect(nours.structuredContent).toMatchObject({ reply: "Fixed.\n\nNour, Tier 2 support" }); expect(sams.structuredContent).toMatchObject({ reply: "Fixed.\n\nThe Help Desk" }); await server.dispose(); }); test("an anonymous caller is refused user scope, with a message that says why", async ({ mcp }) => { const result = await mcp.tools.call("set_signature", { signature: "Someone" }); expect(result).toBeError("REMEMBER_IDENTITY_REQUIRED"); expect(result).toHaveTextContent("Remember cannot use user scope without an authenticated user"); }); ``` The other scopes matter as much: `global` is shared by everyone, and `session`, the default, doesn't mean a conversation under MCP 2026-07-28. It lasts for the signed-in caller. An anonymous caller can't use `user` or `session`: Remember refuses it with `REMEMBER_IDENTITY_REQUIRED`, and only `global` works for it. ### [Remembering Across Calls](https://frontmcp.dev/learn/remembering-across-calls) Learn how to store and read values with `this.remember`, what each scope keeps for signed-in and anonymous callers under MCP 2026-07-28, how to make values expire and forget them, and how to give the model memory tools of its own, limited to the scopes you choose. ## Asking for approval `destructiveHint` tells a client a tool can't be undone, and the client may still run it without asking anyone. The approval plugin refuses every call to a tool with `approval` until an approval of it is recorded for the caller: Initial call configuration: ```js { tool: "delete_ticket", arguments: { id: "T-1" } } ``` ```ts help-desk.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApprovalPlugin } from "@frontmcp/plugin-approval"; export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in" }], ["T-2", { id: "T-2", title: "Invoice total is wrong" }], ]); @Tool({ name: "delete_ticket", description: "Delete a support ticket for good. Needs the user's approval: call approve_delete first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, approval: { approvalMessage: "delete_ticket needs the user's approval. Call approve_delete first." }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DeleteTicket], plugins: [ApprovalPlugin.init({ storage: { type: "memory" } })] }) export class HelpDeskApp {} ``` ```ts approval.test.ts import { test, expect } from "@frontmcp/testing"; import { tickets } from "./help-desk.app"; test("an unapproved delete is refused, and the ticket stays", async ({ mcp }) => { const result = await mcp.tools.call("delete_ticket", { id: "T-2" }); expect(result).toBeError(); expect(result.text()).toMatch(/^delete_ticket needs the user's approval/); expect(tickets.has("T-2")).toBe(true); }); ``` The plugin doesn't ask anyone itself. Your code records an approval, with `this.approval`, once the user says yes in a form from `this.elicit()`, which under MCP 2026-07-28 the model can't answer. An approval belongs to a signed-in caller, so an anonymous caller can never keep one. ### [Asking for Approval](https://frontmcp.dev/learn/asking-for-approval) Learn how to put a tool behind approval, what the model sees when a call is refused, which is the same in production, how to record an approval only after the user says yes, and how to withdraw one, limit how long it lasts, and why a session approval lasts for the user under MCP 2026-07-28. ## Turning features on and off A feature flag ships a tool to some users before the rest, or turns one off without a deploy. With the feature flags plugin, `featureFlag: "bulk-export"` on a tool hides it from every list while the flag is off for the caller, and refuses it if it's called anyway. Flags come from an adapter: fixed values, as here, or LaunchDarkly, Split, Unleash or your own. Open the **Capabilities** tab to see which tools are listed: Initial call configuration: ```js { tool: "search_tickets", arguments: {} } ``` ```ts help-desk.app.ts active import { App, Tool, ToolContext } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; @Tool({ name: "search_tickets", description: "Search support tickets.", inputSchema: {} }) export class SearchTickets extends ToolContext { async execute() { return { tickets: ["T-1", "T-3"] }; } } @Tool({ name: "bulk_export", description: "Export every ticket as CSV.", inputSchema: {}, featureFlag: "bulk-export" }) export class BulkExport extends ToolContext { async execute() { return { csv: "id,title\nT-1,Cannot log in" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, BulkExport], plugins: [FeatureFlagPlugin.init({ adapter: "static", flags: { "bulk-export": false } })], }) export class HelpDeskApp {} ``` ```ts flags.test.ts import { test, expect } from "@frontmcp/testing"; test("a tool whose flag is off isn't listed", async ({ mcp }) => { expect((await mcp.tools.list()).map((t: { name: string }) => t.name)).toEqual(["search_tickets"]); }); test("and is refused if it's called anyway", async ({ mcp }) => { const result = await mcp.tools.call("bulk_export", {}); expect(result).toBeError("FEATURE_FLAG_DISABLED"); expect(result).toHaveTextContent('Tool "bulk_export" is disabled by feature flag "bulk-export"'); }); ``` Change `"bulk-export": false` to `true`, and `bulk_export` appears. Each caller's flags are evaluated for them, from their token, so a flag can be on for some users and off for the rest; under MCP 2026-07-28 every anonymous caller gets the same answer. ### [Turning Features On and Off](https://frontmcp.dev/learn/turning-features-on-and-off) Learn why a switch inside `execute()` is the wrong way to hide a tool, how to put tools, resources and prompts behind a flag, what a caller sees while it's off, how to make a flag a kill switch that's on by default, and how to turn a flag on for some callers first and read it inside a tool. ## Letting the model write code with CodeCall A server with dozens of tools sends every tool's schema to the model before it can pick one. CodeCall puts them behind six meta-tools instead: the model searches with `codecall:search`, reads the schemas of the tools it picked with `codecall:describe`, and calls them one at a time with `codecall:invoke`, or several at once from a short script with `codecall:execute`: Initial call configuration: ```js { tool: "codecall:search", arguments: { queries: ["close a ticket"] } } ``` ```ts help-desk.app.ts active import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { CloseTicket, GetCustomer, GetTicket, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, GetTicket, CloseTicket, GetCustomer], plugins: [CodeCallPlugin.init({ mode: "codecall_only" })], }) export class HelpDeskApp {} ``` ```ts tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open", priority: "high", customerId: "C-1" }, { id: "T-2", title: "Invoice total is wrong", status: "open", priority: "low", customerId: "C-2" }, { id: "T-3", title: "Login link expired", status: "open", priority: "high", customerId: "C-2" }, ]; const customers = [ { id: "C-1", name: "Acme Corp", plan: "enterprise" }, { id: "C-2", name: "Globex", plan: "starter" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by status", inputSchema: { status: z.enum(["open", "closed"]).optional() }, }) export class SearchTickets extends ToolContext { async execute({ status }: { status?: "open" | "closed" }) { return { tickets: tickets.filter((t) => !status || t.status === status) }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().describe("A ticket id, like T-1") } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "get_customer", description: "Get a customer account by its id", inputSchema: { id: z.string() } }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return customers.find((c) => c.id === id) ?? this.fail(new PublicMcpError(`There's no customer ${id}.`)); } } ``` ```ts codecall.test.ts import { test, expect } from "@frontmcp/testing"; test("tools/list shows CodeCall's tools instead of the app's", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name); expect(names).toEqual([ "codecall:describe", "codecall:execute", "codecall:invoke", "codecall:search", "codecall:searchKnowledge", "codecall:searchSkills", ]); }); test("the model finds a tool by what it wants to do", async ({ mcp }) => { const { tools } = (await mcp.tools.call("codecall:search", { queries: ["close a ticket"] })).json(); expect(tools[0]).toMatchObject({ name: "close_ticket", appId: "help-desk" }); }); test("and calls it through codecall:invoke", async ({ mcp }) => { const result = await mcp.tools.call("codecall:invoke", { tool: "get_ticket", input: { id: "T-1" } }); expect(result.json()).toMatchObject({ id: "T-1", title: "Cannot log in" }); }); test("a script joins tools, and only its answer goes back", async ({ mcp }) => { const script = [ 'const { tickets } = await callTool("search_tickets", { status: "open" });', 'const urgent = tickets.filter((t) => t.priority === "high");', "const out = [];", "for (const t of urgent) {", ' const customer = await callTool("get_customer", { id: t.customerId });', " out.push({ ticket: t.id, customer: customer.name });", "}", "return out;", ].join("\n"); const answer = (await mcp.tools.call("codecall:execute", { script })).json(); expect(answer).toEqual({ status: "ok", result: [ { ticket: "T-1", customer: "Acme Corp" }, { ticket: "T-3", customer: "Globex" }, ], }); }); ``` A script runs on the server, in a sandbox, and can loop over results and join them, so only the answer goes back to the model. This one lists the urgent open tickets with their customers, in one request: ```js const { tickets } = await callTool("search_tickets", { status: "open" }); const urgent = tickets.filter((t) => t.priority === "high"); const out = []; for (const t of urgent) { const customer = await callTool("get_customer", { id: t.customerId }); out.push({ ticket: t.id, customer: customer.name }); } return out; ``` Here are the tools above again, with `codecall:execute` called with that script. The Playground runs it in a browser sandbox, where a server uses one built on Node's `vm`; the answer is the same: **Reuses runnable project: help-desk.** Initial call configuration: ```js { tool: "codecall:execute", arguments: { script: [ 'const { tickets } = await callTool("search_tickets", { status: "open" });', 'const urgent = tickets.filter((t) => t.priority === "high");', 'const out = [];', 'for (const t of urgent) {', ' const customer = await callTool("get_customer", { id: t.customerId });', ' out.push({ ticket: t.id, customer: customer.name });', '}', 'return out;', ].join("\n") } } ``` `codecall:execute` returns `{ "status": "ok", "result": [{ "ticket": "T-1", "customer": "Acme Corp" }, { "ticket": "T-3", "customer": "Globex" }] }`. ### [Letting the Model Write Code with CodeCall](https://frontmcp.dev/learn/letting-the-model-write-code-with-codecall) Learn what a long tool list costs a model, how to put your tools behind CodeCall and when it's worth it, how the model finds, reads and calls them, one at a time or from a script, what a script may do, and how to keep tools out of its reach. ## Wrapping an OpenAPI service When what the model needs already exists as a REST API with an OpenAPI description, `OpenapiAdapter` from `@frontmcp/adapters` makes a tool of each operation, named by its `operationId`, which sends the request the spec describes and hands back the API's answer. The Playground can't reach a real API, so `desk.example.ts` plays it, in-process: Initial call configuration: ```js { tool: "getTicket", arguments: { id: "T-1" } } ``` ```ts desk.app.ts active import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./spec"; @App({ id: "desk", name: "Desk", adapters: [OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec })], }) export class DeskApp {} ``` ```ts spec.ts export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, paths: { "/tickets": { get: { operationId: "listTickets", summary: "List support tickets, newest first", parameters: [{ name: "status", in: "query", schema: { type: "string", enum: ["open", "closed"] } }], responses: { "200": { description: "The tickets" } }, }, }, "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "The ticket" } }, }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. // It answers requests in-process and records them. Your server doesn't need it. export const received: string[] = []; const tickets: Record = { "T-1": { id: "T-1", title: "Cannot log in", status: "open" }, }; async function desk(request: Request): Promise { received.push(`${request.method} ${request.url}`); const path = new URL(request.url).pathname; if (path === "/v1/tickets") return Response.json(Object.values(tickets)); const ticket = tickets[path.replace("/v1/tickets/", "")]; return ticket ? Response.json(ticket) : Response.json({ message: "No such ticket" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input)); return url.hostname === "desk.example" ? desk(new Request(input, init)) : realFetch(input, init); }; ``` ```ts desk.test.ts import { test, expect } from "@frontmcp/testing"; import { received } from "./desk.example"; test("each operation is a tool named by its operationId", async ({ mcp }) => { expect((await mcp.tools.list()).map((t: { name: string }) => t.name).sort()).toEqual(["getTicket", "listTickets"]); }); test("a call sends the request, and returns the API's status and body", async ({ mcp }) => { const result = await mcp.tools.call("getTicket", { id: "T-1" }); expect(result.json()).toEqual({ status: 200, ok: true, data: { id: "T-1", title: "Cannot log in", status: "open" } }); expect(received.at(-1)).toBe("GET https://desk.example/v1/tickets/T-1"); }); test("an error from the API is an error the model can read", async ({ mcp }) => { const result = await mcp.tools.call("getTicket", { id: "T-9" }); expect(result).toBeError(); expect(result.text()).toContain("No such ticket"); }); ``` The model gets the API's answer as it is, and every operation in the spec as a tool, which is a lot of tools for a large API. The adapter's options choose which operations become tools, rename and describe them, send the API's credentials, and reshape what comes back. The adapter goes in an app's `adapters`, and each one needs a `name` of its own. ### [Wrapping an OpenAPI Service](https://frontmcp.dev/learn/wrapping-an-openapi-service) Learn how to turn an OpenAPI description into tools, what a call sends to the API and what the model gets back, how to give the adapter the API's credentials without the model seeing them, how to choose and name the operations the model sees, and what to do when an API is too big for one tool per operation. ## Plugin, adapter or your own code? | If you need… | Use | | --- | --- | | The same answer again, without the wait | The cache plugin, on tools that only read | | A value that outlasts one call | The Remember plugin, in the scope that matches who should read it | | A person's yes before a tool runs | The approval plugin, with a form only the user can answer | | A tool for some users, or one you can switch off | The feature flags plugin | | More tools than a model can usefully read | CodeCall | | An existing REST API as tools | The OpenAPI adapter, or a few tools with [`this.fetch()`](https://frontmcp.dev/learn/calling-other-services) when the model only needs a few well-shaped calls | | Something none of these do | [A plugin of your own](https://frontmcp.dev/learn/extending-with-plugins) | Every option of each one is in the [plugins and adapters reference](https://frontmcp.dev/reference/plugins). ## What's next? Start the chapter with [Caching Results](https://frontmcp.dev/learn/caching-results). After it, [Testing and Shipping](https://frontmcp.dev/learn/testing-and-shipping) covers proving your server works and getting it into production. --- # Caching Results > How to answer repeated calls to a slow FrontMCP tool from a cache with @frontmcp/plugin-cache, whose calls share an entry, what makes two calls the same, how long an entry lives, and what not to cache. Source: https://frontmcp.dev/learn/caching-results [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A model asks the same question more than once. It looks up the customer on a ticket, then again before it writes the reply, then again for the next ticket from the same customer. When the lookup waits on a slow CRM, every repeat makes the user wait again for an answer the model already had. FrontMCP's cache plugin, `@frontmcp/plugin-cache`, stores what a tool returns and answers the next call with the same arguments from the store, without running the tool. Turning it on is one line in the app and one field on the tool. Deciding what to cache, and for whom, is the rest of this lesson. **You will learn** - How to cache a tool's results with the cache plugin - Why the cache keeps each caller's answers apart, and when to share them - What makes two calls the same call - How long an entry lives, and why you can't clear one - What not to cache ## A lookup the model repeats `get_customer` asks the CRM for a customer's account. The CRM takes a fifth of a second to answer, and `crm.ts` counts the requests it gets. Open the **Tests** tab: Initial call configuration: ```js { tool: "get_customer", arguments: { id: "C-1" } } ``` ```ts get-customer.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { crm } from "./crm"; @Tool({ name: "get_customer", description: "Get a customer account by its id: the company's name and its plan.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true }, }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return crm.getCustomer(id); } } ``` ```ts crm.ts import { PublicMcpError } from "@frontmcp/sdk"; // Stands in for a CRM that is slow to answer, and counts the requests it gets. const customers: Record = { "C-1": { id: "C-1", name: "Acme Corp", plan: "enterprise" }, "C-2": { id: "C-2", name: "Globex", plan: "starter" }, }; export const crm = { requests: 0, async getCustomer(id: string) { crm.requests++; await new Promise((resolve) => setTimeout(resolve, 200)); const customer = customers[id]; if (!customer) throw new PublicMcpError(`There's no customer ${id}.`); return { ...customer }; }, }; ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { GetCustomer } from "./get-customer.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [GetCustomer] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts repeat.test.ts import { test, expect } from "@frontmcp/testing"; import { crm } from "./crm"; test("🚩 every call waits for the CRM again", async ({ mcp }) => { const before = crm.requests; for (let i = 0; i < 3; i++) { const result = await mcp.tools.call("get_customer", { id: "C-1" }); expect(result.json()).toEqual({ id: "C-1", name: "Acme Corp", plan: "enterprise" }); expect(result.durationMs).toBeGreaterThan(150); } expect(crm.requests - before).toBe(3); }); ``` Three calls, three requests to the CRM, three waits, for the same answer. A customer's name and plan don't change from one minute to the next, so the second and third calls could have been answered at once. ## Turning the cache on Install the plugin: ```bash npm install @frontmcp/plugin-cache ``` Then register it on the app with `CachePlugin.init({ type: "memory" })`, and mark each tool it should cache with `cache`. `ttl` is how long an answer is kept, in seconds: Initial call configuration: ```js { tool: "get_customer", arguments: { id: "C-1" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { GetCustomer } from "./get-customer.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [GetCustomer], plugins: [CachePlugin.init({ type: "memory" })], }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts get-customer.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { crm } from "./crm"; @Tool({ name: "get_customer", description: "Get a customer account by its id: the company's name and its plan.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true }, cache: { ttl: 300 }, // keep each answer for 5 minutes }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return crm.getCustomer(id); } } ``` ```ts crm.ts import { PublicMcpError } from "@frontmcp/sdk"; // Stands in for a CRM that is slow to answer, and counts the requests it gets. const customers: Record = { "C-1": { id: "C-1", name: "Acme Corp", plan: "enterprise" }, "C-2": { id: "C-2", name: "Globex", plan: "starter" }, }; export const crm = { requests: 0, async getCustomer(id: string) { crm.requests++; await new Promise((resolve) => setTimeout(resolve, 200)); const customer = customers[id]; if (!customer) throw new PublicMcpError(`There's no customer ${id}.`); return { ...customer }; }, }; ``` ```ts cache.test.ts import { test, expect } from "@frontmcp/testing"; import { crm } from "./crm"; test("🚩 an anonymous caller is never answered from the cache", async ({ mcp }) => { const before = crm.requests; await mcp.tools.call("get_customer", { id: "C-1" }); const second = await mcp.tools.call("get_customer", { id: "C-1" }); expect(crm.requests - before).toBe(2); expect(second.raw._meta?.cache).toBeUndefined(); }); ``` The cache is on, and the CRM still gets every request. Nothing is wrong with the setup. By default the cache keeps a separate entry for each caller, so that one user is never given an answer that was meant for another. The Playground's client doesn't sign in, and under MCP 2026-07-28 a caller without credentials is a [new anonymous caller](https://frontmcp.dev/learn/authenticating-clients#a-server-anyone-can-call) on every request. With no identity to key by, each call skips the cache: the plugin neither reads nor stores an entry. There's no error or warning. > **Note** > > Changed in 1.10.14: before, these calls stored entries that no later call could read. They now store nothing. The tool still runs on every call. ## Sharing answers between callers A customer's account looks the same to every support agent who asks, so there's no reason to keep one copy per caller. `keyByIdentity: false` makes every caller share one entry per tool and arguments: Initial call configuration: ```js { tool: "get_customer", arguments: { id: "C-1" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { GetCustomer } from "./get-customer.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [GetCustomer], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], // ✅ the same answer for everyone }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts get-customer.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { crm } from "./crm"; @Tool({ name: "get_customer", description: "Get a customer account by its id: the company's name and its plan.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true }, cache: { ttl: 300 }, }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return crm.getCustomer(id); } } ``` ```ts crm.ts import { PublicMcpError } from "@frontmcp/sdk"; // Stands in for a CRM that is slow to answer, and counts the requests it gets. const customers: Record = { "C-1": { id: "C-1", name: "Acme Corp", plan: "enterprise" }, "C-2": { id: "C-2", name: "Globex", plan: "starter" }, }; export const crm = { requests: 0, async getCustomer(id: string) { crm.requests++; await new Promise((resolve) => setTimeout(resolve, 200)); const customer = customers[id]; if (!customer) throw new PublicMcpError(`There's no customer ${id}.`); return { ...customer }; }, }; ``` ```ts cache.test.ts import { test, expect } from "@frontmcp/testing"; import { crm } from "./crm"; test("the second call is answered from the cache, at once", async ({ mcp }) => { const before = crm.requests; const first = await mcp.tools.call("get_customer", { id: "C-2" }); const second = await mcp.tools.call("get_customer", { id: "C-2" }); expect(crm.requests - before).toBe(1); expect(second.durationMs).toBeLessThan(150); expect(first.raw._meta?.cache).toBeUndefined(); expect(second.raw._meta?.cache).toBe("hit"); }); test("the data is what the tool returned, marker aside", async ({ mcp }) => { await mcp.tools.call("get_customer", { id: "C-1" }); const hit = await mcp.tools.call("get_customer", { id: "C-1" }); expect(hit.raw._meta?.cache).toBe("hit"); expect(hit.json()).toEqual({ id: "C-1", name: "Acme Corp", plan: "enterprise" }); }); test("a failed call isn't stored", async ({ mcp }) => { const before = crm.requests; expect(await mcp.tools.call("get_customer", { id: "C-9" })).toBeError(); expect(await mcp.tools.call("get_customer", { id: "C-9" })).toBeError(); expect(crm.requests - before).toBe(2); }); ``` Now the first call asks the CRM and the second is answered from the store, without running `execute()`. Every caller shares the entry, so one agent's lookup also saves the next agent's wait. - **A hit is marked, and its data isn't changed.** Its result carries `_meta.cache: "hit"`, next to the data the tool returned. The marker isn't in `structuredContent` or in the text the model reads ([What a cache hit looks like](https://frontmcp.dev/reference/plugins/cache#what-a-cache-hit-looks-like)). - **Only calls that succeed are stored.** A tool that throws stores nothing, so `C-9` is looked up again each time. - **The store is in memory.** `type: "memory"` keeps entries in the server's process: they're lost on restart and not shared between instances. With more than one instance, keep them in Redis instead ([Using Redis](https://frontmcp.dev/reference/plugins/cache#using-redis)). ## Answers that depend on who's asking Sharing is right for a customer's account. It's wrong for `my_open_tickets`, which lists the tickets assigned to the caller. A plugin applies to the tools of the app it's registered on, so tools that need different rules go in different apps, each with its own `CachePlugin.init()`. `my_open_tickets` keeps the default, one entry per caller. The Playground's client is anonymous, which would tell us nothing here, so the tests call the server in-process with [`createDirect()`](https://frontmcp.dev/learn/running-frontmcp-anywhere) as two signed-in support agents, `nour` and `sam`: Initial call configuration: ```js { tool: "get_customer", arguments: { id: "C-1" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { GetCustomer, MyOpenTickets } from "./tools"; @App({ id: "customers", name: "Customers", tools: [GetCustomer], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], // the same answer for everyone }) class CustomersApp {} @App({ id: "queue", name: "Queue", tools: [MyOpenTickets], plugins: [CachePlugin.init({ type: "memory" })], // ✅ one entry per caller }) class QueueApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [CustomersApp, QueueApp], }; @FrontMcp(config) export default class Server {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { crm, queue } from "./stores"; @Tool({ name: "get_customer", description: "Get a customer account by its id: the company's name and its plan.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true }, cache: { ttl: 300 }, }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return crm.getCustomer(id); } } @Tool({ name: "my_open_tickets", description: "The open support tickets assigned to you.", inputSchema: {}, annotations: { readOnlyHint: true }, cache: { ttl: 60 }, }) export class MyOpenTickets extends ToolContext { async execute() { const agent = this.auth.user.sub; return { agent, tickets: await queue.openTicketsFor(agent) }; } } ``` ```ts stores.ts import { PublicMcpError } from "@frontmcp/sdk"; // Stand in for the CRM and the ticket database, and count the requests they get. const customers: Record = { "C-1": { id: "C-1", name: "Acme Corp", plan: "enterprise" }, "C-2": { id: "C-2", name: "Globex", plan: "starter" }, }; export const crm = { requests: 0, async getCustomer(id: string) { crm.requests++; await new Promise((resolve) => setTimeout(resolve, 200)); const customer = customers[id]; if (!customer) throw new PublicMcpError(`There's no customer ${id}.`); return { ...customer }; }, }; const assigned: Record = { nour: ["T-1", "T-3"], sam: ["T-2"] }; export const queue = { searches: 0, async openTicketsFor(agent: string) { queue.searches++; return assigned[agent] ?? []; }, }; ``` ```ts per-caller.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { config } from "./main"; import { queue } from "./stores"; import { MyOpenTickets } from "./tools"; const nour = { authContext: { user: { sub: "nour" } } }; const sam = { authContext: { user: { sub: "sam" } } }; test("each agent gets their own tickets, and their repeats from the cache", async () => { const server = await FrontMcpInstance.createDirect(config); const before = queue.searches; expect((await server.callTool("my_open_tickets", {}, nour)).structuredContent).toEqual({ agent: "nour", tickets: ["T-1", "T-3"] }); expect((await server.callTool("my_open_tickets", {}, sam)).structuredContent).toEqual({ agent: "sam", tickets: ["T-2"] }); const again = await server.callTool("my_open_tickets", {}, nour); expect(again._meta?.cache).toBe("hit"); expect(queue.searches - before).toBe(2); // Nour's second call didn't search await server.dispose(); }); test("🚩 with keyByIdentity: false, Sam is given Nour's tickets", async () => { @App({ id: "queue", name: "Queue", tools: [MyOpenTickets], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })] }) class SharedQueueApp {} const server = await FrontMcpInstance.createDirect({ ...config, apps: [SharedQueueApp] }); await server.callTool("my_open_tickets", {}, nour); const forSam = await server.callTool("my_open_tickets", {}, sam); expect(forSam._meta?.cache).toBe("hit"); expect(forSam.structuredContent).toMatchObject({ agent: "nour", tickets: ["T-1", "T-3"] }); await server.dispose(); }); ``` Each agent's first call searches, and their repeat is answered from their own entry. With the whole app on `keyByIdentity: false`, the second test shows what goes wrong: Sam asks for his tickets and gets Nour's, marked as a cache hit. With `keyByIdentity` on, the cache tells callers apart by what [authentication](https://frontmcp.dev/learn/authenticating-clients) established: | Caller | Entries | | --- | --- | | Signed in through an identity provider (`transparent`, `local` or `remote`) | One set per user, by the token's `sub`, shared by all of that user's sessions and devices | | A `static` key | One set per key | | Anonymous, under MCP 2026-07-28 | None: skips cache reads and writes | | Anonymous, on a session-based client (before 2026-07-28) | One set per session the server verified, keyed by its session id | > **Pitfall: keyByIdentity: false gives one caller's answer to everyone** > > With `keyByIdentity: false`, the first caller's result is served to every later caller with the same arguments until it expires. If a tool reads `this.auth`, or its answer depends on the caller's tenant, account or permissions, the next caller gets the first caller's data. Share only answers that are the same for everyone, and put those tools in an app of their own. ## What makes two calls the same The cache looks an answer up by a key made of three things: the caller (unless `keyByIdentity` is `false`), the tool as `:`, and the call's arguments **after** the input schema has validated them. That last part decides how often a model's calls hit. `search_articles` searches the help center, whose articles are the same for everyone: Initial call configuration: ```js { tool: "search_articles", arguments: { query: "password reset" } } ``` ```ts search-articles.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { helpCenter } from "./help-center"; @Tool({ name: "search_articles", description: "Search the help center's articles. Returns the best matches, most relevant first.", inputSchema: { query: z.string().trim().toLowerCase().describe("What to search for, like 'password reset'"), limit: z.number().int().min(1).max(10).default(5).describe("How many articles to return"), }, annotations: { readOnlyHint: true }, cache: { ttl: 600 }, }) export class SearchArticles extends ToolContext { async execute({ query, limit }: { query: string; limit: number }) { return { articles: await helpCenter.search(query, limit) }; } } ``` ```ts help-center.ts // Stands in for the help center's search, and counts the searches it runs. const articles = [ { slug: "reset-your-password", title: "Reset your password" }, { slug: "password-rules", title: "Password rules for your team" }, { slug: "export-tickets", title: "Export tickets as CSV" }, ]; export const helpCenter = { searches: 0, async search(query: string, limit: number) { helpCenter.searches++; const words = query.split(/\s+/); return articles.filter((a) => words.some((w) => a.title.toLowerCase().includes(w))).slice(0, limit); }, }; ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { SearchArticles } from "./search-articles.tool"; @App({ id: "help-center", name: "Help Center", tools: [SearchArticles], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], }) class HelpCenterApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpCenterApp], }) export default class Server {} ``` ```ts key.test.ts import { test, expect } from "@frontmcp/testing"; import { helpCenter } from "./help-center"; /** How many of these calls reached the help center. */ async function searchesFor(mcp: any, ...calls: object[]) { const before = helpCenter.searches; for (const args of calls) await mcp.tools.call("search_articles", args); return helpCenter.searches - before; } test("the order of the arguments doesn't matter", async ({ mcp }) => { expect(await searchesFor(mcp, { query: "export", limit: 3 }, { limit: 3, query: "export" })).toBe(1); }); test("the schema's transforms run first", async ({ mcp }) => { expect(await searchesFor(mcp, { query: "rules" }, { query: " Rules " }, { query: "RULES" })).toBe(1); }); test("a default counts as if the model had sent it", async ({ mcp }) => { expect(await searchesFor(mcp, { query: "team" }, { query: "team", limit: 5 })).toBe(1); }); test("arguments the schema doesn't declare don't count", async ({ mcp }) => { expect(await searchesFor(mcp, { query: "csv" }, { query: "csv", locale: "fr" })).toBe(1); }); test("any other value is another entry", async ({ mcp }) => { expect(await searchesFor(mcp, { query: "password", limit: 1 }, { query: "password", limit: 2 })).toBe(2); }); ``` The key is built from what `execute()` receives, not from what the model sent. Object keys are sorted, arguments the schema doesn't declare are dropped, defaults are filled in, and transforms like `trim()` and `toLowerCase()` have already run. So a schema that normalizes its input also makes the cache hit more often: `" Rules "` and `"RULES"` are the same search as `"rules"`. Anything left that differs, even `limit: 1` against `limit: 2`, is another entry. ## How long an entry lives An entry lives for its `ttl`, and then the next call runs the tool again. The plugin has no way to delete an entry sooner. Here `update_plan` changes a customer's plan in the CRM, and `get_customer` keeps giving the old one. The tests move the clock forward by replacing `Date.now()`, which is what the cache's memory store reads: Initial call configuration: ```js { tool: "get_customer", arguments: { id: "C-2" } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { crm } from "./crm"; @Tool({ name: "get_customer", description: "Get a customer account by its id: the company's name and its plan. May be up to 5 minutes old.", inputSchema: { id: z.string().describe("Customer id, like C-1") }, annotations: { readOnlyHint: true }, cache: { ttl: 300 }, }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return crm.getCustomer(id); } } @Tool({ name: "update_plan", description: "Change a customer's plan.", inputSchema: { id: z.string(), plan: z.enum(["starter", "business", "enterprise"]) }, }) export class UpdatePlan extends ToolContext { async execute({ id, plan }: { id: string; plan: "starter" | "business" | "enterprise" }) { return crm.setPlan(id, plan); } } @Tool({ name: "get_sla_policy", description: "The help desk's response times for each plan.", inputSchema: {}, annotations: { readOnlyHint: true }, cache: true, // 🚩 kept for a day: the plugin's defaultTTL }) export class GetSlaPolicy extends ToolContext { async execute() { crm.requests++; return { starter: "2 days", business: "8 hours", enterprise: "1 hour" }; } } ``` ```ts crm.ts import { PublicMcpError } from "@frontmcp/sdk"; // Stands in for a CRM that is slow to answer, and counts the requests it gets. const customers: Record = { "C-1": { id: "C-1", name: "Acme Corp", plan: "enterprise" }, "C-2": { id: "C-2", name: "Globex", plan: "starter" }, }; export const crm = { requests: 0, async getCustomer(id: string) { crm.requests++; await new Promise((resolve) => setTimeout(resolve, 200)); const customer = customers[id]; if (!customer) throw new PublicMcpError(`There's no customer ${id}.`); return { ...customer }; }, async setPlan(id: string, plan: string) { const customer = customers[id]; if (!customer) throw new PublicMcpError(`There's no customer ${id}.`); customer.plan = plan; return { ...customer }; }, }; ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { GetCustomer, GetSlaPolicy, UpdatePlan } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetCustomer, UpdatePlan, GetSlaPolicy], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts ttl.test.ts import { test, expect } from "@frontmcp/testing"; import { crm } from "./crm"; /** Runs `fn` with the clock `seconds` ahead. */ async function inSeconds(seconds: number, fn: () => Promise) { const realNow = Date.now; const now = realNow(); Date.now = () => now + seconds * 1000; try { return await fn(); } finally { Date.now = realNow; } } test("🚩 a change doesn't reach the cached answer", async ({ mcp }) => { await mcp.tools.call("get_customer", { id: "C-2" }); // stored: starter await mcp.tools.call("update_plan", { id: "C-2", plan: "business" }); const cached = await mcp.tools.call("get_customer", { id: "C-2" }); expect(cached.raw._meta?.cache).toBe("hit"); expect(cached.json().plan).toBe("starter"); }); test("once the ttl has passed, the tool runs again", async ({ mcp }) => { const fresh = await inSeconds(301, () => mcp.tools.call("get_customer", { id: "C-2" })); expect(fresh.raw._meta?.cache).toBeUndefined(); expect(fresh.json().plan).toBe("business"); }); test("cache: true keeps the first answer for a day, however often it's read", async ({ mcp }) => { const before = crm.requests; const day = 24 * 60 * 60; await mcp.tools.call("get_sla_policy", {}); const lastMinute = await inSeconds(day - 60, () => mcp.tools.call("get_sla_policy", {})); expect(lastMinute.raw._meta?.cache).toBe("hit"); const nextDay = await inSeconds(day + 60, () => mcp.tools.call("get_sla_policy", {})); expect(nextDay.raw._meta?.cache).toBeUndefined(); expect(crm.requests - before).toBe(2); }); ``` The model changed the plan, and the next lookup still says `starter`: the model is told two different things in a row. A client can skip the cache for one call by sending the header `x-frontmcp-disable-cache: true`, but that call's fresh answer isn't stored, and the old entry stays for everyone else ([Letting a client skip the cache](https://frontmcp.dev/reference/plugins/cache#letting-a-client-skip-the-cache)). Short of restarting a server whose store is in memory, which empties it, nothing clears an entry early. So choose `ttl` as the oldest answer you're willing to give: - **Say it in the description.** "May be up to 5 minutes old" lets the model tell the user, or tell them a change can take a few minutes to show. - **Keep it short, or don't cache, for data your own tools change.** If `update_plan` is used often, a five-minute-old plan will confuse the model more than a slow lookup. - **Give every cached tool an explicit `ttl`.** `cache: true` uses the plugin's `defaultTTL`, a day unless you set it, so a change can take a day to reach the model. The last test shows `get_sla_policy` answering from its first call until the day is over, however often it's read. (Before FrontMCP 1.9, each read gave the entry a full day again, so an answer read daily was never refreshed. Reading an entry now keeps it alive only with `slideWindow: true`: see [the reference](https://frontmcp.dev/reference/plugins/cache#cache-in-tool).) ## What not to cache A cached call doesn't run `execute()`. For a tool that only reads, that's the point. For a tool that does something, it means the second call doesn't do it: Initial call configuration: ```js { tool: "add_note", arguments: { ticketId: "T-1", text: "Called the customer back." } } ``` ```ts add-note.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; export const notes: string[] = []; @Tool({ name: "add_note", description: "Add an internal note to a support ticket.", inputSchema: { ticketId: z.string(), text: z.string() }, cache: { ttl: 300 }, // 🚩 on a tool that changes something }) export class AddNote extends ToolContext { async execute({ ticketId, text }: { ticketId: string; text: string }) { notes.push(`${ticketId}: ${text}`); return { ticketId, added: true }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { AddNote } from "./add-note.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [AddNote], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts notes.test.ts import { test, expect } from "@frontmcp/testing"; import { notes } from "./add-note.tool"; test("🚩 the second note is never added, and the model is told it was", async ({ mcp }) => { const before = notes.length; const args = { ticketId: "T-2", text: "Customer tried again, still failing." }; await mcp.tools.call("add_note", args); const second = await mcp.tools.call("add_note", args); expect(second.json()).toMatchObject({ ticketId: "T-2", added: true }); expect(notes.length - before).toBe(1); }); ``` An agent really may add the same note twice, after the customer writes in again. The second call answers "added" from the cache, and nothing is added. Leave these out of the cache: | Don't cache | Because | | --- | --- | | Tools that change something: `add_note`, `close_ticket`, `refund_invoice` | A hit skips the change and reports success. Cache only tools that just read, the ones you'd mark `readOnlyHint: true`. | | Answers that depend on the caller, in an app with `keyByIdentity: false` | The first caller's answer goes to everyone. Keep them per caller, behind authentication. | | Answers the model acts on right away | A ticket's status just before closing it, a balance just before refunding it: a few minutes old can be wrong. | ## Recap - `@frontmcp/plugin-cache` answers a repeated call from a store without running `execute()`. Register `CachePlugin.init({ type: "memory" })` on the app, and mark each tool with `cache: { ttl }`, in seconds. - By default, each caller has their own entries. Anonymous callers under MCP 2026-07-28 skip cache reads and writes, so their tools run every time. - `keyByIdentity: false` shares entries between callers. Use it only for answers that are the same for everyone, in an app of their own; a plugin covers the tools of the app it's registered on. - Two calls are the same when the tool and the validated arguments match: key order, undeclared arguments and defaults don't matter, and the schema's transforms have run. - An entry lives until its `ttl` ends, and the plugin can't clear it sooner. Choose `ttl` as the oldest answer you'll accept, and say so in the description. - Cache only tools that read. Failed calls aren't stored, whether the tool throws or returns an error result. - Every option, the Redis stores and the bypass header are in the [Cache plugin reference](https://frontmcp.dev/reference/plugins/cache). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Cache the article lookup `get_article` reads an article from the help center, which is slow, and the model reads the same few articles over and over. Answer repeated lookups from a cache for 10 minutes. Articles are the same for everyone who asks. Initial call configuration: ```js { tool: "get_article", arguments: { slug: "reset-your-password" } } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; import { helpCenter } from "./help-center"; @Tool({ name: "get_article", description: "Read a help center article by its slug.", inputSchema: { slug: z.string().describe("The article's slug, like reset-your-password") }, annotations: { readOnlyHint: true }, }) class GetArticle extends ToolContext { async execute({ slug }: { slug: string }) { return helpCenter.getArticle(slug); } } @App({ id: "help-center", name: "Help Center", tools: [GetArticle] }) class HelpCenterApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpCenterApp], }) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { helpCenter } from "./help-center"; @Tool({ name: "get_article", description: "Read a help center article by its slug. May be up to 10 minutes old.", inputSchema: { slug: z.string().describe("The article's slug, like reset-your-password") }, annotations: { readOnlyHint: true }, cache: { ttl: 600 }, }) class GetArticle extends ToolContext { async execute({ slug }: { slug: string }) { return helpCenter.getArticle(slug); } } @App({ id: "help-center", name: "Help Center", tools: [GetArticle], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], }) class HelpCenterApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpCenterApp], }) export default class Server {} ``` ```ts help-center.ts import { PublicMcpError } from "@frontmcp/sdk"; // Stands in for a slow help center, and counts the requests it gets. const articles: Record = { "reset-your-password": { slug: "reset-your-password", title: "Reset your password", body: "Open the sign-in page and choose Forgot password." }, "export-tickets": { slug: "export-tickets", title: "Export tickets as CSV", body: "Open Reports, then choose Export." }, }; export const helpCenter = { requests: 0, async getArticle(slug: string) { helpCenter.requests++; await new Promise((resolve) => setTimeout(resolve, 200)); const article = articles[slug]; if (!article) throw new PublicMcpError(`There's no article ${slug}.`); return { ...article }; }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts article.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { helpCenter } from "./help-center"; test("a repeated lookup doesn't reach the help center", async ({ mcp }) => { const before = helpCenter.requests; const first = await mcp.tools.call("get_article", { slug: "export-tickets" }); const second = await mcp.tools.call("get_article", { slug: "export-tickets" }); expect(second.json().title).toBe(first.json().title); expect(helpCenter.requests - before).toBe(1); }); test("the repeat is marked as a cache hit", async ({ mcp }) => { await mcp.tools.call("get_article", { slug: "reset-your-password" }); const second = await mcp.tools.call("get_article", { slug: "reset-your-password" }); expect(second.raw._meta?.cache).toBe("hit"); }); test("each article is looked up for itself", async ({ mcp }) => { expect((await mcp.tools.call("get_article", { slug: "export-tickets" })).json().title).toBe("Export tickets as CSV"); expect((await mcp.tools.call("get_article", { slug: "reset-your-password" })).json().title).toBe("Reset your password"); }); test("a missing article is still an error", async ({ mcp }) => { expect(await mcp.tools.call("get_article", { slug: "no-such-article" })).toBeError(); }); ``` **Hint:** It takes a change to the app and one to the tool. Then think about who the Playground's caller is: the checks call the tool the way the Playground does, without signing in. **Solution:** `CachePlugin.init({ type: "memory", keyByIdentity: false })` on the app and `cache: { ttl: 600 }` on the tool turn the cache on for `get_article`. `keyByIdentity: false` is what makes it work for the Playground's caller: with the default, each anonymous request skips cache reads and writes. Sharing is safe because an article doesn't depend on who reads it. The missing article throws, so it isn't stored, and the description now says how old an article may be. ### Challenge: Keep each agent's queue their own The help desk caches everything in one app with `keyByIdentity: false`. That's right for `get_article`, and wrong for `my_open_tickets`: Sam gets whichever agent's tickets were cached first. Keep each agent's tickets their own, still answered from the cache when an agent asks again, and keep articles shared. Initial call configuration: ```js { tool: "get_article", arguments: { slug: "export-tickets" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { GetArticle, MyOpenTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetArticle, MyOpenTickets], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }; @FrontMcp(config) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { GetArticle, MyOpenTickets } from "./tools"; @App({ id: "help-center", name: "Help Center", tools: [GetArticle], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], // the same for everyone }) class HelpCenterApp {} @App({ id: "queue", name: "Queue", tools: [MyOpenTickets], plugins: [CachePlugin.init({ type: "memory" })], // one entry per caller }) class QueueApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpCenterApp, QueueApp], }; @FrontMcp(config) export default class Server {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; export const counts = { articleReads: 0, ticketSearches: 0 }; const assigned: Record = { nour: ["T-1", "T-3"], sam: ["T-2"] }; @Tool({ name: "get_article", description: "Read a help center article by its slug.", inputSchema: { slug: z.string() }, annotations: { readOnlyHint: true }, cache: { ttl: 600 }, }) export class GetArticle extends ToolContext { async execute({ slug }: { slug: string }) { counts.articleReads++; return { slug, title: slug === "export-tickets" ? "Export tickets as CSV" : "Reset your password" }; } } @Tool({ name: "my_open_tickets", description: "The open support tickets assigned to you.", inputSchema: {}, annotations: { readOnlyHint: true }, cache: { ttl: 60 }, }) export class MyOpenTickets extends ToolContext { async execute() { counts.ticketSearches++; const agent = this.auth.user.sub; return { agent, tickets: assigned[agent] ?? [] }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts queue.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; import { counts } from "./tools"; const nour = { authContext: { user: { sub: "nour" } } }; const sam = { authContext: { user: { sub: "sam" } } }; test("each agent gets their own open tickets", async () => { const server = await FrontMcpInstance.createDirect(config); expect((await server.callTool("my_open_tickets", {}, nour)).structuredContent).toEqual({ agent: "nour", tickets: ["T-1", "T-3"] }); expect((await server.callTool("my_open_tickets", {}, sam)).structuredContent).toEqual({ agent: "sam", tickets: ["T-2"] }); await server.dispose(); }); test("an agent's repeat is answered from the cache", async () => { const server = await FrontMcpInstance.createDirect(config); await server.callTool("my_open_tickets", {}, sam); const before = counts.ticketSearches; const again = await server.callTool("my_open_tickets", {}, sam); expect(again._meta?.cache).toBe("hit"); expect(counts.ticketSearches).toBe(before); await server.dispose(); }); test("articles are still shared between callers", async ({ mcp }) => { await mcp.tools.call("get_article", { slug: "reset-your-password" }); const before = counts.articleReads; const second = await mcp.tools.call("get_article", { slug: "reset-your-password" }); expect(second.raw._meta?.cache).toBe("hit"); expect(counts.articleReads).toBe(before); }); ``` **Hint:** `keyByIdentity` is an option of the plugin, not of a tool, and a plugin registered on an app applies to that app's tools only. **Solution:** `get_article` and `my_open_tickets` need different rules, so they go in different apps, each with its own `CachePlugin.init()`: the help center app shares its entries with `keyByIdentity: false`, and the queue app keeps the default, one entry per caller. The checks call `my_open_tickets` as `nour` and `sam`, who each get their own tickets, and whose repeats are still hits. Removing `cache` from `my_open_tickets` would also keep the tickets apart, but every call would search again. ### Challenge: Refresh the SLA policy every hour `get_sla_policy` is cached with `cache: true`, so a change to the help desk's response times can take a day to reach the model. Make the policy at most an hour old, and keep answering repeats within the hour from the cache. Initial call configuration: ```js { tool: "get_sla_policy", arguments: {} } ``` ```ts get-sla-policy.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; import { policies } from "./policies"; @Tool({ name: "get_sla_policy", description: "The help desk's response times for each plan.", inputSchema: {}, annotations: { readOnlyHint: true }, cache: true, }) export class GetSlaPolicy extends ToolContext { async execute() { return policies.read(); } } ``` **Solution file (alternative to the starter):** ```ts get-sla-policy.tool.ts solution import { Tool, ToolContext } from "@frontmcp/sdk"; import { policies } from "./policies"; @Tool({ name: "get_sla_policy", description: "The help desk's response times for each plan. May be up to an hour old.", inputSchema: {}, annotations: { readOnlyHint: true }, cache: { ttl: 3600 }, }) export class GetSlaPolicy extends ToolContext { async execute() { return policies.read(); } } ``` ```ts policies.ts // Stands in for the help desk's settings, and counts the reads. export const policies = { reads: 0, current: { starter: "2 days", business: "8 hours", enterprise: "1 hour" }, async read() { policies.reads++; return { ...policies.current }; }, }; ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { GetSlaPolicy } from "./get-sla-policy.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [GetSlaPolicy], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], }) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts freshness.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { policies } from "./policies"; async function inSeconds(seconds: number, fn: () => Promise) { const realNow = Date.now; const now = realNow(); Date.now = () => now + seconds * 1000; try { return await fn(); } finally { Date.now = realNow; } } test("a repeat within the hour is answered from the cache", async ({ mcp }) => { await mcp.tools.call("get_sla_policy", {}); const before = policies.reads; const again = await inSeconds(30 * 60, () => mcp.tools.call("get_sla_policy", {})); expect(again.raw._meta?.cache).toBe("hit"); expect(policies.reads).toBe(before); }); test("a change reaches the model within the hour", async ({ mcp }) => { await mcp.tools.call("get_sla_policy", {}); policies.current = { ...policies.current, business: "4 hours" }; const later = await inSeconds(60 * 60 + 60, () => mcp.tools.call("get_sla_policy", {})); expect(later.json().business).toBe("4 hours"); }); ``` **Hint:** `cache: true` takes the plugin's `defaultTTL`, which is a day unless you set it. A tool can say how long its own entries live. **Solution:** `cache: { ttl: 3600 }` keeps each answer for an hour from the call that stored it, however often it's read in between, so the change reaches the model on the first call after the hour. The description says so, which lets the model tell the user that a change can take an hour to show. Setting `defaultTTL: 3600` on the plugin passes the checks too, but changes every `cache: true` tool in the app. --- # Remembering Across Calls > Keep values between FrontMCP tool calls with @frontmcp/plugin-remember and this.remember: scopes, signed-in and anonymous callers, expiry, and memory tools. Source: https://frontmcp.dev/learn/remembering-across-calls [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A tool forgets everything when its call ends. A support agent tells the assistant to sign replies "Nour, Tier 2 support", and on the next call the signature is gone. A variable at the top of the file remembers it, but for every caller at once, and only until the server restarts. The Remember plugin, `@frontmcp/plugin-remember`, gives every FrontMCP tool `this.remember`, a small key-value memory. Each value is stored in a **scope**, which decides who can read it back. Under MCP 2026-07-28, what a scope keeps depends on whether the caller signed in, so this lesson spends as much time on *who* as on *what*. **You will learn** - How to store and read values with `this.remember` - Which scope to put a value in, and who can read it back - What lasts for a signed-in caller, and what an anonymous caller keeps, under MCP 2026-07-28 - How to make a value expire, and how to forget it - How to let the model remember things itself, and limit what it can store ## A preference in a module variable `set_signature` saves the signature an agent's replies end with, and `draft_reply` signs a reply with it. The signature lives in a variable at the top of the file. To see whose signature ends up where, the tests need two callers who are signed in. The Playground's own client never signs in, so `server.ts` gives two support agents, Nour and Sam, a [static key](https://frontmcp.dev/learn/authenticating-clients#requiring-a-shared-key-static-mode) each, and `callAs()` in `call-as.ts` sends a tool call with a key, the way an MCP 2026-07-28 client would. Every call goes to the same server. Open the **Tests** tab: Initial call configuration: ```js { tool: "draft_reply", arguments: { ticketId: "T-1", text: "You can log in again." } } ``` ```ts signature.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; // 🚩 One signature for the whole server let signature = "The Help Desk"; @Tool({ name: "set_signature", description: "Set the signature your replies end with.", inputSchema: { signature: z.string().max(80) }, }) export class SetSignature extends ToolContext { async execute(input: { signature: string }) { signature = input.signature; return { signature }; } } @Tool({ name: "draft_reply", description: "Draft a reply to a support ticket, signed with your signature.", inputSchema: { ticketId: z.string(), text: z.string() }, }) export class DraftReply extends ToolContext { async execute({ ticketId, text }: { ticketId: string; text: string }) { return { ticketId, reply: `${text}\n\n${signature}` }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetSignature, DraftReply] }) export class HelpDeskApp {} ``` ```ts server.ts import { HelpDeskApp } from "./signature.app"; // Two support agents, each with a key of their own. // In your project: @FrontMcp(config) export default class Server {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; let server: ReturnType | undefined; /** Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. */ export async function callAs(key: string, tool: string, args: Record = {}) { server ??= FrontMcpInstance.createFetchHandler(config); const response = await (await server)( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result; } ``` ```ts signature.test.ts import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; const SAM = "agent-sam-key"; test("the signature is there on the next call", async () => { await callAs(NOUR, "set_signature", { signature: "Nour, Tier 2 support" }); const draft = await callAs(NOUR, "draft_reply", { ticketId: "T-1", text: "You can log in again." }); expect(draft.structuredContent.reply).toBe("You can log in again.\n\nNour, Tier 2 support"); }); test("🚩 Sam's replies are signed with Nour's signature", async () => { await callAs(NOUR, "set_signature", { signature: "Nour, Tier 2 support" }); const draft = await callAs(SAM, "draft_reply", { ticketId: "T-2", text: "Your invoice is fixed." }); expect(draft.structuredContent.reply).toContain("Nour, Tier 2 support"); }); ``` The variable remembers, and that's the trouble: it belongs to the file, so every caller shares it. When Nour sets her signature, Sam's replies are signed with it too. It's also lost when the server restarts, and each instance of the server has its own. [Sharing State with Providers](https://frontmcp.dev/learn/sharing-state-with-providers#state-in-a-module-variable) covers what else goes wrong with module variables. What this tool needs is a place that keeps a value for one agent, across calls. ## Giving tools a memory Install the plugin: ```bash npm install @frontmcp/plugin-remember ``` Register it on the app with `RememberPlugin.init({ type: "memory" })`. Every tool then has `this.remember`. `set(key, value, { scope })` stores a value, and `get(key, { scope, defaultValue })` reads it back. `scope: "user"` keeps a value for the caller: Initial call configuration: ```js { tool: "draft_reply", arguments: { ticketId: "T-1", text: "You can log in again." } } ``` ```ts signature.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @Tool({ name: "set_signature", description: "Set the signature your replies end with.", inputSchema: { signature: z.string().max(80) }, }) export class SetSignature extends ToolContext { async execute({ signature }: { signature: string }) { await this.remember.set("signature", signature, { scope: "user" }); // ✅ this caller's return { signature }; } } @Tool({ name: "draft_reply", description: "Draft a reply to a support ticket, signed with your signature.", inputSchema: { ticketId: z.string(), text: z.string() }, }) export class DraftReply extends ToolContext { async execute({ ticketId, text }: { ticketId: string; text: string }) { const signature = await this.remember.get("signature", { scope: "user", defaultValue: "The Help Desk" }); return { ticketId, reply: `${text}\n\n${signature}` }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetSignature, DraftReply], plugins: [RememberPlugin.init({ type: "memory" })], }) export class HelpDeskApp {} ``` ```ts server.ts import { HelpDeskApp } from "./signature.app"; // Two support agents, each with a key of their own. // In your project: @FrontMcp(config) export default class Server {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; let server: ReturnType | undefined; /** Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. */ export async function callAs(key: string, tool: string, args: Record = {}) { server ??= FrontMcpInstance.createFetchHandler(config); const response = await (await server)( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result; } ``` ```ts signature.test.ts import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; const SAM = "agent-sam-key"; test("each agent's signature is their own", async () => { await callAs(NOUR, "set_signature", { signature: "Nour, Tier 2 support" }); const nours = await callAs(NOUR, "draft_reply", { ticketId: "T-1", text: "You can log in again." }); const sams = await callAs(SAM, "draft_reply", { ticketId: "T-2", text: "Your invoice is fixed." }); expect(nours.structuredContent.reply).toBe("You can log in again.\n\nNour, Tier 2 support"); expect(sams.structuredContent.reply).toBe("Your invoice is fixed.\n\nThe Help Desk"); }); test("setting Sam's doesn't change Nour's", async () => { await callAs(SAM, "set_signature", { signature: "Sam, Billing" }); const nours = await callAs(NOUR, "draft_reply", { ticketId: "T-1", text: "Done." }); expect(nours.structuredContent.reply).toBe("Done.\n\nNour, Tier 2 support"); }); test("an anonymous caller can't keep a signature", async ({ mcp }) => { // The Playground's own server, whose callers don't sign in const result = await mcp.tools.call("set_signature", { signature: "Someone" }); expect(result).toBeError("REMEMBER_IDENTITY_REQUIRED"); expect(result.text()).toContain("Remember cannot use user scope without an authenticated user"); }); ``` Now Nour's signature is Nour's, Sam gets the default until he sets his own, and each is there on the agent's next request. The last test calls the Playground's own server, whose client doesn't sign in: `user` scope refuses it, and so does the call in the Call tab. `user` scope keeps values for `this.remember.userId`, the caller the server worked out from the request: - **A signed-in user**, with a token from an identity provider, is the token's `sub`. Their values follow them across sessions, conversations and clients. - **A static key** is `static:` and a hash of the key. Everyone who uses the key shares its values. - **An anonymous caller** has no identity to keep values under: under MCP 2026-07-28 it's a new `anon:` id on every request, and `user` scope refuses it. `this.remember` throws a `RememberIdentityError`, which reaches the client as its message, with the code `REMEMBER_IDENTITY_REQUIRED`. So a memory that belongs to a person needs the person to sign in. [Authenticating Clients](https://frontmcp.dev/learn/authenticating-clients) covers how. > **Note** > > Changed in 1.8.6: `user` scope used to accept an anonymous caller. Its `anon:` id is new on every request, so `set()` stored the value where nothing looks again, and `get()` found nothing, without an error. Now it's refused, like `session` scope. > **Note** > > `RememberPlugin.init()` with no argument, or `plugins: [RememberPlugin]` without `init()`, keeps values in memory. (Before FrontMCP 1.9.4, the class without `init()` left tools without `this.remember`.) Registered on one app, the plugin gives `this.remember` to that app's tools only: register it on `@FrontMcp` for every app. (Before FrontMCP 1.9, it reached every app's tools, which read and wrote the same values: [Caveats](https://frontmcp.dev/reference/plugins/remember#caveats).) ## Choosing a scope Every `this.remember` method takes a `scope`, and without one it's `"session"`. Under MCP 2026-07-28, where a client sends each request on its own and there are no sessions, the four scopes keep: | Scope | A value belongs to | Signed-in caller | Anonymous caller | | --- | --- | --- | --- | | `user` | The caller | Kept, across requests | Refused | | `session` (the default) | The caller, apart from their `user` values | Kept, across requests | Refused | | `tool` | The caller, and the tool that stored it | Kept, across requests, for that tool only | Refused | | `global` | Everyone | Kept, and shared | Kept, and shared | A session-based client, on a protocol version before 2026-07-28, keeps `session` and `tool` values for its session instead ([Scopes](https://frontmcp.dev/reference/plugins/remember#scopes)). This help desk uses `global` for a banner every caller sees during an outage, and `session` for the ticket an agent is working on: Initial call configuration: ```js { tool: "get_banner", arguments: {} } ``` ```ts desk.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @Tool({ name: "set_banner", description: "Show a banner to everyone, like an outage notice.", inputSchema: { text: z.string() } }) export class SetBanner extends ToolContext { async execute({ text }: { text: string }) { await this.remember.set("banner", text, { scope: "global" }); return { banner: text }; } } @Tool({ name: "get_banner", description: "The banner everyone sees, if there is one.", inputSchema: {} }) export class GetBanner extends ToolContext { async execute() { return { banner: await this.remember.get("banner", { scope: "global", defaultValue: null }) }; } } @Tool({ name: "work_on", description: "Mark a ticket as the one you're working on.", inputSchema: { ticketId: z.string() } }) export class WorkOn extends ToolContext { async execute({ ticketId }: { ticketId: string }) { await this.remember.set("ticket", ticketId); // session scope, the default return { ticketId }; } } @Tool({ name: "current_ticket", description: "The ticket you're working on.", inputSchema: {} }) export class CurrentTicket extends ToolContext { async execute() { return { ticketId: await this.remember.get("ticket", { defaultValue: null }) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetBanner, GetBanner, WorkOn, CurrentTicket], plugins: [RememberPlugin.init({ type: "memory" })], }) export class HelpDeskApp {} ``` ```ts server.ts import { HelpDeskApp } from "./desk.app"; // Two support agents, each with a key of their own. // In your project: @FrontMcp(config) export default class Server {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; let server: ReturnType | undefined; /** Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. */ export async function callAs(key: string, tool: string, args: Record = {}) { server ??= FrontMcpInstance.createFetchHandler(config); const response = await (await server)( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result; } ``` ```ts scopes.test.ts import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; const SAM = "agent-sam-key"; test("global: every signed-in agent reads the banner", async () => { await callAs(NOUR, "set_banner", { text: "Login is down. We're on it." }); expect((await callAs(SAM, "get_banner")).structuredContent).toEqual({ banner: "Login is down. We're on it." }); }); test("global: an anonymous caller can set and read one too", async ({ mcp }) => { await mcp.tools.call("set_banner", { text: "Exports are slow today." }); expect((await mcp.tools.call("get_banner", {})).json()).toEqual({ banner: "Exports are slow today." }); }); test("session: kept for a signed-in agent across requests, and only for them", async () => { await callAs(NOUR, "work_on", { ticketId: "T-3" }); expect((await callAs(NOUR, "current_ticket")).structuredContent).toEqual({ ticketId: "T-3" }); expect((await callAs(SAM, "current_ticket")).structuredContent).toEqual({ ticketId: null }); }); test("session: an anonymous caller is refused", async ({ mcp }) => { const result = await mcp.tools.call("work_on", { ticketId: "T-1" }); expect(result).toBeError("REMEMBER_IDENTITY_REQUIRED"); expect(result.text()).toContain("Remember cannot use session or tool scope for an unauthenticated request"); }); ``` The banner is in `global` scope, so Sam reads what Nour set, and a caller who isn't signed in can set and read a banner too. (The Playground's own server and the one `callAs()` starts are two servers, and each has its own memory: the anonymous caller's banner is a different one from Nour's.) The ticket is in `session` scope, the default: it lasts for Nour across her requests, Sam doesn't see it, and a caller who isn't signed in can't use `session` scope, or `user`, at all. `this.remember` throws a `RememberIdentityError`, and the call fails with the code `REMEMBER_IDENTITY_REQUIRED`. The error's message says what to do: authenticate the request, or use `global` if the value really is shared. > **Pitfall: Under 2026-07-28, session doesn't mean a conversation** > > The name suggests a value that ends with the conversation. MCP 2026-07-28 has no sessions, so FrontMCP keeps `session` and `tool` values for the signed-in caller instead: Nour's current ticket is still there tomorrow, in every conversation and every client she uses, until it's forgotten or expires. Give conversation-sized values a `ttl` (next section), put what belongs to a person in `user` scope, and remember that an anonymous caller can use only `global`. Which scope, then: - **`user`** for what belongs to a person: a signature, a language, the columns they like in a report. - **`global`** for what everyone may see: a banner, a shared counter, the last time a sync ran. Never for anything personal, because every caller reads it. - **`session`** for what a signed-in caller is in the middle of, with a `ttl`, knowing it lasts across their conversations. - **`tool`** for a tool's own bookkeeping that no other tool should read or change, like which tickets `next_ticket` already suggested to this agent. ## How long a value lives A value lives until it's forgotten, unless you give it a `ttl`, in seconds, when you store it, or the plugin has a `defaultTTL`, which `init()` takes for values stored without one. A reply draft should be there tomorrow morning, but not next month. `save_draft` keeps a draft for a day, and `send_reply` forgets it once it's sent. The tests move the clock forward by replacing `Date.now()`, which is what the plugin and its memory store read: ```ts drafts.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; const input = { ticketId: z.string().describe("Ticket id, like T-1") }; @Tool({ name: "save_draft", description: "Save a reply draft for a ticket. Drafts are kept for a day.", inputSchema: { ...input, text: z.string() } }) export class SaveDraft extends ToolContext { async execute({ ticketId, text }: { ticketId: string; text: string }) { await this.remember.set(`draft:${ticketId}`, text, { scope: "user", ttl: 24 * 60 * 60 }); return { saved: ticketId }; } } @Tool({ name: "get_draft", description: "Your reply draft for a ticket, if you have one.", inputSchema: input }) export class GetDraft extends ToolContext { async execute({ ticketId }: { ticketId: string }) { return { draft: await this.remember.get(`draft:${ticketId}`, { scope: "user", defaultValue: null }) }; } } @Tool({ name: "send_reply", description: "Send your reply draft for a ticket to the customer.", inputSchema: input }) export class SendReply extends ToolContext { async execute({ ticketId }: { ticketId: string }) { const key = `draft:${ticketId}`; const draft = await this.remember.get(key, { scope: "user" }); if (!draft) return { sent: false }; await this.remember.forget(key, { scope: "user" }); return { sent: true, text: draft }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SaveDraft, GetDraft, SendReply], plugins: [RememberPlugin.init({ type: "memory" })], }) export class HelpDeskApp {} ``` ```ts server.ts import { HelpDeskApp } from "./drafts.app"; // Two support agents, each with a key of their own. // In your project: @FrontMcp(config) export default class Server {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; let server: ReturnType | undefined; /** Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. */ export async function callAs(key: string, tool: string, args: Record = {}) { server ??= FrontMcpInstance.createFetchHandler(config); const response = await (await server)( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result; } ``` ```ts drafts.test.ts import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; /** Runs `fn` with the clock `hours` ahead. */ async function inHours(hours: number, fn: () => Promise) { const realNow = Date.now; const now = realNow(); Date.now = () => now + hours * 60 * 60 * 1000; try { return await fn(); } finally { Date.now = realNow; } } test("a draft is there the next morning", async () => { await callAs(NOUR, "save_draft", { ticketId: "T-1", text: "You can log in again." }); const later = await inHours(20, () => callAs(NOUR, "get_draft", { ticketId: "T-1" })); expect(later.structuredContent).toEqual({ draft: "You can log in again." }); }); test("and gone after a day", async () => { await callAs(NOUR, "save_draft", { ticketId: "T-2", text: "Your invoice is fixed." }); const later = await inHours(25, () => callAs(NOUR, "get_draft", { ticketId: "T-2" })); expect(later.structuredContent).toEqual({ draft: null }); }); test("sending a reply forgets its draft", async () => { await callAs(NOUR, "save_draft", { ticketId: "T-3", text: "Here's a new link." }); expect((await callAs(NOUR, "send_reply", { ticketId: "T-3" })).structuredContent).toEqual({ sent: true, text: "Here's a new link." }); expect((await callAs(NOUR, "get_draft", { ticketId: "T-3" })).structuredContent).toEqual({ draft: null }); }); ``` `forget(key, { scope })` deletes a value at once, and a value past its `ttl` reads as missing. `this.remember` has a few more methods, like `knows()` to check for a value and `list()` for the keys in a scope ([`this.remember`](https://frontmcp.dev/reference/plugins/remember#thisremember)). Every value also lives only as long as its store: - **`type: "memory"` keeps values in the server's process, one store per server.** They're lost on restart and not shared between instances, or between two servers in one process. For a server that restarts or runs more than once, use Redis or Vercel KV ([Stores](https://frontmcp.dev/reference/plugins/remember#stores)). - **Values are encrypted** with a secret the server derives its keys from. In production, set `REMEMBER_SECRET` to the same value on every instance. Without it, each process makes up its own, and values stored before a restart, or by another instance, can't be read ([Encryption](https://frontmcp.dev/reference/plugins/remember#encryption)). ## Letting the model remember things So far your tools decide what to remember. The plugin can also give the model tools of its own. Set `tools.enabled` and it registers `remember_this`, `recall`, `forget` and `list_memories`, and your app lists none of them. Each takes a `scope`, which defaults to `session`. Their descriptions say what each scope keeps under 2026-07-28, and end with "An anonymous caller cannot use user scope, nor session scope without a session." The model still picks the scope, so limit it to the one you mean with `tools.allowedScopes`: Initial call configuration: ```js { tool: "list_memories", arguments: { scope: "user" } } ``` ```ts assistant.app.ts active import { App } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @App({ id: "assistant", name: "Assistant", plugins: [RememberPlugin.init({ type: "memory", tools: { enabled: true, allowedScopes: ["user"] } })], }) export class AssistantApp {} ``` ```ts server.ts import { AssistantApp } from "./assistant.app"; // Two support agents, each with a key of their own. // In your project: @FrontMcp(config) export default class Server {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [AssistantApp], auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; let server: ReturnType | undefined; /** Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. */ export async function callAs(key: string, tool: string, args: Record = {}) { server ??= FrontMcpInstance.createFetchHandler(config); const response = await (await server)( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result; } ``` ```ts memory-tools.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { ForgetTool, ListMemoriesTool, RecallTool, RememberPlugin, RememberThisTool } from "@frontmcp/plugin-remember"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; const SAM = "agent-sam-key"; test("the plugin registers the four memory tools, and the app lists none", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name).sort(); expect(names).toEqual(["forget", "list_memories", "recall", "remember_this"]); }); test("the tools' scope description says what an anonymous caller can't use", async ({ mcp }) => { const tools = await mcp.tools.list(); const rememberThis = tools.find((t: { name: string }) => t.name === "remember_this"); expect(rememberThis.inputSchema.properties.scope.description).toContain("user: the signed-in caller, across all of its sessions."); expect(rememberThis.inputSchema.properties.scope.description).toContain("An anonymous caller cannot use user scope, nor session scope without a session."); }); test("an anonymous caller can't list memories in user scope", async ({ mcp }) => { const result = await mcp.tools.call("list_memories", { scope: "user" }); expect(result).toBeError("REMEMBER_IDENTITY_REQUIRED"); expect(result.text()).toContain("Remember cannot use user scope without an authenticated user"); }); test("the model remembers and recalls things for the agent", async () => { const saved = await callAs(NOUR, "remember_this", { key: "timezone", value: "Europe/Paris", scope: "user" }); expect(saved.structuredContent).toEqual({ success: true, key: "timezone", scope: "user" }); expect((await callAs(NOUR, "recall", { key: "timezone", scope: "user" })).structuredContent).toMatchObject({ found: true, value: "Europe/Paris" }); expect((await callAs(SAM, "recall", { key: "timezone", scope: "user" })).structuredContent).toMatchObject({ found: false }); expect((await callAs(NOUR, "list_memories", { scope: "user" })).structuredContent).toMatchObject({ keys: ["timezone"], count: 1 }); }); test("another scope is refused, the default included, and the message names the allowed scope", async () => { const refused = await callAs(NOUR, "remember_this", { key: "timezone", value: "Europe/Paris" }); expect(refused.isError).toBe(true); expect(refused._meta.code).toBe("REMEMBER_SCOPE_NOT_ALLOWED"); expect(refused.content[0].text).toBe("Scope 'session' is not allowed. Allowed scopes: user"); const recalled = await callAs(NOUR, "recall", { key: "timezone", scope: "global" }); expect(recalled._meta.code).toBe("REMEMBER_SCOPE_NOT_ALLOWED"); }); test("tools.prefix puts a prefix on the names", async () => { @App({ id: "assistant", name: "Assistant", plugins: [RememberPlugin.init({ type: "memory", tools: { enabled: true, prefix: "memory_" } })] }) class Prefixed {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [Prefixed] }); const { tools } = await server.listTools(); expect(tools.map((t) => t.name).sort()).toEqual(["memory_forget", "memory_list_memories", "memory_recall", "memory_remember_this"]); expect(tools.find((t) => t.name === "memory_recall")?.description).toContain("saved with memory_remember_this"); await server.dispose(); }); test("an app that lists the tool classes too has every tool twice", async () => { @App({ id: "assistant", name: "Assistant", tools: [RememberThisTool, RecallTool, ForgetTool, ListMemoriesTool], plugins: [RememberPlugin.init({ type: "memory", tools: { enabled: true } })], }) class Twice {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [Twice] }); const names = (await server.listTools()).tools.map((t) => t.name); expect(names).toHaveLength(8); expect(names).toContain("assistant:recall"); expect(names).toContain("remember:recall"); await server.dispose(); }); ``` The Playground calls `list_memories` as its anonymous client, and is refused with `REMEMBER_IDENTITY_REQUIRED`: an anonymous caller has no `user` memory, so these tools are for signed-in users. For Nour, `remember_this` stores her time zone in `user` scope, and `recall` finds it for her and not for Sam. A call without a scope, or with another, is refused with a tool error that names the allowed scopes and has the code `REMEMBER_SCOPE_NOT_ALLOWED`, so the model can call again with `scope: "user"`. `tools.prefix` puts a prefix on all four names, like `memory_recall`, and their descriptions name each other by the prefixed names. > **Note** > > Changed in 1.8.6: `list_memories` for an anonymous caller in `user` scope answered `{ keys: [], count: 0 }`, as if there were nothing to list. It's an error now. > **Note** > > Changed in 1.8.7: the plugin registers these tools itself, and a refused scope is a public error, so in production the model reads the message instead of `Internal FrontMCP error…`. Before, the plugin added no tools: the app listed `RememberThisTool` and the other classes in its `tools`, and `tools` options passed to `init()` stopped the server with `TypeError: list is not iterable`, so they went through `useFactory`. An app that still lists the classes and sets `tools.enabled` has every tool twice: drop one of the two. The model decides what to remember, so treat what these tools store as the user's notes, not as settings your code relies on. For a value your code needs, like the signature, write a tool of your own that stores it in the scope you choose. ## Recap - `@frontmcp/plugin-remember` gives every tool `this.remember`. Register `RememberPlugin.init({ type: "memory" })`, then `set(key, value, { scope, ttl })`, `get(key, { scope, defaultValue })` and `forget(key, { scope })`. - `user` scope keeps a value for the caller: a signed-in user's token `sub`, or a static key. An anonymous caller has no identity to keep a value under, and `user` scope refuses it. - `session`, the default, is kept for a signed-in caller across requests and conversations under 2026-07-28, and refused to an anonymous one. `tool` works the same way, with values for one tool only. `global` is shared by every caller, and the only scope an anonymous caller can use. A refusal has the code `REMEMBER_IDENTITY_REQUIRED`. - `ttl` is in seconds; without one, a value lasts until it's forgotten, or for the plugin's `defaultTTL` when you set one. The memory store is lost on restart; use Redis or Vercel KV, and one `REMEMBER_SECRET`, for a server that runs more than once. - `tools: { enabled: true }` makes the plugin register `remember_this`, `recall`, `forget` and `list_memories`, so the model can remember things. Limit their scopes with `tools.allowedScopes`: a call with another scope is refused with `REMEMBER_SCOPE_NOT_ALLOWED`. - Every option, store and method is in the [Remember plugin reference](https://frontmcp.dev/reference/plugins/remember). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Give each agent their own signature `set_signature` and `draft_reply` use `this.remember`, and still sign every agent's replies with whichever signature was set last. Make each agent's signature their own, with the default for agents who haven't set one. Initial call configuration: ```js { tool: "draft_reply", arguments: { ticketId: "T-1", text: "You can log in again." } } ``` ```ts signature.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @Tool({ name: "set_signature", description: "Set the signature your replies end with.", inputSchema: { signature: z.string().max(80) }, }) export class SetSignature extends ToolContext { async execute({ signature }: { signature: string }) { await this.remember.set("signature", signature, { scope: "global" }); return { signature }; } } @Tool({ name: "draft_reply", description: "Draft a reply to a support ticket, signed with your signature.", inputSchema: { ticketId: z.string(), text: z.string() }, }) export class DraftReply extends ToolContext { async execute({ ticketId, text }: { ticketId: string; text: string }) { const signature = await this.remember.get("signature", { scope: "global", defaultValue: "The Help Desk" }); return { ticketId, reply: `${text}\n\n${signature}` }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetSignature, DraftReply], plugins: [RememberPlugin.init({ type: "memory" })], }) export class HelpDeskApp {} ``` **Solution file (alternative to the starter):** ```ts signature.app.ts solution import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @Tool({ name: "set_signature", description: "Set the signature your replies end with.", inputSchema: { signature: z.string().max(80) }, }) export class SetSignature extends ToolContext { async execute({ signature }: { signature: string }) { await this.remember.set("signature", signature, { scope: "user" }); return { signature }; } } @Tool({ name: "draft_reply", description: "Draft a reply to a support ticket, signed with your signature.", inputSchema: { ticketId: z.string(), text: z.string() }, }) export class DraftReply extends ToolContext { async execute({ ticketId, text }: { ticketId: string; text: string }) { const signature = await this.remember.get("signature", { scope: "user", defaultValue: "The Help Desk" }); return { ticketId, reply: `${text}\n\n${signature}` }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetSignature, DraftReply], plugins: [RememberPlugin.init({ type: "memory" })], }) export class HelpDeskApp {} ``` ```ts server.ts import { HelpDeskApp } from "./signature.app"; // Two support agents, each with a key of their own. export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; let server: ReturnType | undefined; /** Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. */ export async function callAs(key: string, tool: string, args: Record = {}) { server ??= FrontMcpInstance.createFetchHandler(config); const response = await (await server)( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result; } ``` **Hidden fixture/test file (runs with the example):** ```ts signature.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; const SAM = "agent-sam-key"; test("an agent's replies are signed with their own signature", async () => { await callAs(NOUR, "set_signature", { signature: "Nour, Tier 2 support" }); const draft = await callAs(NOUR, "draft_reply", { ticketId: "T-1", text: "Fixed." }); expect(draft.structuredContent.reply).toBe("Fixed.\n\nNour, Tier 2 support"); }); test("an agent without a signature gets the default", async () => { const draft = await callAs(SAM, "draft_reply", { ticketId: "T-2", text: "Fixed." }); expect(draft.structuredContent.reply).toBe("Fixed.\n\nThe Help Desk"); }); test("one agent's change doesn't reach another's replies", async () => { await callAs(SAM, "set_signature", { signature: "Sam, Billing" }); const draft = await callAs(NOUR, "draft_reply", { ticketId: "T-1", text: "Fixed." }); expect(draft.structuredContent.reply).toBe("Fixed.\n\nNour, Tier 2 support"); }); ``` **Hint:** The code already stores the signature, and every agent reads it back. The question is who shares it. **Solution:** `global` scope is one value for every caller, so the last signature set was on everyone's replies. `scope: "user"` in both `set()` and `get()` keeps a value for each caller: the checks sign in with Nour's and Sam's keys, so each has their own, and Sam gets the default until he sets his. Both calls must use the same scope, or `draft_reply` looks in a different place from where `set_signature` wrote. ### Challenge: Show the outage banner to everyone During an outage, an agent sets a banner that every caller should see, including customers who haven't signed in. Right now the banner is only there for the agent who set it, and an anonymous caller's `get_banner` fails. Make every caller read the same banner. Initial call configuration: ```js { tool: "get_banner", arguments: {} } ``` ```ts banner.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @Tool({ name: "set_banner", description: "Show a banner to everyone, like an outage notice.", inputSchema: { text: z.string() } }) export class SetBanner extends ToolContext { async execute({ text }: { text: string }) { await this.remember.set("banner", text); return { banner: text }; } } @Tool({ name: "get_banner", description: "The banner everyone sees, if there is one.", inputSchema: {} }) export class GetBanner extends ToolContext { async execute() { return { banner: await this.remember.get("banner", { defaultValue: null }) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetBanner, GetBanner], plugins: [RememberPlugin.init({ type: "memory" })], }) export class HelpDeskApp {} ``` **Solution file (alternative to the starter):** ```ts banner.app.ts solution import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @Tool({ name: "set_banner", description: "Show a banner to everyone, like an outage notice.", inputSchema: { text: z.string() } }) export class SetBanner extends ToolContext { async execute({ text }: { text: string }) { await this.remember.set("banner", text, { scope: "global" }); return { banner: text }; } } @Tool({ name: "get_banner", description: "The banner everyone sees, if there is one.", inputSchema: {} }) export class GetBanner extends ToolContext { async execute() { return { banner: await this.remember.get("banner", { scope: "global", defaultValue: null }) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetBanner, GetBanner], plugins: [RememberPlugin.init({ type: "memory" })], }) export class HelpDeskApp {} ``` ```ts server.ts import { HelpDeskApp } from "./banner.app"; // Two support agents, each with a key of their own. export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; let server: ReturnType | undefined; /** Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. */ export async function callAs(key: string, tool: string, args: Record = {}) { server ??= FrontMcpInstance.createFetchHandler(config); const response = await (await server)( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result; } ``` **Hidden fixture/test file (runs with the example):** ```ts banner.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; test("another agent sees the banner an agent set", async () => { await callAs("agent-nour-key", "set_banner", { text: "Login is down. We're on it." }); expect((await callAs("agent-sam-key", "get_banner")).structuredContent).toEqual({ banner: "Login is down. We're on it." }); }); test("a caller who isn't signed in can post and read a banner too", async ({ mcp }) => { expect(await mcp.tools.call("set_banner", { text: "Exports are slow today." })).toBeSuccessful(); const result = await mcp.tools.call("get_banner", {}); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ banner: "Exports are slow today." }); }); ``` **Hint:** Neither call names a scope, so both use the default. What does the default keep under MCP 2026-07-28, and for whom? **Solution:** Without a `scope`, `this.remember` uses `session`, which under 2026-07-28 belongs to the signed-in caller: Nour's banner was Nour's alone, and an anonymous caller was refused with `RememberIdentityError`. `scope: "global"` in both calls keeps one banner for everyone. That's right for a banner, because it's meant for every caller, and wrong for anything personal. ### Challenge: Let drafts expire after a day Reply drafts are kept forever, and agents keep finding week-old drafts for tickets that were solved long ago. Keep a draft for one day after it's saved, and no longer. ```ts drafts.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; const input = { ticketId: z.string().describe("Ticket id, like T-1") }; @Tool({ name: "save_draft", description: "Save a reply draft for a ticket.", inputSchema: { ...input, text: z.string() } }) export class SaveDraft extends ToolContext { async execute({ ticketId, text }: { ticketId: string; text: string }) { await this.remember.set(`draft:${ticketId}`, text, { scope: "user" }); return { saved: ticketId }; } } @Tool({ name: "get_draft", description: "Your reply draft for a ticket, if you have one.", inputSchema: input }) export class GetDraft extends ToolContext { async execute({ ticketId }: { ticketId: string }) { return { draft: await this.remember.get(`draft:${ticketId}`, { scope: "user", defaultValue: null }) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SaveDraft, GetDraft], plugins: [RememberPlugin.init({ type: "memory" })], }) export class HelpDeskApp {} ``` **Solution file (alternative to the starter):** ```ts drafts.app.ts solution import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; const input = { ticketId: z.string().describe("Ticket id, like T-1") }; @Tool({ name: "save_draft", description: "Save a reply draft for a ticket. Drafts are kept for a day.", inputSchema: { ...input, text: z.string() } }) export class SaveDraft extends ToolContext { async execute({ ticketId, text }: { ticketId: string; text: string }) { await this.remember.set(`draft:${ticketId}`, text, { scope: "user", ttl: 24 * 60 * 60 }); return { saved: ticketId }; } } @Tool({ name: "get_draft", description: "Your reply draft for a ticket, if you have one.", inputSchema: input }) export class GetDraft extends ToolContext { async execute({ ticketId }: { ticketId: string }) { return { draft: await this.remember.get(`draft:${ticketId}`, { scope: "user", defaultValue: null }) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SaveDraft, GetDraft], plugins: [RememberPlugin.init({ type: "memory" })], }) export class HelpDeskApp {} ``` ```ts server.ts import { HelpDeskApp } from "./drafts.app"; // Two support agents, each with a key of their own. export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; let server: ReturnType | undefined; /** Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. */ export async function callAs(key: string, tool: string, args: Record = {}) { server ??= FrontMcpInstance.createFetchHandler(config); const response = await (await server)( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result; } ``` **Hidden fixture/test file (runs with the example):** ```ts drafts.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; async function inHours(hours: number, fn: () => Promise) { const realNow = Date.now; const now = realNow(); Date.now = () => now + hours * 60 * 60 * 1000; try { return await fn(); } finally { Date.now = realNow; } } test("a draft is still there after 23 hours", async () => { await callAs(NOUR, "save_draft", { ticketId: "T-1", text: "You can log in again." }); const later = await inHours(23, () => callAs(NOUR, "get_draft", { ticketId: "T-1" })); expect(later.structuredContent).toEqual({ draft: "You can log in again." }); }); test("a draft is gone after 25 hours", async () => { await callAs(NOUR, "save_draft", { ticketId: "T-2", text: "Your invoice is fixed." }); const later = await inHours(25, () => callAs(NOUR, "get_draft", { ticketId: "T-2" })); expect(later.structuredContent).toEqual({ draft: null }); }); ``` **Hint:** `set()` takes one more option. It's in seconds. **Solution:** `ttl: 24 * 60 * 60` stores the draft for 86,400 seconds, a day. After that `get()` treats it as missing and returns the `defaultValue`, `null`, and the store drops it. The description tells the model drafts are kept for a day, so it can tell the agent. ### Challenge: Let the model remember, for users only Give the assistant the four memory tools, so the model can remember things for a signed-in agent and recall them later. Allow only `user` scope: a call with any other scope, or none, must be refused. Initial call configuration: ```js { tool: "whats_new", arguments: {} } ``` ```ts assistant.app.ts active import { App, Tool, ToolContext } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @Tool({ name: "whats_new", description: "What's new in the help desk this week.", inputSchema: {} }) export class WhatsNew extends ToolContext { async execute() { return { news: ["Tickets can now be merged."] }; } } @App({ id: "assistant", name: "Assistant", tools: [WhatsNew], plugins: [RememberPlugin.init({ type: "memory" })], }) export class AssistantApp {} ``` **Solution file (alternative to the starter):** ```ts assistant.app.ts solution import { App, Tool, ToolContext } from "@frontmcp/sdk"; import { RememberPlugin } from "@frontmcp/plugin-remember"; @Tool({ name: "whats_new", description: "What's new in the help desk this week.", inputSchema: {} }) export class WhatsNew extends ToolContext { async execute() { return { news: ["Tickets can now be merged."] }; } } @App({ id: "assistant", name: "Assistant", tools: [WhatsNew], plugins: [RememberPlugin.init({ type: "memory", tools: { enabled: true, allowedScopes: ["user"] } })], }) export class AssistantApp {} ``` ```ts server.ts import { AssistantApp } from "./assistant.app"; // Two support agents, each with a key of their own. export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [AssistantApp], auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; let server: ReturnType | undefined; /** Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. */ export async function callAs(key: string, tool: string, args: Record = {}) { server ??= FrontMcpInstance.createFetchHandler(config); const response = await (await server)( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result; } ``` **Hidden fixture/test file (runs with the example):** ```ts memory.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; test("`remember_this`, `recall`, `forget` and `list_memories` are listed", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name).sort(); expect(names).toEqual(["forget", "list_memories", "recall", "remember_this", "whats_new"]); }); test("the model can remember something for an agent and recall it", async () => { await callAs(NOUR, "remember_this", { key: "team", value: "Tier 2", scope: "user" }); expect((await callAs(NOUR, "recall", { key: "team", scope: "user" })).structuredContent).toMatchObject({ found: true, value: "Tier 2" }); }); test("a call without `scope: \"user\"` is refused", async () => { const withoutScope = await callAs(NOUR, "remember_this", { key: "team", value: "Tier 2" }); const inGlobal = await callAs(NOUR, "remember_this", { key: "team", value: "Tier 2", scope: "global" }); expect(withoutScope.isError).toBe(true); expect(inGlobal.isError).toBe(true); }); ``` **Hint:** The plugin registers the memory tools itself, when you ask it to. Two of its `tools` options do the job: one turns them on, the other limits their scopes. **Solution:** `tools: { enabled: true }` makes the plugin register `remember_this`, `recall`, `forget` and `list_memories` next to `whats_new`, and `allowedScopes: ["user"]` limits them to `user` scope. A call without a scope asks for `session`, which isn't allowed, so the model is told to use `user`. --- # Asking for Approval > Require recorded user approval before a FrontMCP tool runs. Build the approval UI and control expiration and withdrawal. Source: https://frontmcp.dev/learn/asking-for-approval [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Some tools shouldn't run just because the model decided to. Deleting a ticket can't be undone. `destructiveHint` tells the client so, but the client may run the tool without asking anyone, and [authorization](https://frontmcp.dev/learn/authorizing-calls) decides who may delete tickets, not whether this user agreed to let the assistant do it. `@frontmcp/plugin-approval` puts a gate in front of a FrontMCP tool: every call is refused until an approval of that tool is recorded for the caller. Your code records the approval once the user says yes, and can withdraw it. The plugin doesn't ask anyone itself, so this lesson builds the asking too. **You will learn** - How to require approval before a tool runs - What the model sees when a call is refused, and how to tell it what to do next - How to record an approval once the user says yes, and how to withdraw it - How long an approval lasts under MCP 2026-07-28 - Why the model must never be able to approve its own calls ## A tool the model can run on its own `delete_ticket` deletes a ticket for good, and says so with `destructiveHint`: Initial call configuration: ```js { tool: "delete_ticket", arguments: { id: "T-1" } } ``` ```ts delete-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); ``` ```ts delete.test.ts import { test, expect } from "@frontmcp/testing"; import { tickets } from "./store"; test("the tool says it's destructive", async ({ mcp }) => { const [tool] = await mcp.tools.list(); expect(tool.annotations).toMatchObject({ destructiveHint: true }); }); test("🚩 and the call deletes the ticket, with nobody asked", async ({ mcp }) => { const result = await mcp.tools.call("delete_ticket", { id: "T-2" }); expect(result.json()).toEqual({ id: "T-2", deleted: true }); expect(tickets.has("T-2")).toBe(false); }); ``` A hint is only a hint. Some clients ask the user before a destructive call, some ask once and remember, and some don't ask at all, and your server can't tell which one it's talking to. [Asking the User Mid-Call](https://frontmcp.dev/learn/asking-the-user) shows how a tool can ask on every call. An approval is different: the user says yes once, your server records it, and a gate outside the tool checks for it on every call, until it expires or is withdrawn. ## Putting a tool behind approval Install the plugin: ```bash npm install @frontmcp/plugin-approval ``` Register it on the app with `ApprovalPlugin.init({ storage: { type: "memory" } })`, and give each tool that needs approval an `approval` field. `approvalMessage` is what a refused call says: Initial call configuration: ```js { tool: "delete_ticket", arguments: { id: "T-1" } } ``` ```ts help-desk.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApprovalPlugin } from "@frontmcp/plugin-approval"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good. Needs the user's approval.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, approval: { approvalMessage: "delete_ticket needs the user's approval first." }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return tickets.get(id) ?? { id, found: false }; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, DeleteTicket], plugins: [ApprovalPlugin.init({ storage: { type: "memory" } })], }) export class HelpDeskApp {} ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); ``` ```ts gate.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { DeleteTicket } from "./help-desk.app"; import { tickets } from "./store"; test("an unapproved call is refused, and the ticket stays", async ({ mcp }) => { const result = await mcp.tools.call("delete_ticket", { id: "T-2" }); expect(result).toBeError("APPROVAL_REQUIRED"); expect(result.text()).toBe("delete_ticket needs the user's approval first."); expect(tickets.has("T-2")).toBe(true); }); test("tools without `approval` aren't affected", async ({ mcp }) => { expect((await mcp.tools.call("get_ticket", { id: "T-1" })).json()).toMatchObject({ title: "Cannot log in" }); }); test("the gated tool is still listed", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("delete_ticket"); }); test("🚩 without the plugin, the server doesn't start", async () => { @App({ id: "help-desk", name: "Help Desk", tools: [DeleteTicket] }) class Unprotected {} await expect(FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [Unprotected] })).rejects.toThrow( `Tool "delete_ticket" declares 'approval' (enforced by ApprovalPlugin from @frontmcp/plugin-approval)`, ); }); ``` The plugin checks after the arguments are validated and before `execute()` runs, so a refused call changes nothing. `get_ticket`, which has no `approval`, runs as before. `approval: true` works too, with a default message; either way, a tool with `approval` on a server with no approval plugin doesn't start, so a gate can't be left off by accident. The refusal is a tool error, the kind the model reads. Open the Call tab: the text is `approvalMessage` and nothing more, and `_meta.code` is `APPROVAL_REQUIRED`. It reads the same in production ([What the client sees](https://frontmcp.dev/reference/plugins/approval#what-the-client-sees)), so put in `approvalMessage` what the model should do next: "Call approve_delete first." > **Note** > > Changed in 1.8.6: before, a refusal reached the client as an internal error. Its `_meta.code` was `SERVER_ERROR`, in development its text went on with `Original error:` and a stack trace, and in production it was only `Internal FrontMCP error. Please contact support with error ID: …`, so the model never learned that it needed approval. ## Recording an approval Nothing can approve `delete_ticket` yet. The plugin adds `this.approval` to the tools of the app it's registered on (every app's, on `@FrontMcp`), which grants, checks and withdraws approvals for the caller. `approve_delete` grants one with `grantUserApproval()`, which lasts until it's withdrawn. An approval is kept for a caller, so the tests need callers who are signed in. As in [Remembering Across Calls](https://frontmcp.dev/learn/remembering-across-calls), `server.ts` gives Nour and Sam a [static key](https://frontmcp.dev/learn/authenticating-clients#requiring-a-shared-key-static-mode) each, and `callAs()` sends a tool call with a key the way an MCP 2026-07-28 client would, to one server for every call. It also answers a form, if a tool asks one, the way the user would; this section doesn't need that yet: Initial call configuration: ```js { tool: "approve_delete", arguments: {} } ``` ```ts approve-delete.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; // An approval names its tool by the app's id and the tool's name export const DELETE_TICKET = "help-desk:delete_ticket"; @Tool({ name: "approve_delete", description: "Approve delete_ticket for you.", inputSchema: {} }) export class ApproveDelete extends ToolContext { async execute() { const record = await this.approval.grantUserApproval(DELETE_TICKET); // 🚩 without asking anyone return { approved: true, scope: record.scope, grantedBy: record.grantedBy }; } } ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApprovalPlugin } from "@frontmcp/plugin-approval"; import { ApproveDelete } from "./approve-delete.tool"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good. Needs the user's approval: call approve_delete first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, approval: { approvalMessage: "delete_ticket needs the user's approval. Call approve_delete first." }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DeleteTicket, ApproveDelete], plugins: [ApprovalPlugin.init({ storage: { type: "memory" } })], }) export class HelpDeskApp {} ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); ``` ```ts server.ts import { HelpDeskApp } from "./help-desk.app"; // Two support agents, each with a key of their own. // In your project: @FrontMcp(config) export default class Server {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` ```ts call-as.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; type Answer = { action: "accept" | "decline"; content?: Record }; let server: ReturnType | undefined; /** * Sends one tools/call with this key, as an MCP 2026-07-28 client would. Every call goes to the same server. * If the tool asks the user something, `answer` is what the user replies; without one, they decline. */ export async function callAs(key: string, tool: string, args: Record = {}, answer?: Answer) { server ??= FrontMcpInstance.createFetchHandler(config); const handler = await server; let reply = {}; for (;;) { const response = await handler( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, ...reply, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { elicitation: { form: {} } }, }, }, }), }), ); const { result } = await response.json(); if (result.resultType !== "input_required") return result; // The tool asked the user: send their answer back, with the state the server returned const inputResponses = Object.fromEntries(Object.keys(result.inputRequests).map((id) => [id, answer ?? { action: "decline" }])); reply = { inputResponses, requestState: result.requestState }; } } ``` ```ts approve.test.ts import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; import { tickets } from "./store"; const NOUR = "agent-nour-key"; const SAM = "agent-sam-key"; test("delete_ticket runs once it's approved", async () => { expect((await callAs(NOUR, "delete_ticket", { id: "T-1" })).isError).toBe(true); expect((await callAs(NOUR, "approve_delete")).structuredContent).toMatchObject({ approved: true, scope: "user" }); expect((await callAs(NOUR, "delete_ticket", { id: "T-1" })).structuredContent).toEqual({ id: "T-1", deleted: true }); }); test("the approval names the caller as its grantor, and says nobody was asked", async () => { const { grantedBy } = (await callAs(NOUR, "approve_delete")).structuredContent; expect(grantedBy).toEqual({ source: "user", identifier: expect.stringMatching(/^static:/), method: "implicit" }); }); test("an approval belongs to the caller who got it", async () => { const result = await callAs(SAM, "delete_ticket", { id: "T-3" }); expect(result.isError).toBe(true); expect(tickets.has("T-3")).toBe(true); }); test("🚩 an anonymous caller's approval is gone by their next call", async ({ mcp }) => { // The Playground's own server, whose callers don't sign in expect(await mcp.tools.call("approve_delete", {})).toBeSuccessful(); expect(await mcp.tools.call("delete_ticket", { id: "T-3" })).toBeError(); }); ``` Once Nour has an approval, her `delete_ticket` runs. Sam has none, so his is still refused. The last test calls the Playground's own server: its caller is approved, and then refused anyway. The result shows the record's `grantedBy`: without one in the grant's options, it's the caller who made the call, for a static key its `static:…` id, with `method: "implicit"`. `"implicit"` is the record saying that nobody was asked: the tool granted on its own. A caller who isn't signed in is `{ source: "user", method: "implicit" }`. - **An approval belongs to a caller.** The gate looks for one recorded for the caller of each call: a signed-in user by their token's `sub`, a static key by its `static:…` id. A caller without credentials is a new anonymous caller on every MCP 2026-07-28 request, so an approval never carries over to their next call. Approvals need callers who [sign in](https://frontmcp.dev/learn/authenticating-clients). - **An approval names its tool as `:`**, like `help-desk:delete_ticket`, not the name clients see. `grantUserApproval("delete_ticket")` records an approval that nothing checks, without an error. - **The store is in memory.** `type: "memory"` keeps approvals in the server's process, so a restart withdraws them all, and each instance has its own. In production, use Redis, Vercel KV, Upstash or Cloudflare KV ([Options](https://frontmcp.dev/reference/plugins/approval#options)). ## Only a person can say yes Look at the first test again, from the model's side: it called `approve_delete`, then `delete_ticket`, and the ticket is gone. Nobody was asked. A tool that grants an approval without asking anyone lets the model approve itself, and the gate protects nothing. The yes has to come from someone the model can't speak for. `this.elicit()` shows the user a form in their client, and under MCP 2026-07-28 only the user can answer it. `approve_delete` now asks first: Initial call configuration: ```js { tool: "approve_delete", arguments: {} } ``` ```ts approve-delete.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { userGrantor } from "@frontmcp/plugin-approval"; export const DELETE_TICKET = "help-desk:delete_ticket"; @Tool({ name: "approve_delete", description: "Ask the user to let you delete support tickets for them. Call it when delete_ticket says it needs approval.", inputSchema: {}, }) export class ApproveDelete extends ToolContext { async execute() { // ✅ The user answers this form in their client. The model can't. const answer = await this.elicit("Allow the assistant to delete support tickets for you?", z.object({ allow: z.boolean() })); if (answer.status !== "accept" || !answer.content?.allow) return { approved: false }; // The user was asked, so the record says so const record = await this.approval.grantUserApproval(DELETE_TICKET, { grantedBy: userGrantor(this.auth.user.sub) }); return { approved: true, grantedBy: record.grantedBy }; } } ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApprovalPlugin } from "@frontmcp/plugin-approval"; import { ApproveDelete } from "./approve-delete.tool"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good. Needs the user's approval: call approve_delete first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, approval: { approvalMessage: "delete_ticket needs the user's approval. Call approve_delete first." }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DeleteTicket, ApproveDelete], plugins: [ApprovalPlugin.init({ storage: { type: "memory" } })], }) export class HelpDeskApp {} ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); ``` ```ts server.ts import { HelpDeskApp } from "./help-desk.app"; // Two support agents, each with a key of their own. // In your project: @FrontMcp(config) export default class Server {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts call-as.ts hidden import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; type Answer = { action: "accept" | "decline"; content?: Record }; let server: ReturnType | undefined; export async function callAs(key: string, tool: string, args: Record = {}, answer?: Answer) { server ??= FrontMcpInstance.createFetchHandler(config); const handler = await server; let reply = {}; for (;;) { const response = await handler( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, ...reply, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { elicitation: { form: {} } }, }, }, }), }), ); const { result } = await response.json(); if (result.resultType !== "input_required") return result; const inputResponses = Object.fromEntries(Object.keys(result.inputRequests).map((id) => [id, answer ?? { action: "decline" }])); reply = { inputResponses, requestState: result.requestState }; } } ``` ```ts ask.test.ts import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; const SAM = "agent-sam-key"; test("saying no, or closing the form, approves nothing", async () => { expect((await callAs(SAM, "approve_delete", {}, { action: "accept", content: { allow: false } })).structuredContent).toEqual({ approved: false }); expect((await callAs(SAM, "approve_delete", {}, { action: "decline" })).structuredContent).toEqual({ approved: false }); expect((await callAs(SAM, "delete_ticket", { id: "T-2" })).isError).toBe(true); }); test("the user's yes lets delete_ticket run, and records who gave it", async () => { const approved = await callAs(NOUR, "approve_delete", {}, { action: "accept", content: { allow: true } }); expect(approved.structuredContent).toMatchObject({ approved: true, grantedBy: { source: "user", identifier: expect.stringMatching(/^static:/), method: "interactive" }, }); expect((await callAs(NOUR, "delete_ticket", { id: "T-2" })).structuredContent).toEqual({ id: "T-2", deleted: true }); }); ``` Press **Call** in the Call tab: `approve_delete` shows the form the user would see. The model can still call `approve_delete`, and it should when `delete_ticket` is refused, as its description says. What it can't do is answer. The tests answer the form both ways: no, or closing it, approves nothing, and yes records an approval. Without a `grantedBy` option, the grant records the caller as `method: "implicit"`, form or no form: the plugin can't tell that a tool asked. `approve_delete` passes `grantedBy: userGrantor(this.auth.user.sub)`, which says `"interactive"`, because the user answered a form first. Pass `grantedBy` yourself too when the grant is made on someone else's behalf, like a team lead approving a teammate, which is what the grantor functions are for ([Grantors and revokers](https://frontmcp.dev/reference/plugins/approval#grantors-and-revokers)). > **Note** > > Changed in 1.8.7: the default `grantedBy` records `method: "implicit"`, because a tool that grants through `this.approval` asked no one. In 1.8.6 it said `"interactive"`, which an audit trail reads as the user saying yes, and before 1.8.6 it was `{ source: "policy" }`. A tool that did ask passes `grantedBy: userGrantor(id)`. > **Note** > > A client on a protocol version before 2026-07-28 that can't show forms gets FrontMCP's fallback instead: the model is told to ask the user in the chat and passes the answer on with `sendElicitationResult` ([this.elicit](https://frontmcp.dev/reference/sdk/elicit#the-model-is-asked-to-call-sendelicitationresult)). There, the yes comes through the model. Where that matters, have someone with more rights grant the approval, like a team lead approving a teammate for a limited time ([Approving for a limited time](https://frontmcp.dev/reference/plugins/approval#approving-for-a-limited-time)). ## Withdrawing an approval, and letting it expire A user approval lasts until it's withdrawn, which is more than most users mean by yes. `this.approval.revokeApproval(toolId)` withdraws the caller's approvals of a tool and says whether there were any. And `grantTimeLimitedApproval(toolId, ttlMs)` grants one that expires by itself. Here `approve_delete` grants for a number of minutes, 15 unless the model asks for another number, and says so in the form. The tests move the clock forward by replacing `Date.now()`, which is what the plugin reads: Initial call configuration: ```js { tool: "approve_delete", arguments: { minutes: 15 } } ``` ```ts approval-tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; export const DELETE_TICKET = "help-desk:delete_ticket"; @Tool({ name: "approve_delete", description: "Ask the user to let you delete support tickets for them, for some minutes. Call it when delete_ticket says it needs approval.", inputSchema: { minutes: z.number().int().min(1).max(60).default(15).describe("How long the approval lasts") }, }) export class ApproveDelete extends ToolContext { async execute({ minutes }: { minutes: number }) { const question = `Allow the assistant to delete support tickets for you for the next ${minutes} minutes?`; const answer = await this.elicit(question, z.object({ allow: z.boolean() })); if (answer.status !== "accept" || !answer.content?.allow) return { approved: false }; const record = await this.approval.grantTimeLimitedApproval(DELETE_TICKET, minutes * 60_000); return { approved: true, expiresAt: new Date(record.expiresAt!).toISOString() }; } } @Tool({ name: "revoke_delete", description: "Withdraw your approval of delete_ticket.", inputSchema: {} }) export class RevokeDelete extends ToolContext { async execute() { return { revoked: await this.approval.revokeApproval(DELETE_TICKET) }; } } @Tool({ name: "my_revocations", description: "The approvals of delete_ticket you withdrew in the last day.", inputSchema: {} }) export class MyRevocations extends ToolContext { async execute() { const revoked = await this.approval.getRevocations(DELETE_TICKET); return { revocations: revoked.map((r) => ({ scope: r.scope, revokedBy: r.revokedBy })) }; } } ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApprovalPlugin } from "@frontmcp/plugin-approval"; import { ApproveDelete, MyRevocations, RevokeDelete } from "./approval-tools"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good. Needs the user's approval: call approve_delete first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, approval: { approvalMessage: "delete_ticket needs the user's approval. Call approve_delete first." }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DeleteTicket, ApproveDelete, RevokeDelete, MyRevocations], plugins: [ApprovalPlugin.init({ storage: { type: "memory" } })], }) export class HelpDeskApp {} ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); ``` ```ts server.ts import { HelpDeskApp } from "./help-desk.app"; // Two support agents, each with a key of their own. // In your project: @FrontMcp(config) export default class Server {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts call-as.ts hidden import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; type Answer = { action: "accept" | "decline"; content?: Record }; let server: ReturnType | undefined; export async function callAs(key: string, tool: string, args: Record = {}, answer?: Answer) { server ??= FrontMcpInstance.createFetchHandler(config); const handler = await server; let reply = {}; for (;;) { const response = await handler( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, ...reply, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { elicitation: { form: {} } }, }, }, }), }), ); const { result } = await response.json(); if (result.resultType !== "input_required") return result; const inputResponses = Object.fromEntries(Object.keys(result.inputRequests).map((id) => [id, answer ?? { action: "decline" }])); reply = { inputResponses, requestState: result.requestState }; } } ``` ```ts lifetime.test.ts import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; const SAM = "agent-sam-key"; const yes = { action: "accept" as const, content: { allow: true } }; const deletes = async (key: string, id: string) => ((await callAs(key, "delete_ticket", { id })).isError ? "refused" : "ran"); /** Runs `fn` with the clock `minutes` ahead. */ async function inMinutes(minutes: number, fn: () => Promise) { const realNow = Date.now; const now = realNow(); Date.now = () => now + minutes * 60_000; try { return await fn(); } finally { Date.now = realNow; } } test("revoking withdraws the approval", async () => { await callAs(NOUR, "approve_delete", {}, yes); expect((await callAs(NOUR, "revoke_delete")).structuredContent).toEqual({ revoked: true }); expect(await deletes(NOUR, "T-1")).toBe("refused"); expect((await callAs(NOUR, "revoke_delete")).structuredContent).toEqual({ revoked: false }); }); test("a withdrawn approval is kept for a day, with who withdrew it", async () => { await callAs(NOUR, "approve_delete", {}, yes); await callAs(NOUR, "revoke_delete"); const { revocations } = (await callAs(NOUR, "my_revocations")).structuredContent; expect(revocations.at(-1)).toEqual({ scope: "time_limited", revokedBy: { source: "user", identifier: expect.stringMatching(/^static:/), method: "implicit" }, }); const nextDay = await inMinutes(24 * 60 + 1, () => callAs(NOUR, "my_revocations")); expect(nextDay.structuredContent).toEqual({ revocations: [] }); }); test("a 15-minute approval works for 15 minutes", async () => { await callAs(SAM, "approve_delete", { minutes: 15 }, yes); expect(await inMinutes(14, () => deletes(SAM, "T-2"))).toBe("ran"); expect(await inMinutes(16, () => deletes(SAM, "T-3"))).toBe("refused"); }); ``` Once an approval is withdrawn or has expired, the refusal is the same as before it was granted, so the model knows to call `approve_delete` again, and the user can say yes for another 15 minutes. A withdrawn approval isn't forgotten at once: the plugin keeps a copy for 24 hours, with who withdrew it, and `this.approval.getRevocations(toolId)` returns the caller's, as `my_revocations` does. `this.approval` has three grants for the caller: | Grant | Lasts | Under MCP 2026-07-28 | | --- | --- | --- | | `grantSessionApproval(toolId)` | Until it's withdrawn, for the caller's session | There are no sessions, so it's kept for the signed-in caller, in every conversation | | `grantUserApproval(toolId)` | Until it's withdrawn, for the caller | The same | | `grantTimeLimitedApproval(toolId, ttlMs)` | `ttlMs` milliseconds | The same | A tool can also cap every approval of it, however it was granted, with `maxTtlMs` in its `approval`: the gate ignores an approval older than that. Every field of `approval` is in [the reference](https://frontmcp.dev/reference/plugins/approval#the-approval-tool-option). > **Pitfall: Under 2026-07-28, a session approval is a user approval** > > An approval the user gave "for this session" sounds like it ends with the conversation. MCP 2026-07-28 has no sessions, so the plugin keeps it for the signed-in caller, and it lasts for every later conversation, on every client, until it's withdrawn or the store is lost. When an approval should end, give it a time limit. > **Note** > > Register the plugin once. On `@FrontMcp`, it gates every app's tools. In one app's `plugins`, it gates that app's tools and those of every app without an approval plugin of its own, but only its own app's tools get `this.approval`. On both, the two gates decide together, and an approval in either store lets the tool run, but each store holds approvals the other doesn't know about ([Register the plugin once](https://frontmcp.dev/reference/plugins/approval#how-a-call-is-checked)). ## Recap - `@frontmcp/plugin-approval` refuses every call to a tool with `approval` until an approval of it is recorded for the caller. Register `ApprovalPlugin.init({ storage: { type: "memory" } })`, and give the tool `approval: true` or `approval: { approvalMessage }`. - A refused call is a tool error with the text `approvalMessage` and the code `APPROVAL_REQUIRED`, in production too, so say in it what the model should do next. - `this.approval` grants, checks and withdraws approvals for the caller, and records the caller as `grantedBy`. Tools are named `:`, and approvals need callers who sign in. - Grant only after a person says yes, in a form from `this.elicit()`, or from a caller with more rights. A tool that grants without asking lets the model approve itself, though its `grantedBy` says `"implicit"`. - `revokeApproval()` withdraws an approval, `grantTimeLimitedApproval()` grants one that expires, and `maxTtlMs` caps every approval of a tool. Under MCP 2026-07-28, a session approval lasts for the signed-in caller. - The store, the grantors, contexts and every option are in the [Approval plugin reference](https://frontmcp.dev/reference/plugins/approval). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Put the refund behind approval `refund_invoice` sends money back to a customer, and nothing stops the model from calling it. `approve_refund` is already written. Make `refund_invoice` refuse every call that isn't approved, with a refusal that tells the model to call `approve_refund`. `get_invoice` must keep working. Initial call configuration: ```js { tool: "refund_invoice", arguments: { id: "INV-7" } } ``` ```ts billing.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApproveRefund } from "./approve-refund.tool"; import { invoices } from "./store"; @Tool({ name: "refund_invoice", description: "Refund an invoice in full.", inputSchema: { id: z.string().describe("Invoice id, like INV-7") }, annotations: { destructiveHint: true }, }) export class RefundInvoice extends ToolContext { async execute({ id }: { id: string }) { invoices.set(id, "refunded"); return { id, status: "refunded" }; } } @Tool({ name: "get_invoice", description: "Get an invoice's status.", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, status: invoices.get(id) ?? "unknown" }; } } @App({ id: "billing", name: "Billing", tools: [RefundInvoice, GetInvoice, ApproveRefund] }) export class BillingApp {} ``` **Solution file (alternative to the starter):** ```ts billing.app.ts solution import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApprovalPlugin } from "@frontmcp/plugin-approval"; import { ApproveRefund } from "./approve-refund.tool"; import { invoices } from "./store"; @Tool({ name: "refund_invoice", description: "Refund an invoice in full.", inputSchema: { id: z.string().describe("Invoice id, like INV-7") }, annotations: { destructiveHint: true }, approval: { approvalMessage: "refund_invoice needs the user's approval. Call approve_refund first." }, }) export class RefundInvoice extends ToolContext { async execute({ id }: { id: string }) { invoices.set(id, "refunded"); return { id, status: "refunded" }; } } @Tool({ name: "get_invoice", description: "Get an invoice's status.", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, status: invoices.get(id) ?? "unknown" }; } } @App({ id: "billing", name: "Billing", tools: [RefundInvoice, GetInvoice, ApproveRefund], plugins: [ApprovalPlugin.init({ storage: { type: "memory" } })], }) export class BillingApp {} ``` ```ts approve-refund.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "approve_refund", description: "Ask the user to let you refund invoices for them.", inputSchema: {} }) export class ApproveRefund extends ToolContext { async execute() { const answer = await this.elicit("Allow the assistant to refund invoices for you?", z.object({ allow: z.boolean() })); if (answer.status !== "accept" || !answer.content?.allow) return { approved: false }; await this.approval.grantUserApproval("billing:refund_invoice"); return { approved: true }; } } ``` ```ts store.ts export const invoices = new Map([ ["INV-7", "paid"], ["INV-8", "paid"], ]); ``` **Hidden fixture/test file (runs with the example):** ```ts refund.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { invoices } from "./store"; test("an unapproved refund is refused, and nothing is refunded", async ({ mcp }) => { const result = await mcp.tools.call("refund_invoice", { id: "INV-8" }); expect(result).toBeError(); expect(invoices.get("INV-8")).toBe("paid"); }); test("the refusal tells the model to call `approve_refund`", async ({ mcp }) => { const result = await mcp.tools.call("refund_invoice", { id: "INV-8" }); expect(result.text()).toContain("approve_refund"); }); test("`get_invoice` still works", async ({ mcp }) => { expect((await mcp.tools.call("get_invoice", { id: "INV-7" })).json()).toMatchObject({ id: "INV-7" }); }); ``` **Hint:** The gate takes two changes: one on the app, one on the tool. What the refusal says is a field of the tool's `approval`. **Solution:** `ApprovalPlugin.init({ storage: { type: "memory" } })` on the app installs the gate, and `approval` on `refund_invoice` puts the tool behind it, with an `approvalMessage` that names `approve_refund`: that's the text the model reads when the call is refused. `get_invoice` has no `approval`, so it isn't gated. ### Challenge: Ask before approving `approve_delete` grants an approval as soon as it's called, so the model can approve its own deletes. Make it ask the user first, and grant only when they say yes. Initial call configuration: ```js { tool: "approve_delete", arguments: {} } ``` ```ts approve-delete.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; export const DELETE_TICKET = "help-desk:delete_ticket"; @Tool({ name: "approve_delete", description: "Ask the user to let you delete support tickets for them. Call it when delete_ticket says it needs approval.", inputSchema: {}, }) export class ApproveDelete extends ToolContext { async execute() { await this.approval.grantUserApproval(DELETE_TICKET); return { approved: true }; } } ``` **Solution file (alternative to the starter):** ```ts approve-delete.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; export const DELETE_TICKET = "help-desk:delete_ticket"; @Tool({ name: "approve_delete", description: "Ask the user to let you delete support tickets for them. Call it when delete_ticket says it needs approval.", inputSchema: {}, }) export class ApproveDelete extends ToolContext { async execute() { const answer = await this.elicit("Allow the assistant to delete support tickets for you?", z.object({ allow: z.boolean() })); if (answer.status !== "accept" || !answer.content?.allow) return { approved: false }; await this.approval.grantUserApproval(DELETE_TICKET); return { approved: true }; } } ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApprovalPlugin } from "@frontmcp/plugin-approval"; import { ApproveDelete } from "./approve-delete.tool"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good. Needs the user's approval: call approve_delete first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, approval: { approvalMessage: "delete_ticket needs the user's approval. Call approve_delete first." }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DeleteTicket, ApproveDelete], plugins: [ApprovalPlugin.init({ storage: { type: "memory" } })], }) export class HelpDeskApp {} ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); ``` ```ts server.ts import { HelpDeskApp } from "./help-desk.app"; // Two support agents, each with a key of their own. export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts call-as.ts hidden import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; type Answer = { action: "accept" | "decline"; content?: Record }; let server: ReturnType | undefined; export async function callAs(key: string, tool: string, args: Record = {}, answer?: Answer) { server ??= FrontMcpInstance.createFetchHandler(config); const handler = await server; let reply = {}; for (;;) { const response = await handler( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, ...reply, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { elicitation: { form: {} } }, }, }, }), }), ); const { result } = await response.json(); if (result.resultType !== "input_required") return result; const inputResponses = Object.fromEntries(Object.keys(result.inputRequests).map((id) => [id, answer ?? { action: "decline" }])); reply = { inputResponses, requestState: result.requestState }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts ask.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const deletes = async (key: string, id: string) => ((await callAs(key, "delete_ticket", { id })).isError ? "refused" : "ran"); test("the user is asked, and saying no approves nothing", async () => { await callAs("agent-sam-key", "approve_delete", {}, { action: "accept", content: { allow: false } }); await callAs("agent-sam-key", "approve_delete", {}, { action: "decline" }); expect(await deletes("agent-sam-key", "T-2")).toBe("refused"); }); test("the user's yes lets `delete_ticket` run", async () => { await callAs("agent-nour-key", "approve_delete", {}, { action: "accept", content: { allow: true } }); expect(await deletes("agent-nour-key", "T-1")).toBe("ran"); }); ``` **Hint:** A tool can pause and ask the person using the client a question. The answer has a `status`, and, when they accepted, `content`. **Solution:** `this.elicit()` shows the user a form with one checkbox, and `approve_delete` grants only when the answer is `accept` with `allow: true`. The checks answer the form as the user would: no, a closed form, and yes. The model can still call `approve_delete`, but under MCP 2026-07-28 it can't answer the form. ### Challenge: Make approvals last an hour at most An approval of `delete_ticket` lasts until it's withdrawn, and users forget they gave one. Make every approval of `delete_ticket` stop working an hour after it's granted. Initial call configuration: ```js { tool: "delete_ticket", arguments: { id: "T-1" } } ``` ```ts help-desk.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApprovalPlugin } from "@frontmcp/plugin-approval"; import { ApproveDelete } from "./approve-delete.tool"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good. Needs the user's approval: call approve_delete first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, approval: { approvalMessage: "delete_ticket needs the user's approval. Call approve_delete first." }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DeleteTicket, ApproveDelete], plugins: [ApprovalPlugin.init({ storage: { type: "memory" } })], }) export class HelpDeskApp {} ``` **Solution file (alternative to the starter):** ```ts help-desk.app.ts solution import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { ApprovalPlugin } from "@frontmcp/plugin-approval"; import { ApproveDelete } from "./approve-delete.tool"; import { tickets } from "./store"; @Tool({ name: "delete_ticket", description: "Delete a support ticket for good. Needs the user's approval, which lasts an hour: call approve_delete first.", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, annotations: { destructiveHint: true }, approval: { approvalMessage: "delete_ticket needs the user's approval. Call approve_delete first.", maxTtlMs: 60 * 60_000 }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, deleted: tickets.delete(id) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DeleteTicket, ApproveDelete], plugins: [ApprovalPlugin.init({ storage: { type: "memory" } })], }) export class HelpDeskApp {} ``` ```ts approve-delete.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "approve_delete", description: "Ask the user to let you delete support tickets for them. Call it when delete_ticket says it needs approval.", inputSchema: {}, }) export class ApproveDelete extends ToolContext { async execute() { const answer = await this.elicit("Allow the assistant to delete support tickets for you?", z.object({ allow: z.boolean() })); if (answer.status !== "accept" || !answer.content?.allow) return { approved: false }; await this.approval.grantUserApproval("help-desk:delete_ticket"); return { approved: true }; } } ``` ```ts store.ts export const tickets = new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "closed" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]); ``` ```ts server.ts import { HelpDeskApp } from "./help-desk.app"; // Two support agents, each with a key of their own. export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, auth: { mode: "static" as const, tokens: ["agent-nour-key", "agent-sam-key"] }, }; ``` **Hidden fixture/test file (runs with the example):** ```ts call-as.ts hidden import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./server"; type Answer = { action: "accept" | "decline"; content?: Record }; let server: ReturnType | undefined; export async function callAs(key: string, tool: string, args: Record = {}, answer?: Answer) { server ??= FrontMcpInstance.createFetchHandler(config); const handler = await server; let reply = {}; for (;;) { const response = await handler( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": tool, authorization: `Bearer ${key}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool, arguments: args, ...reply, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { elicitation: { form: {} } }, }, }, }), }), ); const { result } = await response.json(); if (result.resultType !== "input_required") return result; const inputResponses = Object.fromEntries(Object.keys(result.inputRequests).map((id) => [id, answer ?? { action: "decline" }])); reply = { inputResponses, requestState: result.requestState }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts expiry.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { callAs } from "./call-as"; const NOUR = "agent-nour-key"; const yes = { action: "accept" as const, content: { allow: true } }; const deletes = async (id: string) => ((await callAs(NOUR, "delete_ticket", { id })).isError ? "refused" : "ran"); async function inMinutes(minutes: number, fn: () => Promise) { const realNow = Date.now; const now = realNow(); Date.now = () => now + minutes * 60_000; try { return await fn(); } finally { Date.now = realNow; } } test("an approval works for the first hour", async () => { await callAs(NOUR, "approve_delete", {}, yes); expect(await inMinutes(59, () => deletes("T-1"))).toBe("ran"); }); test("and not after it", async () => { await callAs(NOUR, "approve_delete", {}, yes); expect(await inMinutes(61, () => deletes("T-2"))).toBe("refused"); }); ``` **Hint:** You could change how `approve_delete` grants. But the rule is about `delete_ticket`, whoever grants its approvals: one field of its `approval` says how long any approval of it lasts. **Solution:** `maxTtlMs: 60 * 60_000` in `delete_ticket`'s `approval` is a rule on the tool: the gate ignores any approval of it older than an hour, and a grant through `this.approval` without its own `ttlMs` gets that hour. Granting with `grantTimeLimitedApproval(toolId, 60 * 60_000)` in `approve_delete` would pass the checks too, but only for approvals granted there; `maxTtlMs` also covers any other tool that grants one. The description tells the model how long an approval lasts. --- # Turning Features On and Off > How to put a FrontMCP tool, resource or prompt behind a feature flag with @frontmcp/plugin-feature-flags, what a caller sees while its flag is off, and how to turn a flag on for some callers first. Source: https://frontmcp.dev/learn/turning-features-on-and-off [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A new tool is rarely ready for everyone on the day it's merged. You want the help desk team to try it first, then one customer, then everybody, and you want a way to switch it off again without a deploy when something goes wrong. A **feature flag** is a named switch that a flag service answers per caller. `@frontmcp/plugin-feature-flags` connects flags to a FrontMCP server: give a tool, resource or prompt `featureFlag: "bulk-export"`, and while that flag is off for the caller, the entry isn't listed and can't be called. **You will learn** - Why a switch inside `execute()` is the wrong way to hide a tool - How to put a tool, resource or prompt behind a flag - What a caller sees while a flag is off - How to make a flag default to on, as a kill switch - How to turn a flag on for some callers, and read it inside a tool ## A tool that isn't ready yet The help desk is building `bulk_export`, which exports every ticket as CSV. It works, but it's slow on big accounts, so it shouldn't be used yet. A first attempt keeps it switched off with a constant: Initial call configuration: ```js { tool: "bulk_export", arguments: {} } ``` ```ts tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title", inputSchema: { query: z.string() }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } // 🚩 Not ready: switched off in code const BULK_EXPORT_READY = false; @Tool({ name: "bulk_export", description: "Export every support ticket as CSV", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class BulkExport extends ToolContext { async execute() { if (!BULK_EXPORT_READY) this.fail(new PublicMcpError("Bulk export isn't available yet.")); return { csv: ["id,title,status", ...tickets.map((t) => `${t.id},${t.title},${t.status}`)].join("\n") }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { BulkExport, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, BulkExport] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; ``` ```ts not-ready.test.ts import { test, expect } from "@frontmcp/testing"; test("🚩 the model is offered bulk_export", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("bulk_export"); }); test("🚩 and every call to it fails", async ({ mcp }) => { const result = await mcp.tools.call("bulk_export", {}); expect(result).toBeError(); expect(result).toHaveTextContent("Bulk export isn't available yet."); }); ``` Nobody can export, so in that sense it works. But the model still reads `bulk_export` in its tool list, with a description that promises an export, and it only learns the truth after spending a call on it. And the switch is all or nothing: turning it on means a deploy, for every caller at once. There's no way to let the team try it first. ## Putting a tool behind a flag Install the plugin: ```bash npm install @frontmcp/plugin-feature-flags ``` Then give the tool a `featureFlag`, and register the plugin with the flags' values. The tool loses its `if`: Initial call configuration: ```js { tool: "bulk_export", arguments: {} } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title", inputSchema: { query: z.string() }, annotations: { readOnlyHint: true }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } @Tool({ name: "bulk_export", description: "Export every support ticket as CSV", inputSchema: {}, annotations: { readOnlyHint: true }, featureFlag: "bulk-export", // ✅ exists only while this flag is on }) export class BulkExport extends ToolContext { async execute() { return { csv: ["id,title,status", ...tickets.map((t) => `${t.id},${t.title},${t.status}`)].join("\n") }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { BulkExport, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, BulkExport], plugins: [FeatureFlagPlugin.init({ adapter: "static", flags: { "bulk-export": false } })], }) export class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; ``` ```ts flag.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { BulkExport, SearchTickets } from "./tools"; test("bulk_export isn't listed while its flag is off", async ({ mcp }) => { const tools = await mcp.tools.list(); expect(tools).not.toContainTool("bulk_export"); expect(tools).toContainTool("search_tickets"); }); test("calling it by name anyway is refused", async ({ mcp }) => { const result = await mcp.tools.call("bulk_export", {}); expect(result).toBeError("FEATURE_FLAG_DISABLED"); expect(result).toHaveTextContent('Tool "bulk_export" is disabled by feature flag "bulk-export"'); expect(result).toHaveTextContent('To fix: Turn on the feature flag "bulk-export" to use this tool.'); }); test("🚩 the class without init() has no adapter, and the server doesn't start", async () => { @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, BulkExport], plugins: [FeatureFlagPlugin] }) class WithoutInit {} const startup = FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [WithoutInit] }); await expect(startup).rejects.toThrow("FeatureFlagPlugin.init() requires an `adapter` option, got undefined."); }); test("🚩 without the plugin, the server doesn't start", async () => { @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, BulkExport] }) class WithoutPlugin {} const startup = FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [WithoutPlugin] }); await expect(startup).rejects.toThrow(`Tool "bulk_export" declares 'featureFlag'`); }); ``` Open the **Capabilities** tab: only `search_tickets` is listed. Now change `false` to `true` in `main.ts`, and `bulk_export` is back, working. - **`featureFlag: "bulk-export"`** names the flag that decides whether the tool exists for this caller. The key is any string; it's the name the flag has in your flag service. - **`FeatureFlagPlugin.init({ adapter, ... })`** registers the plugin. The **adapter** is where flag values come from. `"static"` takes them from `flags`, the same for every caller: good for development, for tests, and for a switch you're happy to change with a deploy. The [last section](https://frontmcp.dev/learn/turning-features-on-and-off#turning-a-flag-on-for-some-callers) connects a flag service. - **A call to a tool whose flag is off** is refused before `execute()` runs, with the message above. That covers clients that call the tool by name, for example from a list they fetched before the flag changed. A tool with `featureFlag` and no plugin to check it is a mistake FrontMCP won't let through: the server refuses to start with `Unenforced metadata: Tool "bulk_export" declares 'featureFlag' (enforced by FeatureFlagPlugin …)`, as the last test shows. FrontMCP refuses, rather than list and run the tool for everyone. > **Pitfall: Register the plugin with init()** > > `FeatureFlagPlugin.init()` with no options, or with an `adapter` it doesn't know, throws a `FeatureFlagConfigurationError` when the module loads, naming the supported adapters. `plugins: [FeatureFlagPlugin]`, the class without `init()`, has no adapter either, so the server doesn't start, with the same error. Always pass the options, with at least `adapter`. (Before FrontMCP 1.9.4 the class started, and then `tools/list` failed for every caller with `Provider "[ref]" is not available`.) > **Note** > > On an `@App`, as here, the plugin checks that app's entries, and those of any app without a feature-flag plugin of its own. On `@FrontMcp`, it checks every app's. [Which entries a plugin gates](https://frontmcp.dev/reference/plugins/feature-flags#which-entries-a-plugin-gates) has the details. ## On by default: kill switches A flag the adapter has no value for counts as off. That's the right default for something new: `bulk_export` stays hidden until someone decides otherwise. For a tool people already depend on, you want the opposite: on, unless someone switches it off in an emergency. Give that tool `featureFlag: { key, defaultValue: true }`: Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Printer on fire" } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a support ticket", inputSchema: { title: z.string() }, // ✅ A kill switch: on unless the flag is set to false featureFlag: { key: "ticket-intake", defaultValue: true }, }) export class CreateTicket extends ToolContext { async execute({ title }: { title: string }) { return { id: "T-4", title, status: "open" }; } } @Tool({ name: "ai_summary", description: "Summarize a ticket's thread", inputSchema: { id: z.string() }, featureFlag: "ai-summary", // new: off until turned on }) export class AiSummary extends ToolContext { async execute({ id }: { id: string }) { return { id, summary: "The customer can't log in since this morning." }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { AiSummary, CreateTicket } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket, AiSummary], plugins: [FeatureFlagPlugin.init({ adapter: "static", flags: {} })], // neither flag has a value }) export class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts defaults.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { AiSummary, CreateTicket } from "./tools"; /** The tools a server lists with these flag values. */ async function listedWith(flags: Record, gateDefaultValue = false) { @App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket, AiSummary], plugins: [FeatureFlagPlugin.init({ adapter: "static", flags, gateDefaultValue })] }) class HelpDesk {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }); const { tools } = await server.listTools(); await server.dispose(); return tools.map((t: { name: string }) => t.name).sort(); } test("a flag with no value is off, unless the tool gives a defaultValue", async ({ mcp }) => { expect((await mcp.tools.list()).map((t: { name: string }) => t.name)).toEqual(["create_ticket"]); }); test("setting the flags turns each tool on or off", async () => { expect(await listedWith({ "ai-summary": true })).toEqual(["ai_summary", "create_ticket"]); expect(await listedWith({ "ticket-intake": false })).toEqual([]); // the kill switch }); test("`gateDefaultValue: true` turns on every flag with no value; a flag set to false stays off", async () => { expect(await listedWith({}, true)).toEqual(["ai_summary", "create_ticket"]); expect(await listedWith({ "ai-summary": false }, true)).toEqual(["create_ticket"]); }); ``` `defaultValue` only fills in when the adapter has no answer for the flag, or fails while a call is checked. A flag set to `false` stays off, whatever the tool's `defaultValue` says, so the kill switch works. "No answer" means the adapter left the flag out: the static adapter does that for keys you didn't configure. LaunchDarkly, Split and Unleash answer every key, with their own default for one they don't know, which is off. So with a flag service, create the kill switch there, set to on. The tool's `defaultValue: true` still matters: if the service fails while a call is checked, the call goes through. (A list fails outright during an outage; see [When the flag service fails](https://frontmcp.dev/reference/plugins/feature-flags#when-the-flag-service-fails).) The plugin can flip that default for every tool at once: `FeatureFlagPlugin.init({ adapter, flags, gateDefaultValue: true })` treats every flag without a value as on, for the tools that don't give a `defaultValue` of their own, as the last test shows. That fails open: a new tool is out for everyone the moment it ships, and those tools stay callable while the flag service is down. Keep the default, `false`, and give each kill switch its own `defaultValue: true`. > **Pitfall: A misspelled flag hides the tool** > > Because a flag without a value is off, a typo is silent: `featureFlag: "bulk_export"` on the tool and `"bulk-export": true` in the flags hides the tool for everyone, with no error. Keep flag keys in one place, like `export const BULK_EXPORT = "bulk-export"`, and use the constant on both sides. ## Flagging resources and prompts `@Resource`, `@ResourceTemplate` and `@Prompt` take `featureFlag` too. The help desk's new insights, a ticket statistics resource and a weekly review prompt, share one flag, `insights`, which is off: Initial call configuration: ```js { resource: "tickets://stats" } ``` ```ts insights.ts active import { Prompt, PromptContext, Resource, ResourceContext, type GetPromptResult } from "@frontmcp/sdk"; @Resource({ name: "ticket_stats", uri: "tickets://stats", mimeType: "application/json", featureFlag: "insights" }) export class TicketStats extends ResourceContext { async execute() { return { open: 2, closed: 1 }; } } @Prompt({ name: "weekly_review", description: "Review the week's support tickets", arguments: [], featureFlag: "insights" }) export class WeeklyReview extends PromptContext { async execute(): Promise { return { messages: [{ role: "user", content: { type: "text", text: "Read tickets://stats and summarize the week." } }] }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { TicketStats, WeeklyReview } from "./insights"; @App({ id: "help-desk", name: "Help Desk", resources: [TicketStats], prompts: [WeeklyReview], plugins: [FeatureFlagPlugin.init({ adapter: "static", flags: { insights: false } })], }) export class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts insights.test.ts import { test, expect } from "@frontmcp/testing"; test("neither is listed", async ({ mcp }) => { expect(await mcp.resources.list()).not.toContainResource("tickets://stats"); expect(await mcp.prompts.list()).toHaveLength(0); }); test("reading the resource is refused with a JSON-RPC error", async ({ mcp }) => { const read = await mcp.raw.request({ method: "resources/read", params: { uri: "tickets://stats" } }); expect(read.error).toMatchObject({ code: -32003, message: 'Resource "ticket_stats" is disabled by feature flag "insights"', data: { code: "FEATURE_FLAG_DISABLED" } }); }); test("so is getting the prompt", async ({ mcp }) => { const prompt = await mcp.raw.request({ method: "prompts/get", params: { name: "weekly_review", arguments: {} } }); expect(prompt.error?.message).toBe('Prompt "weekly_review" is disabled by feature flag "insights"'); }); ``` While a flag is off for the caller: | Request | What the caller gets | | --- | --- | | `tools/list`, `resources/list`, `resources/templates/list`, `prompts/list` | The entry is left out. | | `tools/call` | A tool error with the code `FEATURE_FLAG_DISABLED`: `Tool "bulk_export" is disabled by feature flag "bulk-export"`, followed by the line `To fix: Turn on the feature flag "bulk-export" to use this tool.` | | `resources/read`, `prompts/get` | JSON-RPC error `-32003`, with `data.code` `FEATURE_FLAG_DISABLED`: `Resource "ticket_stats" is disabled by feature flag "insights"`, or the same for a prompt. | Those messages name the flag, and they reach the caller as written, in production too: a refusal is a public error, so a caller who tries a hidden entry by name learns its flag's key. Keep flag keys you don't mind showing. Skills and agents take `featureFlag` too; the [plugin's reference](https://frontmcp.dev/reference/plugins/feature-flags#the-featureflag-option) covers them. > **Note** > > Changed in 1.8.7: a refusal used to be wrapped as an internal error. Its `_meta.code` was `SERVER_ERROR`, a resource or prompt answered `-32603`, in development the text went on with `Original error:` and a stack trace, and in production the caller read `Internal FrontMCP error. Please contact support with error ID: …` instead of the message. ## Turning a flag on for some callers A static adapter gives every caller the same answer. A flag service, like LaunchDarkly, Split or Unleash, answers per caller: on for the help desk team, on for one customer's tenant, on for 10% of users. The plugin asks it on every request, about the caller who sent it, and passes it: - **`userId`**: the caller's id from their token, `this.auth.user.sub`. - **`attributes`**: whatever your `attributesResolver` returns, like the caller's tenant or plan. Here a small custom adapter stands in for the flag service: `bulk-export` is on for the `acme` tenant, and `ai-summary` for the support agent `sam`. The tests call the server in-process as two signed-in agents, `nour` from `acme`, and `sam`, who has no tenant; the Playground's own calls are anonymous: Initial call configuration: ```js { tool: "export_formats", arguments: {} } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { RolloutAdapter } from "./rollout-adapter"; @Tool({ name: "bulk_export", description: "Export every support ticket as CSV", inputSchema: {}, featureFlag: "bulk-export" }) class BulkExport extends ToolContext { async execute() { return { csv: "id,title,status\nT-1,Cannot log in,open" }; } } @Tool({ name: "ai_summary", description: "Summarize a ticket's thread", inputSchema: { id: z.string() }, featureFlag: "ai-summary" }) class AiSummary extends ToolContext { async execute({ id }: { id: string }) { return { id, summary: "The customer can't log in since this morning." }; } } @Tool({ name: "export_formats", description: "List the formats this user can export tickets in", inputSchema: {} }) class ExportFormats extends ToolContext { async execute() { const bulk = await this.featureFlags.isEnabled("bulk-export"); // for this caller return { formats: bulk ? ["pdf", "csv"] : ["pdf"] }; } } @App({ id: "help-desk", name: "Help Desk", tools: [BulkExport, AiSummary, ExportFormats], plugins: [ FeatureFlagPlugin.init({ adapter: "custom", adapterInstance: new RolloutAdapter({ "bulk-export": { tenants: ["acme"] }, "ai-summary": { users: ["sam"] } }), // The caller's tenant, from a claim in their token attributesResolver: (ctx) => ({ tenant: (ctx.authInfo as { user?: { tenant?: string } }).user?.tenant }), }), ], }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }; @FrontMcp(config) export default class Server {} ``` ```ts rollout-adapter.ts import type { FeatureFlagAdapter, FeatureFlagContext, FeatureFlagVariant } from "@frontmcp/plugin-feature-flags"; type Rule = { users?: string[]; tenants?: string[] }; /** Flags that are on for some users and tenants. Stands in for a flag service. */ export class RolloutAdapter implements FeatureFlagAdapter { constructor(private readonly rules: Record) {} async initialize() {} async destroy() {} async isEnabled(flagKey: string, { userId, attributes }: FeatureFlagContext): Promise { const rule = this.rules[flagKey]; if (!rule) return false; return (!!userId && !!rule.users?.includes(userId)) || !!rule.tenants?.includes(String(attributes?.tenant)); } async getVariant(flagKey: string, context: FeatureFlagContext): Promise { const enabled = await this.isEnabled(flagKey, context); return { name: enabled ? "on" : "off", value: enabled, enabled }; } // What lists, calls and this.featureFlags.isEnabled() use. Flags without a rule are left out, so a defaultValue applies to them. async evaluateFlags(flagKeys: string[], context: FeatureFlagContext): Promise> { const results = new Map(); for (const key of flagKeys) { if (key in this.rules) results.set(key, await this.isEnabled(key, context)); } return results; } } ``` ```ts targeting.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; // Two signed-in support agents, with the claims their tokens would carry const nour = { authContext: { user: { sub: "nour", tenant: "acme" } } }; const sam = { authContext: { user: { sub: "sam" } } }; test("each agent sees the tools their flags turn on", async () => { const server = await FrontMcpInstance.createDirect(config); const names = async (as: object) => (await server.listTools(as)).tools.map((t: { name: string }) => t.name).sort(); expect(await names(nour)).toEqual(["bulk_export", "export_formats"]); expect(await names(sam)).toEqual(["ai_summary", "export_formats"]); await server.dispose(); }); test("a tool is refused to an agent whose flag is off", async () => { const server = await FrontMcpInstance.createDirect(config); expect((await server.callTool("bulk_export", {}, nour)).structuredContent).toMatchObject({ csv: expect.any(String) }); await expect(server.callTool("bulk_export", {}, sam)).rejects.toThrow('Tool "bulk_export" is disabled by feature flag "bulk-export"'); await server.dispose(); }); test("this.featureFlags answers for the caller", async () => { const server = await FrontMcpInstance.createDirect(config); expect((await server.callTool("export_formats", {}, nour)).structuredContent).toEqual({ formats: ["pdf", "csv"] }); expect((await server.callTool("export_formats", {}, sam)).structuredContent).toEqual({ formats: ["pdf"] }); await server.dispose(); }); test("an anonymous caller gets neither", async ({ mcp }) => { expect((await mcp.tools.list()).map((t: { name: string }) => t.name)).toEqual(["export_formats"]); }); ``` Open the **Capabilities** tab: the Playground calls anonymously, so it only sees `export_formats`, and gets `["pdf"]` from it. The tests show the other two callers. - **`adapter: "custom"`** with `adapterInstance` takes any object with the adapter's five methods: `init()` throws a `FeatureFlagConfigurationError` when it lacks `isEnabled()`, `getVariant()` or `evaluateFlags()`. `evaluateFlags()` is what lists, calls and `this.featureFlags.isEnabled()` use; leave out a key you have no answer for, so the `defaultValue` applies. - **`attributesResolver`** receives the request's context. `ctx.authInfo.user` holds the claims of the caller's token, like `tenant` here. - **`this.featureFlags`**, which the plugin adds to every tool, resource and prompt of the apps it's registered for, reads a flag inside `execute()`, for the same caller. Use it when a flag changes what a tool does rather than whether it exists, as `export_formats` does. An anonymous caller has no `userId`, so a flag service can't tell one from another: a rollout to 10% of users gives all of them the same answer. Target signed-in callers. With a real flag service, only the adapter changes. For LaunchDarkly, install its SDK (`npm install @launchdarkly/node-server-sdk`) and keep the resolver: ```ts FeatureFlagPlugin.init({ adapter: "launchdarkly", config: { sdkKey: process.env.LAUNCHDARKLY_SDK_KEY! }, attributesResolver: (ctx) => ({ tenant: (ctx.authInfo as { user?: { tenant?: string } }).user?.tenant }), }); ``` `"splitio"` and `"unleash"` work the same way, with their own `config`. [LaunchDarkly, Split and Unleash](https://frontmcp.dev/reference/plugins/feature-flags#launchdarkly-split-and-unleash) lists each one's options, and [When the flag service fails](https://frontmcp.dev/reference/plugins/feature-flags#when-the-flag-service-fails) what happens during an outage. > **Note** > > `this.featureFlags.isEnabled("new-editor", true)` gives `true` for a flag the adapter has no answer for, as `defaultValue` does on an entry, and when the adapter fails. Changed in 1.9: it used its default only when the adapter threw, and the static adapter said `false` for a key it didn't know. ## Recap - A switch inside `execute()` still lists the tool, so the model finds out it's off only by calling it. `featureFlag` on the entry hides it instead. - `@frontmcp/plugin-feature-flags` adds `featureFlag` to tools, resources, resource templates, prompts, skills and agents. Register it with `FeatureFlagPlugin.init({ adapter, ... })`; an entry with `featureFlag` and no plugin stops the server from starting. - While a flag is off for the caller, the entry is left out of lists, and calls, reads and gets are refused. - A flag without a value is off. `featureFlag: { key, defaultValue: true }` makes it on until it's set to `false`, for kill switches. - A flag service answers per caller, from their `userId` and the `attributes` your `attributesResolver` returns. `this.featureFlags` reads a flag inside a tool, for the same caller. - Every option, the adapters, and what happens when the flag service fails are in the [feature flags plugin reference](https://frontmcp.dev/reference/plugins/feature-flags). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Hide the merge tool `merge_tickets` isn't finished, and the plugin already has a `ticket-merge` flag for it, set to `false`. The tool is still listed and still runs. Put it behind the flag. Initial call configuration: ```js { tool: "merge_tickets", arguments: { from: "T-3", into: "T-1" } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Tool({ name: "merge_tickets", description: "Merge a duplicate ticket into another one", inputSchema: { from: z.string(), into: z.string() }, }) export class MergeTickets extends ToolContext { async execute({ from, into }: { from: string; into: string }) { return { merged: from, into }; } } ``` **Solution file (alternative to the starter):** ```ts tools.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Tool({ name: "merge_tickets", description: "Merge a duplicate ticket into another one", inputSchema: { from: z.string(), into: z.string() }, featureFlag: "ticket-merge", }) export class MergeTickets extends ToolContext { async execute({ from, into }: { from: string; into: string }) { return { merged: from, into }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { GetTicket, MergeTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, MergeTickets], plugins: [FeatureFlagPlugin.init({ adapter: "static", flags: { "ticket-merge": false } })], }) export class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts merge.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`merge_tickets` isn't listed", async ({ mcp }) => { expect(await mcp.tools.list()).not.toContainTool("merge_tickets"); }); test("calling it is refused by the `ticket-merge` flag", async ({ mcp }) => { const result = await mcp.tools.call("merge_tickets", { from: "T-3", into: "T-1" }); expect(result).toBeError(); expect(result).toHaveTextContent('disabled by feature flag "ticket-merge"'); }); test("`get_ticket` is still listed and works", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("get_ticket"); expect(await mcp.tools.call("get_ticket", { id: "T-1" })).toBeSuccessful(); }); ``` **Hint:** The flag's value is already in `main.ts`. What's missing is the link from the tool to the flag's key. **Solution:** `featureFlag: "ticket-merge"` ties the tool to the flag, and the plugin, already registered on the app, does the rest: while the flag is `false`, `merge_tickets` is left out of `tools/list` and refused when called by name. Setting the flag to `true` in `main.ts` brings it back without touching the tool. ### Challenge: Make ticket intake a kill switch Someone put `create_ticket` behind a `ticket-intake` flag, so it can be switched off if the ticket database struggles. But the flags in `main.ts` don't set it, so the tool vanished for everyone. Make `create_ticket` stay on while the flag has no value, and still go away when the flag is set to `false`. Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Printer on fire" } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a support ticket", inputSchema: { title: z.string() }, featureFlag: "ticket-intake", }) export class CreateTicket extends ToolContext { async execute({ title }: { title: string }) { return { id: "T-4", title, status: "open" }; } } ``` **Solution file (alternative to the starter):** ```ts tools.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a support ticket", inputSchema: { title: z.string() }, featureFlag: { key: "ticket-intake", defaultValue: true }, }) export class CreateTicket extends ToolContext { async execute({ title }: { title: string }) { return { id: "T-4", title, status: "open" }; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { CreateTicket } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], plugins: [FeatureFlagPlugin.init({ adapter: "static", flags: {} })], }) export class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts intake.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { CreateTicket } from "./tools"; async function listedWith(flags: Record) { @App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], plugins: [FeatureFlagPlugin.init({ adapter: "static", flags })] }) class HelpDesk {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }); const { tools } = await server.listTools(); await server.dispose(); return tools.map((t: { name: string }) => t.name); } test("with no value for `ticket-intake`, `create_ticket` is listed and works", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("create_ticket"); expect(await mcp.tools.call("create_ticket", { title: "Printer on fire" })).toBeSuccessful(); expect(await listedWith({})).toEqual(["create_ticket"]); }); test("setting `ticket-intake` to false still switches it off", async () => { expect(await listedWith({ "ticket-intake": false })).toEqual([]); }); ``` **Hint:** `featureFlag` also takes an object, with the key and what to assume when the adapter has no value for it. **Solution:** `featureFlag: { key: "ticket-intake", defaultValue: true }` treats a flag without a value as on, so the tool is back for everyone. A value of `false` still wins over `defaultValue`, so the switch still works. Adding `"ticket-intake": true` to `main.ts` would bring the tool back too, but only for that one configuration: the checks also start servers whose flags don't set it. The default belongs on the tool. ### Challenge: Roll out bulk export to one tenant The rollout adapter turns `bulk-export` on for the `acme` tenant, and `nour`'s token says she's from `acme`. But she doesn't see `bulk_export`: the adapter never learns her tenant. Pass it on, from the `tenant` claim of the caller's token. Initial call configuration: ```js { tool: "search_tickets", arguments: {} } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { RolloutAdapter } from "./rollout-adapter"; @Tool({ name: "search_tickets", description: "Search support tickets", inputSchema: {} }) class SearchTickets extends ToolContext { async execute() { return { tickets: ["T-1", "T-3"] }; } } @Tool({ name: "bulk_export", description: "Export every support ticket as CSV", inputSchema: {}, featureFlag: "bulk-export" }) class BulkExport extends ToolContext { async execute() { return { csv: "id,title,status\nT-1,Cannot log in,open" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, BulkExport], plugins: [ FeatureFlagPlugin.init({ adapter: "custom", adapterInstance: new RolloutAdapter({ "bulk-export": { tenants: ["acme"] } }), }), ], }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }; @FrontMcp(config) export default class Server {} ``` **Solution file (alternative to the starter):** ```ts main.ts solution import { App, FrontMcp, Tool, ToolContext } from "@frontmcp/sdk"; import { FeatureFlagPlugin } from "@frontmcp/plugin-feature-flags"; import { RolloutAdapter } from "./rollout-adapter"; @Tool({ name: "search_tickets", description: "Search support tickets", inputSchema: {} }) class SearchTickets extends ToolContext { async execute() { return { tickets: ["T-1", "T-3"] }; } } @Tool({ name: "bulk_export", description: "Export every support ticket as CSV", inputSchema: {}, featureFlag: "bulk-export" }) class BulkExport extends ToolContext { async execute() { return { csv: "id,title,status\nT-1,Cannot log in,open" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, BulkExport], plugins: [ FeatureFlagPlugin.init({ adapter: "custom", adapterInstance: new RolloutAdapter({ "bulk-export": { tenants: ["acme"] } }), attributesResolver: (ctx) => ({ tenant: (ctx.authInfo as { user?: { tenant?: string } }).user?.tenant }), }), ], }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }; @FrontMcp(config) export default class Server {} ``` ```ts rollout-adapter.ts import type { FeatureFlagAdapter, FeatureFlagContext, FeatureFlagVariant } from "@frontmcp/plugin-feature-flags"; type Rule = { users?: string[]; tenants?: string[] }; /** Flags that are on for some users and tenants. Stands in for a flag service. */ export class RolloutAdapter implements FeatureFlagAdapter { constructor(private readonly rules: Record) {} async initialize() {} async destroy() {} async isEnabled(flagKey: string, { userId, attributes }: FeatureFlagContext): Promise { const rule = this.rules[flagKey]; if (!rule) return false; return (!!userId && !!rule.users?.includes(userId)) || !!rule.tenants?.includes(String(attributes?.tenant)); } async getVariant(flagKey: string, context: FeatureFlagContext): Promise { const enabled = await this.isEnabled(flagKey, context); return { name: enabled ? "on" : "off", value: enabled, enabled }; } async evaluateFlags(flagKeys: string[], context: FeatureFlagContext): Promise> { const results = new Map(); for (const key of flagKeys) { if (key in this.rules) results.set(key, await this.isEnabled(key, context)); } return results; } } ``` **Hidden fixture/test file (runs with the example):** ```ts rollout.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; const nour = { authContext: { user: { sub: "nour", tenant: "acme" } } }; const sam = { authContext: { user: { sub: "sam", tenant: "globex" } } }; async function listedFor(as: object) { const server = await FrontMcpInstance.createDirect(config); const { tools } = await server.listTools(as); await server.dispose(); return tools.map((t: { name: string }) => t.name).sort(); } test("`nour`, from acme, sees `bulk_export`", async () => { expect(await listedFor(nour)).toEqual(["bulk_export", "search_tickets"]); }); test("`sam`, from another tenant, doesn't", async () => { expect(await listedFor(sam)).toEqual(["search_tickets"]); }); test("neither does an anonymous caller", async ({ mcp }) => { expect(await mcp.tools.list()).not.toContainTool("bulk_export"); }); ``` **Hint:** The adapter checks `attributes.tenant`. Which plugin option decides what `attributes` holds? **Solution:** `attributesResolver` runs on every request, and what it returns reaches the adapter as `attributes`. Reading `tenant` from `ctx.authInfo.user`, the caller's token claims, gives the adapter `acme` for `nour`, so `bulk-export` is on for her, and something else, or nothing, for everyone else. --- # Letting the Model Write Code with CodeCall > Why long tool lists cost a model, and how @frontmcp/plugin-codecall lets it search tools, read their schemas and call them directly or from a short server-side script. Source: https://frontmcp.dev/learn/letting-the-model-write-code-with-codecall [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Every tool you add is one more name, description and schema that the model reads before it answers anything. At a dozen tools that's nothing. At a few hundred, the list crowds the model's context, similar tools blur together, and a task that takes five calls takes five round trips, with every result passing through the model. `@frontmcp/plugin-codecall` changes what a FrontMCP server shows the model: instead of your tools, a few CodeCall tools that it uses to search yours, read the ones it needs, and call them, one at a time or from a short script that runs on your server and sends back only the answer. **You will learn** - What a long tool list costs a model - How to put your tools behind CodeCall, and when it's worth it - How the model finds tools with `codecall:search` and reads them with `codecall:describe` - How it calls them, one with `codecall:invoke`, or several from a `codecall:execute` script - What a script may do, and how to keep tools out of its reach ## A server with too many tools The help desk has grown. It has seven areas now, tickets, customers, invoices, agents, macros, articles and SLA policies, each with five actions. That's 35 tools, written here with a loop to keep the example short. Open the **Tests** tab: ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; const areas = ["ticket", "customer", "invoice", "agent", "macro", "article", "sla policy"]; const actions: [string, (area: string) => string][] = [ ["list", (area) => `List ${area}s, newest first. Filter by status and page through the results.`], ["get", (area) => `Get one ${area} by its id, with every field.`], ["create", (area) => `Create a new ${area}. Returns the new record with its id.`], ["update", (area) => `Update the fields of one ${area}. Fields you leave out keep their value.`], ["delete", (area) => `Delete one ${area}. This can't be undone.`], ]; export const helpDeskTools = areas.flatMap((area) => actions.map(([action, describe]) => { @Tool({ name: `${action}_${area.replace(" ", "_")}`, description: describe(area), inputSchema: { id: z.string().optional().describe(`The ${area}'s id`), status: z.enum(["open", "pending", "closed"]).optional().describe("Only records with this status"), page: z.number().int().min(1).optional().describe("Page number, from 1"), pageSize: z.number().int().min(1).max(100).optional().describe("Records per page, up to 100"), }, }) class AreaTool extends ToolContext { async execute(input: { id?: string; status?: "open" | "pending" | "closed"; page?: number; pageSize?: number }) { return { action, area, ...input }; } } return AreaTool; }), ); ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { helpDeskTools } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: helpDeskTools }) export class HelpDeskApp {} ``` ```ts list.test.ts import { test, expect } from "@frontmcp/testing"; test("🚩 the model is sent all 35 tools, every schema included", async ({ mcp }) => { const tools = await mcp.tools.list(); expect(tools).toHaveLength(35); expect(JSON.stringify(tools).length).toBeGreaterThan(19_000); // about 20 KB }); test("🚩 and the tools look alike", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name); expect(names.filter((name: string) => name.endsWith("_ticket"))).toEqual([ "create_ticket", "delete_ticket", "get_ticket", "list_ticket", "update_ticket", ]); }); ``` Nothing here is wrong, and a client lists all 35 tools. Open the **Capabilities** tab and scroll: that's what the model reads before every answer, about 20 KB of names, descriptions and schemas, and each new tool adds half a kilobyte more. Three problems grow with the list: 1. **Context.** The whole list is sent with every request to the model, whether the conversation needs one tool or none. At 200 tools it's over 100 KB. 2. **Choice.** The more tools look alike, the more often the model picks the wrong one, or calls two to be sure. 3. **Round trips.** "Which urgent tickets are open, and whose are they?" takes a search and then a customer lookup per ticket. Each call is a round trip through the model, and each result, every field of every ticket, lands in its context, where it stays. ## Putting the tools behind CodeCall Install the plugin: ```bash npm install @frontmcp/plugin-codecall ``` It needs Node 24 or later. Then register it on the app: Initial call configuration: ```js { tool: "codecall:search", arguments: { queries: ["update ticket", "list invoices"] } } ``` ```ts help-desk.app.ts active import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { helpDeskTools } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: helpDeskTools, plugins: [CodeCallPlugin.init({ mode: "codecall_only" })], }) export class HelpDeskApp {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const areas = ["ticket", "customer", "invoice", "agent", "macro", "article", "sla policy"]; const actions: [string, (area: string) => string][] = [ ["list", (area) => `List ${area}s, newest first. Filter by status and page through the results.`], ["get", (area) => `Get one ${area} by its id, with every field.`], ["create", (area) => `Create a new ${area}. Returns the new record with its id.`], ["update", (area) => `Update the fields of one ${area}. Fields you leave out keep their value.`], ["delete", (area) => `Delete one ${area}. This can't be undone.`], ]; export const helpDeskTools = areas.flatMap((area) => actions.map(([action, describe]) => { @Tool({ name: `${action}_${area.replace(" ", "_")}`, description: describe(area), inputSchema: { id: z.string().optional().describe(`The ${area}'s id`), status: z.enum(["open", "pending", "closed"]).optional().describe("Only records with this status"), page: z.number().int().min(1).optional().describe("Page number, from 1"), pageSize: z.number().int().min(1).max(100).optional().describe("Records per page, up to 100"), }, }) class AreaTool extends ToolContext { async execute(input: { id?: string; status?: "open" | "pending" | "closed"; page?: number; pageSize?: number }) { return { action, area, ...input }; } } return AreaTool; }), ); ``` ```ts codecall.test.ts import { test, expect } from "@frontmcp/testing"; import { create } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { helpDeskTools } from "./tools"; test("tools/list shows CodeCall's tools instead of the app's", async ({ mcp }) => { expect((await mcp.tools.list()).map((t: { name: string }) => t.name)).toEqual([ "codecall:describe", "codecall:execute", "codecall:invoke", "codecall:search", "codecall:searchKnowledge", "codecall:searchSkills", ]); }); test("the list is the same size, however many tools are behind it", async ({ mcp }) => { const small = await create({ info: { name: "help-desk", version: "1.0.0" }, tools: helpDeskTools.slice(0, 5), plugins: [CodeCallPlugin.init({ mode: "codecall_only" })], }); const fiveTools = (await small.listTools()).tools; await small.dispose(); expect(JSON.stringify(await mcp.tools.list()).length).toBe(JSON.stringify(fiveTools).length); }); test("CodeCall can use all 35 tools, and finds them", async ({ mcp }) => { const { tools, totalAvailableTools } = (await mcp.tools.call("codecall:search", { queries: ["update ticket", "list invoices"] })).json(); expect(totalAvailableTools).toBe(35); expect(tools.slice(0, 2).map((t: { name: string }) => t.name).sort()).toEqual(["list_invoice", "update_ticket"]); }); ``` Open **Capabilities** again: the app's 35 tools are gone from the list, and CodeCall's six are there instead. The **Call** tab shows the model searching for two of the tools it can no longer see. The model now works in steps: | Tool | What the model does with it | | --- | --- | | `codecall:search` | Finds tools for short phrases, like `"close ticket"`. | | `codecall:describe` | Reads the input and output schemas of the tools it picked. | | `codecall:invoke` | Calls one tool, and gets its result. | | `codecall:execute` | Runs a short script that calls several tools, and gets what the script returns. | | `codecall:searchSkills`, `codecall:searchKnowledge` | Search the server's [skills](https://frontmcp.dev/learn/teaching-the-model-skills). | Each has a long description written for the model, which explains that flow. Every tool call still goes through FrontMCP's normal flow, with the caller's credentials: validation, hooks and [authorization](https://frontmcp.dev/learn/authorizing-calls) all apply, as for a direct call. `mode: "codecall_only"` is the default, and the usual choice: CodeCall's tools are listed, yours aren't. `"codecall_opt_in"` lists every tool as before and lets CodeCall use only the ones marked `codecall: { enabledInCodeCall: true }`, which is a way to try CodeCall on a server whose clients already use the tools directly. In `codecall_only`, a client can't call your tools directly any more: a `tools/call` for one that isn't listed gets `Tool "…" not found`. [Modes](https://frontmcp.dev/reference/plugins/codecall#modes) lists all three. > **Pitfall: CodeCall's own tools aren't small** > > Those six descriptions and schemas come to about 21 KB, what 35 to 40 small tools like these take, and it stays that size however many tools are behind them. For a server with a dozen tools, list them directly: CodeCall costs the model more than it saves. It pays off when your own list is bigger than that, or when the model's tasks need several calls in a row. > **Note** > > It makes no difference whether you register CodeCall on one `@App` or on `@FrontMcp`: either way it hides every app's tools from `tools/list`, and its tools search and call every app's tools. [`appIds`](https://frontmcp.dev/reference/plugins/codecall#several-apps-on-one-server) limits the hiding to the apps you name. ## Finding tools: search, then describe The rest of this lesson uses a smaller help desk, with real tickets and customers, so there's something to find. `codecall:search` takes one or more short phrases, searches for each on its own, and merges the results, best first: Initial call configuration: ```js { tool: "codecall:search", arguments: { queries: ["close ticket", "refund invoice"] } } ``` ```ts tools.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open", priority: "high", customerId: "C-1" }, { id: "T-2", title: "Invoice shows the wrong total", status: "open", priority: "low", customerId: "C-2" }, { id: "T-3", title: "Export times out", status: "open", priority: "high", customerId: "C-2" }, { id: "T-4", title: "Password reset email never arrives", status: "closed", priority: "high", customerId: "C-1" }, ]; const customers = [ { id: "C-1", name: "Acme Corp", plan: "enterprise" }, { id: "C-2", name: "Globex", plan: "starter" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by status and priority", inputSchema: { status: z.enum(["open", "closed"]).optional(), priority: z.enum(["low", "high"]).optional() }, }) export class SearchTickets extends ToolContext { async execute({ status, priority }: { status?: "open" | "closed"; priority?: "low" | "high" }) { return { tickets: tickets.filter((t) => (!status || t.status === status) && (!priority || t.priority === priority)) }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().describe("A ticket id, like T-1") }, examples: [{ description: "Look up the ticket about logging in", input: { id: "T-1" } }], }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return ticket; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "get_customer", description: "Get a customer account by its id", inputSchema: { id: z.string() } }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return customers.find((c) => c.id === id) ?? this.fail(new PublicMcpError(`There's no customer ${id}.`)); } } @Tool({ name: "refund_invoice", description: "Refund an invoice in full", inputSchema: { invoiceId: z.string() } }) export class RefundInvoice extends ToolContext { async execute({ invoiceId }: { invoiceId: string }) { return { invoiceId, status: "refunded" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { CloseTicket, GetCustomer, GetTicket, RefundInvoice, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, GetTicket, CloseTicket, GetCustomer, RefundInvoice], plugins: [CodeCallPlugin.init({ mode: "codecall_only" })], }) export class HelpDeskApp {} ``` ```ts find.test.ts import { test, expect } from "@frontmcp/testing"; const search = async (mcp: any, queries: string[]) => (await mcp.tools.call("codecall:search", { queries })).json(); test("each phrase finds its tool, best first", async ({ mcp }) => { const { tools } = await search(mcp, ["close ticket", "refund invoice"]); expect(tools[0]).toMatchObject({ name: "close_ticket", matchedQueries: ["close ticket"] }); expect(tools[1]).toMatchObject({ name: "refund_invoice", matchedQueries: ["refund invoice"] }); }); test("🚩 search matches words, not meaning", async ({ mcp }) => { expect((await search(mcp, ["give money back"])).tools).toEqual([]); }); test("codecall:describe returns the JSON Schema, with each field's description", async ({ mcp }) => { const { tools } = (await mcp.tools.call("codecall:describe", { toolNames: ["get_ticket"] })).json(); expect(tools[0].inputSchema.properties.id).toEqual({ type: "string", description: "A ticket id, like T-1" }); expect(tools[0].usageExamples).toEqual([ { description: "Look up the ticket about logging in", code: 'const result = await callTool(\'get_ticket\', {\n "id": "T-1"\n});\nreturn result;', }, ]); }); test("without examples, CodeCall writes one from the tool's schema", async ({ mcp }) => { const { tools } = (await mcp.tools.call("codecall:describe", { toolNames: ["search_tickets"] })).json(); expect(Object.keys(tools[0].inputSchema.properties)).toEqual(["status", "priority"]); expect(tools[0].usageExamples).toEqual([ { description: "Search for search_tickets", code: 'const results = await callTool(\'search_tickets\', {\n "status": "open"\n});\nreturn results.items || results;', }, ]); }); ``` - **Search matches words**, from each tool's name (split on `_`, `-`, `:` and `.`), its description, its `tags`, the names of its input fields and its `examples`. Built-in synonyms help (`add` also finds `create`), but words aren't reduced to their stem, so `ticket` doesn't find `tickets`, and a phrase in other words, like `give money back`, finds nothing. Write descriptions with the words a model would search for. - **Each result** has the tool's `name`, `description`, `appId`, a `relevanceScore` from 0 to 1, and `matchedQueries`, the phrases that found it. `totalAvailableTools` counts the tools CodeCall may use. - **`codecall:describe`** takes the names the model picked and returns each tool's input and output schema as JSON Schema, with the text of each field's `.describe()`, and some usage examples. A name CodeCall doesn't have comes back in `notFound`. CodeCall caches the results of `codecall:search` and `codecall:describe` for 60 seconds per signed-in caller, with the [Cache plugin](https://frontmcp.dev/learn/caching-results) it brings along. After you change a tool, a caller who asked about it in the last minute gets the old answer until then. Anonymous MCP 2026-07-28 callers, like the Playground's, skip cache reads and writes; anonymous callers on older revisions can reuse entries within a session the server verified. > **Note** > > `codecall:describe` gives a tool's own [`examples`](https://frontmcp.dev/reference/sdk/tool#options) as its usage examples, and shows only those. A tool without any gets one that CodeCall writes from its name and input schema: it uses only properties the schema declares, like `status`, with the first value of the enum, for `search_tickets`. That's a valid call, but a guess at what the model wants. Give a tool an example of the call you'd make, and that's the one the model copies. ## Calling one tool: `codecall:invoke` Once the model knows a tool's schema, `codecall:invoke` calls it and returns the tool's own result, errors included: Initial call configuration: ```js { tool: "codecall:invoke", arguments: { tool: "get_ticket", input: { id: "T-1" } } } ``` ```ts help-desk.app.ts active import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { CloseTicket, GetCustomer, GetTicket, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, GetTicket, CloseTicket, GetCustomer], plugins: [CodeCallPlugin.init({ mode: "codecall_only" })], }) export class HelpDeskApp {} ``` ```ts tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open", priority: "high", customerId: "C-1" }, { id: "T-2", title: "Invoice shows the wrong total", status: "open", priority: "low", customerId: "C-2" }, { id: "T-3", title: "Export times out", status: "open", priority: "high", customerId: "C-2" }, { id: "T-4", title: "Password reset email never arrives", status: "closed", priority: "high", customerId: "C-1" }, ]; const customers = [ { id: "C-1", name: "Acme Corp", plan: "enterprise" }, { id: "C-2", name: "Globex", plan: "starter" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by status and priority", inputSchema: { status: z.enum(["open", "closed"]).optional(), priority: z.enum(["low", "high"]).optional() }, }) export class SearchTickets extends ToolContext { async execute({ status, priority }: { status?: "open" | "closed"; priority?: "low" | "high" }) { return { tickets: tickets.filter((t) => (!status || t.status === status) && (!priority || t.priority === priority)) }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().describe("A ticket id, like T-1") } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return ticket; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "get_customer", description: "Get a customer account by its id", inputSchema: { id: z.string() } }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return customers.find((c) => c.id === id) ?? this.fail(new PublicMcpError(`There's no customer ${id}.`)); } } ``` ```ts invoke.test.ts import { test, expect } from "@frontmcp/testing"; test("it returns the tool's own result", async ({ mcp }) => { const result = await mcp.tools.call("codecall:invoke", { tool: "get_ticket", input: { id: "T-1" } }); expect(result.json()).toMatchObject({ id: "T-1", title: "Cannot log in", status: "open" }); }); test("and the tool's own error", async ({ mcp }) => { const result = await mcp.tools.call("codecall:invoke", { tool: "get_ticket", input: { id: "T-9" } }); expect(result).toBeError(); expect(result).toHaveTextContent("There's no ticket T-9."); }); test("a tool CodeCall doesn't have is refused, with a hint", async ({ mcp }) => { const result = await mcp.tools.call("codecall:invoke", { tool: "delete_everything", input: {} }); expect(result).toHaveTextContent('Tool "delete_everything" is not available. Use codecall:search to discover available tools.'); }); ``` ```ts script.test.ts import { test, expect } from "@frontmcp/testing"; const run = async (mcp: any, script: string) => (await mcp.tools.call("codecall:execute", { script })).json(); test("a script joins tools and returns only the answer", async ({ mcp }) => { const script = [ 'const { tickets } = await callTool("search_tickets", { status: "open", priority: "high" });', "const out = [];", "for (const t of tickets) {", ' const customer = await callTool("get_customer", { id: t.customerId });', " out.push({ ticket: t.id, title: t.title, customer: customer.name });", "}", "return out;", ].join("\n"); expect(await run(mcp, script)).toEqual({ status: "ok", result: [ { ticket: "T-1", title: "Cannot log in", customer: "Acme Corp" }, { ticket: "T-3", title: "Export times out", customer: "Globex" }, ], }); }); test("parallel() fetches the customers at once", async ({ mcp }) => { const script = [ 'const { tickets } = await callTool("search_tickets", { status: "open" });', 'const owners = await parallel(tickets, (t) => callTool("get_customer", { id: t.customerId }));', "return tickets.map((t, i) => `${t.id}: ${owners[i].name}`);", ].join("\n"); expect(await run(mcp, script)).toEqual({ status: "ok", result: ["T-1: Acme Corp", "T-2: Globex", "T-3: Globex"] }); }); test("a script that reads and then deletes is stopped by the sandbox", async ({ mcp }) => { const script = 'const customer = await callTool("get_customer", { id: "C-2" });\nreturn await callTool("delete_customer", { id: customer.id });'; expect(await run(mcp, script)).toEqual({ status: "runtime_error", error: { source: "script", message: "Suspicious pattern detected: Delete operation after data access (potential cover-up) [DELETE_AFTER_ACCESS]", name: "Error", }, }); }); test("a thrown public error keeps the tool's message in the script", async ({ mcp }) => { const caught = 'try {\n return await callTool("get_ticket", { id: "T-9" });\n} catch (error) {\n return { failed: error.message };\n}'; expect(await run(mcp, caught)).toEqual({ status: "ok", result: { failed: "There's no ticket T-9." } }); expect(await run(mcp, 'return await callTool("get_ticket", { id: "T-9" });')).toEqual({ status: "tool_error", error: { source: "tool", toolName: "get_ticket", message: "There's no ticket T-9.", code: "EXECUTION" }, }); }); ``` That's the same result the model would get from calling `get_ticket` directly, so for a single call nothing changes but the path. Try `T-9` in the Call tab: the tool's error message comes through too. ## Several calls in one script: `codecall:execute` "Which urgent tickets are open, and whose are they?" needs a search and then one customer lookup per ticket. With `codecall:execute`, the model writes those calls as a short JavaScript program and sends it in one request. The script runs on your server, and only what it returns goes back to the model: ```js const { tickets } = await callTool("search_tickets", { status: "open", priority: "high" }); const out = []; for (const t of tickets) { const customer = await callTool("get_customer", { id: t.customerId }); out.push({ ticket: t.id, title: t.title, customer: customer.name }); } return out; ``` Here are the tools above again, with `codecall:execute` already called with that script. It's in the **Call** tab's `script` field: change it and send it again. **Reuses runnable project: help-desk.** Initial call configuration: ```js { tool: "codecall:execute", arguments: { script: [ 'const { tickets } = await callTool("search_tickets", { status: "open", priority: "high" });', 'const out = [];', 'for (const t of tickets) {', ' const customer = await callTool("get_customer", { id: t.customerId });', ' out.push({ ticket: t.id, title: t.title, customer: customer.name });', '}', 'return out;', ].join("\n") } } ``` `codecall:execute` answers: ```json { "status": "ok", "result": [ { "ticket": "T-1", "title": "Cannot log in", "customer": "Acme Corp" }, { "ticket": "T-3", "title": "Export times out", "customer": "Globex" } ] } ``` Three tool calls, one round trip, and the model reads two short lines instead of every field of every ticket and customer. The script is the body of an `async` function: it uses `await` at the top level and `return`s its answer. - **`callTool(name, input)`** calls a tool through the same flow as a direct call, with the caller's credentials, and returns the object the tool returned. - **`parallel(items, fn)`** runs calls at once, like `Promise.all`, for up to 100 items. - **`mcpLog(level, message)`** adds a line to the result's `logs`. `console` is off by default; a server can [enable it explicitly](https://frontmcp.dev/reference/plugins/codecall#sending-script-console-output-to-the-server) to log on the server instead. - **`status`** says how the script ended: `ok` with a `result`, or `syntax_error`, `illegal_access`, `tool_error`, `runtime_error` or `timeout`, with an `error`. `codecall:execute` answers with such an object whatever happens to the script, so the model can read what went wrong and try again. Only input that doesn't fit its schema, like a script under 23 characters, is an error result. The same question with `parallel()`, which fetches the customers at once: ```js const { tickets } = await callTool("search_tickets", { status: "open" }); const owners = await parallel(tickets, (t) => callTool("get_customer", { id: t.customerId })); return tickets.map((t, i) => `${t.id}: ${owners[i].name}`); // { "status": "ok", "result": ["T-1: Acme Corp", "T-2: Globex", "T-3: Globex"] } ``` > **Note: The Playground runs scripts in a browser sandbox** > > A server runs a script in a sandbox built on Node's `vm` module, which a browser doesn't have, so the Playground runs it in Enclave's browser sandbox: two nested iframes with no network and no `eval`. The checks and the tool calls are the same, and the tests on this page pass on Node and in the browser. A few things differ, like `getTool()`, which only answers for names written in the script. [In the Playground](https://frontmcp.dev/reference/plugins/codecall#in-the-playground) lists them. ## What a script may do A script is code a model wrote, so CodeCall treats it as untrusted. It runs a subset of JavaScript called **AgentScript**, and checks each script before running any of it. Anything outside the subset is refused with `illegal_access`, and nothing in the script runs, not even the tool calls before the refused line. Checking works in the Playground too, so the tests here try some refused scripts. Add your own: Initial call configuration: ```js { tool: "codecall:execute", arguments: { script: "let page = 1;\nwhile (page < 3) { page++; }\nreturn callTool('search_tickets', {});" } } ``` ```ts refused.test.ts active import { test, expect } from "@frontmcp/testing"; import { closed } from "./tools"; const run = async (mcp: any, script: string) => (await mcp.tools.call("codecall:execute", { script })).json(); test("while loops are refused; use for…of", async ({ mcp }) => { const result = await run(mcp, "let page = 1;\nwhile (page < 3) { page++; }\nreturn callTool('search_tickets', {});"); expect(result.status).toBe("illegal_access"); expect(result.error.message).toContain("FORBIDDEN_LOOP (line 2): Only for-of loops are allowed (vm.allowLoops is false) (while loop)"); }); test("so are counting for loops, in the default preset", async ({ mcp }) => { const result = await run(mcp, "let n = 0;\nfor (let i = 0; i < 3; i++) { n += i; }\nreturn callTool('search_tickets', {});"); expect(result.error.message).toContain("FORBIDDEN_LOOP (line 2): Only for-of loops are allowed (vm.allowLoops is false) (for loop)"); }); test("function declarations are refused; use arrow functions", async ({ mcp }) => { const result = await run(mcp, "function isOpen(t) { return t.status === 'open'; }\nreturn callTool('search_tickets', {});"); expect(result.error.message).toContain("NO_USER_FUNCTION_DECLARATION"); }); test("console is off by default; use mcpLog()", async ({ mcp }) => { const result = await run(mcp, "console.log('hi');\nreturn callTool('search_tickets', {});"); expect(result.error.message).toContain("DISALLOWED_IDENTIFIER (line 1): console is not available in CodeCall scripts unless vm.allowConsole is true; use mcpLog(level, message)"); }); test("eval, process and constructor tricks are refused", async ({ mcp }) => { for (const script of [ "return eval(\"callTool('search_tickets', {})\");", "const env = process.env;\nreturn callTool('search_tickets', {});", "return [].constructor.constructor('return process')();", ]) { expect((await run(mcp, script)).status).toBe("illegal_access"); } }); test("a refused script has no effect at all", async ({ mcp }) => { const result = await run(mcp, "await callTool('close_ticket', { id: 'T-2' });\nwhile (true) {}\nreturn 1;"); expect(result.status).toBe("illegal_access"); expect(closed).toEqual([]); // close_ticket never ran }); test("a script shorter than 23 characters is an error result", async ({ mcp }) => { expect(await mcp.tools.call("codecall:execute", { script: "return 1 + 1" })).toBeError("INVALID_INPUT"); }); ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; export const closed: string[] = []; @Tool({ name: "search_tickets", description: "Search support tickets by status", inputSchema: { status: z.enum(["open", "closed"]).optional() } }) export class SearchTickets extends ToolContext { async execute(_input: { status?: "open" | "closed" }) { return { tickets: [{ id: "T-1", status: "open" }, { id: "T-2", status: "open" }] }; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { closed.push(id); return { id, status: "closed" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { CloseTicket, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, CloseTicket], plugins: [CodeCallPlugin.init({ mode: "codecall_only" })] }) export class HelpDeskApp {} ``` | A script may use | It may not use | | --- | --- | | `const`, `let`, `if`, `for…of` (with `break` and `continue`), `try`/`catch`, `throw` | `for (…; …; …)`, unless the server sets `vm.allowLoops`; `while`, `do…while`, `for…in` | | Arrow functions, also `async` | `function` declarations and expressions, `class` | | `callTool()`, `parallel()`, `getTool()`, `mcpLog()`, `mcpNotify()` | `console` unless the server sets `vm.allowConsole: true`; `fetch`, `setTimeout`, `process`, `require`, `import()`, `globalThis` | | `Math`, `JSON`, `Object`, `Array`, `String`, `Number`, `Date`, and their methods | `eval`, `Function`, `.constructor`, `__proto__`, regular expressions, `Promise`, `Map`, `Set`, `Error` | A tool's name in `callTool()` must be a string literal: `callTool(name, …)` with a variable is refused. So is a script with a line over 2,000 characters (`PRESCANNER_LINE_TOO_LONG`), or with a BiDi control character, one that changes the direction of text, even in a string or a comment (`PRESCANNER_BIDI_ATTACK`). To throw an error of your own, `throw "message"`. [AgentScript](https://frontmcp.dev/reference/plugins/codecall#agentscript) lists every rule. A script that passes the checks runs in a fresh sandbox, within limits set by the `vm` option's preset (`secure` by default): | Limit | `secure` | When it's reached | | --- | --- | --- | | Execution time | 3.5 seconds | The script ends with `timeout`; a pending tool gets another 3.5 seconds to finish. Changed in 1.12.1: before, tool waits had no such bound. | | Tool calls | 5,000 per script | `runtime_error`: `Maximum tool call limit exceeded (5000). …` | | Loop iterations | 10,000 per loop, in every preset | `runtime_error`: `Maximum iteration limit exceeded (10000). This limit prevents infinite loops.` | | Items in `parallel()` | 100 | `runtime_error`: `parallel() is limited to 100 items` | [`vm`](https://frontmcp.dev/reference/plugins/codecall#vm) lists the other presets. > **Pitfall: The sandbox stops scripts that look like an attack** > > While a script runs, the sandbox watches the order of its tool calls by tool name, and stops patterns an attacker would use: a `delete…` call soon after a read, a `send…` or `export…` call after a `list…`, and a few more. They match parts of names, so ordinary scripts trip them too. This script, which looks up a customer and deletes it, > > ```js > const customer = await callTool("get_customer", { id: "C-2" }); > return await callTool("delete_customer", { id: customer.id }); > ``` > > ends with `{ "status": "runtime_error", "error": { "source": "script", "message": "Suspicious pattern detected: Delete operation after data access (potential cover-up) [DELETE_AFTER_ACCESS]", "name": "Error" } }`. CodeCall has no option to turn this off. Split such work over two requests, or make the second call with `codecall:invoke`. [Limits](https://frontmcp.dev/reference/plugins/codecall#limits) lists every pattern. ### When a tool fails inside a script A failed call throws, and a script can catch it. A thrown public error keeps the tool's message, without stack frames or server paths: ```js try { return await callTool("get_ticket", { id: "T-9" }); } catch (error) { return { failed: error.message }; } // { "status": "ok", "result": { "failed": "There's no ticket T-9." } } ``` Without the `try`, the script ends with `{ "status": "tool_error", "error": { "source": "tool", "toolName": "get_ticket", "message": "There's no ticket T-9.", "code": "EXECUTION" } }`. `callTool(name, input, { throwOnError: false })` returns `{ success, data }` or `{ success, error }` instead of throwing, with the same message. An internal error still gets a generic message. So does `this.fail(new PublicMcpError(...))`; throw the public error as `GetTicket` does above, or call it with `codecall:invoke`. Changed in 1.11.3: before, even a thrown public error lost its message. ## Keeping tools away from CodeCall CodeCall may use every tool of the server by default, so a script can call a destructive tool as easily as a harmless one, as often as the limits allow. Keep such tools away from it, with `codecall: { enabledInCodeCall: false }` on the tool, or an `includeTools` rule, which can read the tool's annotations: Initial call configuration: ```js { tool: "codecall:describe", arguments: { toolNames: ["get_ticket", "delete_customer", "purge_closed_tickets"] } } ``` ```ts help-desk.app.ts active import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { DeleteCustomer, GetTicket, PurgeClosedTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, DeleteCustomer, PurgeClosedTickets], plugins: [ CodeCallPlugin.init({ mode: "codecall_only", // ✅ No tool marked destructive, whoever wrote it includeTools: (tool) => !tool.annotations?.destructiveHint, }), ], }) export class HelpDeskApp {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Tool({ name: "delete_customer", description: "Delete a customer and all their tickets", inputSchema: { id: z.string() }, codecall: { enabledInCodeCall: false }, // ✅ never through CodeCall }) export class DeleteCustomer extends ToolContext { async execute({ id }: { id: string }) { return { deleted: id }; } } @Tool({ name: "purge_closed_tickets", description: "Delete every closed ticket", inputSchema: {}, annotations: { destructiveHint: true }, }) export class PurgeClosedTickets extends ToolContext { async execute() { return { purged: 12 }; } } ``` ```ts away.test.ts import { test, expect } from "@frontmcp/testing"; test("codecall:describe only knows get_ticket", async ({ mcp }) => { const result = await mcp.tools.call("codecall:describe", { toolNames: ["get_ticket", "delete_customer", "purge_closed_tickets"] }); expect(result.json().tools.map((t: { name: string }) => t.name)).toEqual(["get_ticket"]); expect(result.json().notFound).toEqual(["delete_customer", "purge_closed_tickets"]); }); test("codecall:invoke refuses the other two", async ({ mcp }) => { const result = await mcp.tools.call("codecall:invoke", { tool: "purge_closed_tickets", input: {} }); expect(result).toBeError(); expect(result).toHaveTextContent('Tool "purge_closed_tickets" is not available.'); }); test("a client that knows the name can't call them directly either", async ({ mcp }) => { const result = await mcp.tools.call("delete_customer", { id: "C-1" }); expect(result).toBeError("TOOL_NOT_FOUND"); expect(result).toHaveTextContent('Tool "delete_customer" not found'); }); ``` A tool CodeCall may not use isn't found by search, is in `notFound` for `codecall:describe`, is refused by `codecall:invoke`, and gets `Access denied for tool "delete_customer"` in a script. The model can't tell whether such a tool exists. The reverse option, `codecall: { visibleInListTools: true }`, keeps a tool in `tools/list` next to CodeCall's, for one the model should always see, like a health check. In `codecall_only`, as here, a client that sends `tools/call` for `delete_customer` by name gets `Tool "delete_customer" not found` too, as the last test shows: CodeCall takes it out of `tools/list`, and FrontMCP answers a direct call of a tool CodeCall hides as if it didn't exist. Your own tools can still call it with `this.callTool()`. > **Pitfall: In the other modes, a listed tool can be called directly** > > `codecall_opt_in` and `metadata_driven` leave tools in `tools/list`, and a client can call a listed tool by name, even one CodeCall refuses. To decide who may call a tool, use [`authorities`](https://frontmcp.dev/learn/authorizing-calls#declaring-who-may-call-a-tool), which apply to direct calls and to CodeCall's alike. (Before FrontMCP 1.9, a client could call any tool by name, in every mode: hiding it was the only protection.) The [CRM with CodeCall](https://frontmcp.dev/examples/crm-with-codecall) example puts 47 tools behind CodeCall, keeps the destructive ones out of reach, and runs one script that combines eight calls. ## Recap - Every listed tool is read by the model before every answer. A long list costs context and accuracy, and multi-step tasks cost a round trip per call. - `CodeCallPlugin.init({ mode: "codecall_only" })` lists CodeCall's six tools instead of yours. They're about 21 KB, whatever is behind them, so CodeCall pays off for large servers, not small ones. - The model finds tools with `codecall:search` (words, not meaning), reads their schemas with `codecall:describe`, and calls one with `codecall:invoke`. Give tools good descriptions and `examples`. - `codecall:execute` runs an AgentScript program on the server that calls several tools and returns only the answer. Scripts are checked before they run, and run within limits. The Playground runs them in a browser sandbox. - Keep destructive tools away with `enabledInCodeCall: false` or `includeTools`. In `codecall_only`, a client can't call them by name either; in the other modes, use `authorities` for that. - Every option, AgentScript's rules and the sandbox's limits are in the [CodeCall reference](https://frontmcp.dev/reference/plugins/codecall). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Put the help desk behind CodeCall The help desk lists its tools directly. Put them behind CodeCall, so the model sees CodeCall's tools and reaches the help desk's through them. ```ts help-desk.app.ts active import { App } from "@frontmcp/sdk"; import { CloseTicket, GetCustomer, GetTicket, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, GetTicket, CloseTicket, GetCustomer], }) export class HelpDeskApp {} ``` **Solution file (alternative to the starter):** ```ts help-desk.app.ts solution import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { CloseTicket, GetCustomer, GetTicket, SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, GetTicket, CloseTicket, GetCustomer], plugins: [CodeCallPlugin.init({ mode: "codecall_only" })], }) export class HelpDeskApp {} ``` ```ts tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open", customerId: "C-1" }, { id: "T-2", title: "Invoice shows the wrong total", status: "open", customerId: "C-2" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by status", inputSchema: { status: z.enum(["open", "closed"]).optional() } }) export class SearchTickets extends ToolContext { async execute({ status }: { status?: "open" | "closed" }) { return { tickets: tickets.filter((t) => !status || t.status === status) }; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return tickets.find((t) => t.id === id) ?? this.fail(new PublicMcpError(`There's no ticket ${id}.`)); } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "get_customer", description: "Get a customer account by its id", inputSchema: { id: z.string() } }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { return { id, name: id === "C-1" ? "Acme Corp" : "Globex" }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts codecall.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`tools/list` shows CodeCall's tools, not the help desk's", async ({ mcp }) => { const tools = await mcp.tools.list(); expect(tools).toContainTool("codecall:search"); expect(tools).toContainTool("codecall:execute"); expect(tools).not.toContainTool("get_ticket"); }); test("`codecall:describe` knows `get_ticket`", async ({ mcp }) => { const result = await mcp.tools.call("codecall:describe", { toolNames: ["get_ticket"] }); expect(result).toBeSuccessful(); expect(result.json().tools[0].name).toBe("get_ticket"); }); test("`codecall:invoke` calls it", async ({ mcp }) => { const result = await mcp.tools.call("codecall:invoke", { tool: "get_ticket", input: { id: "T-1" } }); expect(result.json()).toMatchObject({ id: "T-1", title: "Cannot log in" }); }); ``` **Hint:** CodeCall is a plugin. Remember to call `init()`. **Solution:** `plugins: [CodeCallPlugin.init({ mode: "codecall_only" })]` registers CodeCall on the app. `tools/list` now shows its six tools, and the four help desk tools are reached through `codecall:search`, `codecall:describe`, `codecall:invoke` and `codecall:execute`. `CodeCallPlugin.init()` works too, since `"codecall_only"` is the default; `plugins: [CodeCallPlugin]` without `init()` starts, but every CodeCall tool then fails with `Provider "CodeCallConfig" is not available`. ### Challenge: Keep destructive tools out of scripts CodeCall can reach `delete_customer` and `purge_closed_tickets`, so a model's script could call them in a loop. Keep every tool annotated `destructiveHint` away from CodeCall, including ones added later, and leave the rest available. Initial call configuration: ```js { tool: "codecall:describe", arguments: { toolNames: ["get_ticket", "delete_customer", "purge_closed_tickets"] } } ``` ```ts help-desk.app.ts active import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { CloseTicket, DeleteCustomer, GetTicket, PurgeClosedTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, CloseTicket, DeleteCustomer, PurgeClosedTickets], plugins: [CodeCallPlugin.init({ mode: "codecall_only" })], }) export class HelpDeskApp {} ``` **Solution file (alternative to the starter):** ```ts help-desk.app.ts solution import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { CloseTicket, DeleteCustomer, GetTicket, PurgeClosedTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, CloseTicket, DeleteCustomer, PurgeClosedTickets], plugins: [ CodeCallPlugin.init({ mode: "codecall_only", includeTools: (tool) => !tool.annotations?.destructiveHint, }), ], }) export class HelpDeskApp {} ``` ```ts tools.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @Tool({ name: "delete_customer", description: "Delete a customer and all their tickets", inputSchema: { id: z.string() }, annotations: { destructiveHint: true }, }) export class DeleteCustomer extends ToolContext { async execute({ id }: { id: string }) { return { deleted: id }; } } @Tool({ name: "purge_closed_tickets", description: "Delete every closed ticket", inputSchema: {}, annotations: { destructiveHint: true }, }) export class PurgeClosedTickets extends ToolContext { async execute() { return { purged: 12 }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts away.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance, Tool, ToolContext } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; test("`delete_customer` and `purge_closed_tickets` are out of CodeCall's reach", async ({ mcp }) => { const result = await mcp.tools.call("codecall:describe", { toolNames: ["delete_customer", "purge_closed_tickets"] }); expect(result.json().notFound).toEqual(["delete_customer", "purge_closed_tickets"]); const invoked = await mcp.tools.call("codecall:invoke", { tool: "delete_customer", input: { id: "C-1" } }); expect(invoked).toHaveTextContent('Tool "delete_customer" is not available.'); }); test("`get_ticket` and `close_ticket` are still available", async ({ mcp }) => { const result = await mcp.tools.call("codecall:describe", { toolNames: ["get_ticket", "close_ticket"] }); expect(result.json().notFound).toBeUndefined(); expect(await mcp.tools.call("codecall:invoke", { tool: "close_ticket", input: { id: "T-1" } })).toBeSuccessful(); }); test("so is a destructive tool added later", async () => { @Tool({ name: "wipe_macros", description: "Delete every macro", inputSchema: {}, annotations: { destructiveHint: true } }) class WipeMacros extends ToolContext { async execute() { return { wiped: 3 }; } } @App({ id: "macros", name: "Macros", tools: [WipeMacros] }) class MacrosApp {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp, MacrosApp] }); const asReviewer = { authContext: { user: { sub: "reviewer" } } }; const result = await server.callTool("codecall:describe", { toolNames: ["get_ticket", "wipe_macros"] }, asReviewer); await server.dispose(); expect((result.structuredContent as { notFound?: string[] }).notFound).toEqual(["wipe_macros"]); }); ``` **Hint:** Both tools are already annotated. One CodeCall option decides which tools it may use, and it gets each tool's annotations. **Solution:** `includeTools` is called with each tool, including its `annotations`, and CodeCall only uses the tools it returns `true` for. Returning `!tool.annotations?.destructiveHint` keeps out both tools, and any tool annotated the same way later. `codecall: { enabledInCodeCall: false }` on each tool would keep these two out, but not the next one someone adds. Either way, a client can still call them by name: use [`authorities`](https://frontmcp.dev/learn/authorizing-calls) for that. ### Challenge: Show the model the call you'd make When the model describes `search_tickets`, the example it reads is one CodeCall wrote from the schema: open tickets, with no priority. The help desk's most common search is for open tickets with high priority. Give the tool an example of its own for that search, so it's the call the model sees, and CodeCall's guess isn't listed next to it. Initial call configuration: ```js { tool: "codecall:describe", arguments: { toolNames: ["search_tickets"] } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open", priority: "high" }, { id: "T-2", title: "Invoice shows the wrong total", status: "open", priority: "low" }, { id: "T-4", title: "Password reset email never arrives", status: "closed", priority: "high" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by status and priority", inputSchema: { status: z.enum(["open", "closed"]).optional(), priority: z.enum(["low", "high"]).optional() }, }) export class SearchTickets extends ToolContext { async execute({ status, priority }: { status?: "open" | "closed"; priority?: "low" | "high" }) { return { tickets: tickets.filter((t) => (!status || t.status === status) && (!priority || t.priority === priority)) }; } } ``` **Solution file (alternative to the starter):** ```ts tools.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open", priority: "high" }, { id: "T-2", title: "Invoice shows the wrong total", status: "open", priority: "low" }, { id: "T-4", title: "Password reset email never arrives", status: "closed", priority: "high" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by status and priority", inputSchema: { status: z.enum(["open", "closed"]).optional(), priority: z.enum(["low", "high"]).optional() }, examples: [{ description: "Open tickets with high priority", input: { status: "open", priority: "high" } }], }) export class SearchTickets extends ToolContext { async execute({ status, priority }: { status?: "open" | "closed"; priority?: "low" | "high" }) { return { tickets: tickets.filter((t) => (!status || t.status === status) && (!priority || t.priority === priority)) }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { SearchTickets } from "./tools"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets], plugins: [CodeCallPlugin.init({ mode: "codecall_only" })] }) export class HelpDeskApp {} ``` **Hidden fixture/test file (runs with the example):** ```ts example.test.ts hidden import { test, expect } from "@frontmcp/testing"; const usageExamples = async (mcp: any) => (await mcp.tools.call("codecall:describe", { toolNames: ["search_tickets"] })).json().tools[0].usageExamples; test("the example asks for open tickets with high priority", async ({ mcp }) => { const [example] = await usageExamples(mcp); expect(example.code).toContain('"status": "open"'); expect(example.code).toContain('"priority": "high"'); }); test("CodeCall's own guess isn't listed next to it", async ({ mcp }) => { const examples = await usageExamples(mcp); expect(examples).toHaveLength(1); expect(examples[0].code).not.toContain("results.items"); }); test("its input finds the ticket", async ({ mcp }) => { const result = await mcp.tools.call("codecall:invoke", { tool: "search_tickets", input: { status: "open", priority: "high" } }); expect(result.json().tickets.map((t: { id: string }) => t.id)).toEqual(["T-1"]); }); ``` **Hint:** `@Tool` takes `examples`: a list of `{ description, input }`. **Solution:** `examples: [{ description: "Open tickets with high priority", input: { status: "open", priority: "high" } }]` gives `codecall:describe` a usage example of your own, and it shows yours alone: when a tool has examples, CodeCall doesn't write one next to them. Without it, the model would have copied the guess, which asks for open tickets and leaves out the priority. The examples are indexed for `codecall:search` too, so their descriptions help the model find the tool. --- # Wrapping an OpenAPI Service > Turn an OpenAPI 3 specification into MCP tools. Choose operations, configure server-side credentials and handle API errors. Source: https://frontmcp.dev/learn/wrapping-an-openapi-service [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 The help desk's tickets don't live in your server. They live in the Desk API, a REST service another team runs, and that team publishes an OpenAPI description of it. You could write a tool for each endpoint with [`this.fetch()`](https://frontmcp.dev/learn/calling-other-services), but the description already says everything those tools would repeat: the paths, the parameters, the bodies, the responses. FrontMCP's **OpenAPI adapter**, from `@frontmcp/adapters`, reads it and gives your app one tool per operation, which builds and sends the request the description says, with credentials you configure. **You will learn** - How to turn an OpenAPI description into tools - What a call sends to the API, and what the model gets back - How to give the adapter the API's credentials, without the model seeing them - How to choose which operations become tools, and name them for the model - What to do when an API is too big for one tool per operation ## Turning a spec into tools Install the adapters package: ```bash npm install @frontmcp/adapters ``` Then give the adapter a name, the API's address and its description, the **spec**, and list it in the app's `adapters`: Initial call configuration: ```js { tool: "getTicket", arguments: { id: "T-1" } } ``` ```ts desk.app.ts active import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec })], }) export class DeskApp {} ``` ```ts desk-spec.ts const ticket = { type: "object", properties: { id: { type: "string" }, title: { type: "string" }, status: { type: "string", enum: ["open", "closed"] } }, }; const id = { name: "id", in: "path", required: true, schema: { type: "string" } }; export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, paths: { "/tickets": { get: { operationId: "listTickets", summary: "List support tickets, newest first", parameters: [{ name: "status", in: "query", schema: { type: "string", enum: ["open", "closed"] } }], responses: { "200": { description: "The tickets", content: { "application/json": { schema: { type: "array", items: ticket } } } } }, }, post: { operationId: "createTicket", summary: "Open a support ticket", requestBody: { required: true, content: { "application/json": { schema: { type: "object", required: ["title"], properties: { title: { type: "string" }, priority: { type: "string", enum: ["low", "high"] } }, }, }, }, }, responses: { "201": { description: "Created", content: { "application/json": { schema: ticket } } } }, }, }, "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", parameters: [id], responses: { "200": { description: "The ticket", content: { "application/json": { schema: ticket } } } }, }, delete: { operationId: "deleteTicket", summary: "Delete a support ticket", parameters: [id], responses: { "204": { description: "Deleted" } }, }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. // It answers requests in-process and records them, so tests can check what the API received. export const received: { method: string; url: string; body?: unknown }[] = []; const tickets: Record = { "T-1": { id: "T-1", title: "Cannot log in", status: "open" }, "T-2": { id: "T-2", title: "Invoice total is wrong", status: "closed" }, "T-3": { id: "T-3", title: "Login link expired", status: "open" }, }; async function desk(request: Request): Promise { const text = await request.text(); received.push({ method: request.method, url: request.url, ...(text ? { body: JSON.parse(text) } : {}) }); const url = new URL(request.url); if (request.method === "POST") return Response.json({ id: "T-4", status: "open", ...JSON.parse(text) }, { status: 201 }); if (request.method === "DELETE") return new Response(null, { status: 204 }); if (url.pathname === "/v1/tickets") { const status = url.searchParams.get("status"); return Response.json(Object.values(tickets).filter((t) => !status || t.status === status)); } const ticket = tickets[url.pathname.replace("/v1/tickets/", "")]; return ticket ? Response.json(ticket) : Response.json({ message: "No ticket with that id" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input)); return url.hostname === "desk.example" ? desk(new Request(input, init)) : realFetch(input, init); }; ``` ```ts desk.test.ts import { test, expect } from "@frontmcp/testing"; import { received } from "./desk.example"; test("each operation is a tool, named by its operationId", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name); expect(names).toEqual(["createTicket", "deleteTicket", "getTicket", "listTickets"]); }); test("its parameters and body fields make one input", async ({ mcp }) => { const create = (await mcp.tools.list()).find((t: { name: string }) => t.name === "createTicket"); expect(create.description).toBe("Open a support ticket"); expect(Object.keys(create.inputSchema.properties)).toEqual(["title", "priority"]); expect(create.inputSchema.required).toEqual(["title"]); }); test("a call sends the request the spec describes", async ({ mcp }) => { await mcp.tools.call("listTickets", { status: "open" }); expect(received.at(-1)).toEqual({ method: "GET", url: "https://desk.example/v1/tickets?status=open" }); await mcp.tools.call("createTicket", { title: "Printer on fire", priority: "high" }); expect(received.at(-1)).toEqual({ method: "POST", url: "https://desk.example/v1/tickets", body: { title: "Printer on fire", priority: "high" } }); }); test("the model gets the API's status and body", async ({ mcp }) => { const result = await mcp.tools.call("getTicket", { id: "T-1" }); expect(result.json()).toEqual({ status: 200, ok: true, data: { id: "T-1", title: "Cannot log in", status: "open" } }); }); ``` > **Note** > > The Playground can't reach a real API, so every example in this lesson has a `desk.example.ts` that plays the Desk API at `https://desk.example`. It replaces `globalThis.fetch`, which the adapter calls, answers in-process, and records what it received, so the tests can check what the API was sent. Your server doesn't need it. Open the **Capabilities** tab: four tools, one per operation, with no tool code of yours. - **`name`** names the adapter. It must be unique among all the adapters in the process. - **`baseUrl`** is where the API is. Each operation's path is added to it. - **`spec`** is the OpenAPI 3.0 or 3.1 document, as an object: import the JSON file, or pass `url` instead to download it when the server starts. - **Each tool** is named by the operation's `operationId` and described by its `summary`. Its input has one property for each path, query, header and cookie parameter and each field of the JSON body, and the adapter puts each value back where the spec says it goes. - **The result** is `{ status, ok, data }`: the API's HTTP status and its parsed JSON body. That already works, and it already has problems, which the rest of this lesson fixes: `deleteTicket` is a tool the model can call, the names are the API's, and the real Desk API wants a token, which nothing sends yet. ## What the model gets back The API's answers pass through as they are, errors included. A `4xx` or `5xx` is an error result that still carries the status and the body, so the model can tell a ticket that doesn't exist from an API that's down: Initial call configuration: ```js { tool: "getTicket", arguments: { id: "T-9" } } ``` ```ts errors.test.ts active import { test, expect } from "@frontmcp/testing"; import { received } from "./desk.example"; test("a 404 is an error result, with the API's status and body", async ({ mcp }) => { const result = await mcp.tools.call("getTicket", { id: "T-9" }); expect(result).toBeError(); expect(JSON.parse(result.text())).toEqual({ status: 404, error: "No ticket with that id", data: { message: "No ticket with that id" } }); }); test("a 204 comes back with empty data", async ({ mcp }) => { expect((await mcp.tools.call("deleteTicket", { id: "T-2" })).json()).toEqual({ status: 204, ok: true, data: "" }); }); test("a missing required argument is refused before anything is sent", async ({ mcp }) => { const before = received.length; const result = await mcp.tools.call("getTicket", {}); expect(result).toBeError("INVALID_INPUT"); expect(result).toHaveTextContent("Invalid arguments for tool 'getTicket': id: Invalid input: expected string, received undefined"); expect(received.length).toBe(before); }); test("so is a value the spec doesn't allow, or a key it doesn't have", async ({ mcp }) => { const before = received.length; const urgent = await mcp.tools.call("listTickets", { status: "urgent" }); expect(urgent).toBeError("INVALID_INPUT"); expect(urgent).toHaveTextContent(`Invalid arguments for tool 'listTickets': status: Invalid option: expected one of "open"|"closed"`); const unknownKey = await mcp.tools.call("listTickets", { assignee: "sam" }); expect(unknownKey).toHaveTextContent(`Invalid arguments for tool 'listTickets': input: Unrecognized key: "assignee"`); expect(received.length).toBe(before); }); ``` ```ts desk.app.ts import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec })], }) export class DeskApp {} ``` ```ts desk-spec.ts const ticket = { type: "object", properties: { id: { type: "string" }, title: { type: "string" }, status: { type: "string", enum: ["open", "closed"] } }, }; const id = { name: "id", in: "path", required: true, schema: { type: "string" } }; export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, paths: { "/tickets": { get: { operationId: "listTickets", summary: "List support tickets, newest first", parameters: [{ name: "status", in: "query", schema: { type: "string", enum: ["open", "closed"] } }], responses: { "200": { description: "The tickets", content: { "application/json": { schema: { type: "array", items: ticket } } } } }, }, }, "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", parameters: [id], responses: { "200": { description: "The ticket", content: { "application/json": { schema: ticket } } } }, }, delete: { operationId: "deleteTicket", summary: "Delete a support ticket", parameters: [id], responses: { "204": { description: "Deleted" } }, }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. export const received: { method: string; url: string }[] = []; const tickets: Record = { "T-1": { id: "T-1", title: "Cannot log in", status: "open" }, "T-2": { id: "T-2", title: "Invoice total is wrong", status: "closed" }, }; async function desk(request: Request): Promise { received.push({ method: request.method, url: request.url }); const url = new URL(request.url); if (request.method === "DELETE") return new Response(null, { status: 204 }); if (url.pathname === "/v1/tickets") return Response.json(Object.values(tickets)); const ticket = tickets[url.pathname.replace("/v1/tickets/", "")]; return ticket ? Response.json(ticket) : Response.json({ message: "No ticket with that id" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input)); return url.hostname === "desk.example" ? desk(new Request(input, init)) : realFetch(input, init); }; ``` The error's text is `{"status":404,"error":"No ticket with that id","data":{…}}`: `error` is the body's `message` field, or the body itself when it's text. A redirect isn't followed, and a request that takes longer than `requestTimeoutMs` (30 seconds by default) fails the call. [What the model gets back](https://frontmcp.dev/reference/adapters/openapi#what-the-model-gets-back) covers each case. Before it sends anything, the adapter checks the arguments against the spec, as the last two tests show. A missing required parameter, a value outside an `enum`, or a key the operation doesn't have is refused with the code `INVALID_INPUT`, and the message names the argument and what's wrong with it, so the model can fix the call and try again. The API receives nothing. [Arguments are checked against the spec](https://frontmcp.dev/reference/adapters/openapi#arguments-are-checked-against-the-spec) lists what the check covers. > **Pitfall: The check is only as strict as the spec** > > The adapter checks what the spec says, and nothing more. A `status` declared as a plain `string`, with no `enum`, lets `"urgent"` through to the API, which then answers `400`: an error result, like the `404` above. Keep validating input in the API, as you would for any client, and keep the spec as exact as the API: an `enum` in the spec is also what tells the model which values to send. ## Giving the adapter the API's credentials The real Desk API wants a bearer token on every request, and its spec says so, with a security scheme. An adapter with no credentials doesn't guess: it refuses the call, and sends nothing. Give it the token the Desk team issued for your server, as `staticAuth`: Initial call configuration: ```js { tool: "getTicket", arguments: { id: "T-1" } } ``` ```ts desk.app.ts active import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [ OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec, // In a real server: { jwt: process.env.DESK_API_TOKEN } staticAuth: { jwt: "desk-service-token" }, }), ], }) export class DeskApp {} ``` ```ts desk-spec.ts const ticket = { type: "object", properties: { id: { type: "string" }, title: { type: "string" }, status: { type: "string", enum: ["open", "closed"] } }, }; export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, components: { securitySchemes: { DeskToken: { type: "http", scheme: "bearer" } } }, security: [{ DeskToken: [] }], paths: { "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "The ticket", content: { "application/json": { schema: ticket } } } }, }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. // It wants the token the Desk team issued for the help desk server. export const received: { url: string; authorization: string | null }[] = []; async function desk(request: Request): Promise { const authorization = request.headers.get("authorization"); received.push({ url: request.url, authorization }); if (authorization !== "Bearer desk-service-token") return Response.json({ message: "Invalid token" }, { status: 401 }); return Response.json({ id: "T-1", title: "Cannot log in", status: "open" }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input)); return url.hostname === "desk.example" ? desk(new Request(input, init)) : realFetch(input, init); }; ``` ```ts credentials.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { received } from "./desk.example"; import { spec } from "./desk-spec"; test("the API gets the token as a bearer token", async ({ mcp }) => { expect((await mcp.tools.call("getTicket", { id: "T-1" })).json()).toMatchObject({ status: 200, ok: true }); expect(received.at(-1)?.authorization).toBe("Bearer desk-service-token"); }); test("the model never sees it: it's in no tool's input", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t: { name: string }) => t.name === "getTicket"); expect(Object.keys(tool.inputSchema.properties)).toEqual(["id"]); }); test("🚩 without credentials, calls are refused, and nothing is sent", async () => { @App({ id: "desk", name: "Desk", adapters: [OpenapiAdapter.init({ name: "desk-without-token", baseUrl: "https://desk.example/v1", spec })] }) class DeskWithoutToken {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [DeskWithoutToken] }); const before = received.length; await expect(server.callTool("getTicket", { id: "T-1" })).rejects.toThrow( "Authentication required for tool 'getTicket': no credential for its security schemes.", ); await server.dispose(); expect(received.length).toBe(before); }); ``` The adapter reads the spec's security scheme to know where a credential goes: `DeskToken` is an HTTP bearer scheme, so `jwt` is sent as `Authorization: Bearer desk-service-token`. An `apiKey` scheme would get `apiKey` in the header, query parameter or cookie it names. The token never appears in a tool's input or result, so the model can't see it, repeat it, or be talked into sending a different one. `staticAuth` is one account for every caller, which suits an API that trusts your server as a whole. When the API has an account per user or per customer, pick the credential per call instead, from who's calling: ### A token per tenant `securityResolver(tool, ctx)` returns the credentials for one call. `ctx.authInfo.user` holds the claims of the caller's token, so a tenant claim can pick the tenant's API token. The tests call the server in-process as two signed-in agents: `nour`, whose tenant has a token, and `sam`, whose tenant has none: ```ts main.ts active import "./desk.example"; import { App, FrontMcp } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; // In a real server these come from a secret store const deskTokens: Record = { acme: "desk-token-acme" }; @App({ id: "desk", name: "Desk", adapters: [ OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec, securityResolver: (tool, ctx) => { const tenant = (ctx.authInfo?.user as { tenant?: string } | undefined)?.tenant; return tenant && deskTokens[tenant] ? { jwt: deskTokens[tenant] } : {}; }, }), ], }) class DeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [DeskApp] }; @FrontMcp(config) export default class Server {} ``` ```ts desk-spec.ts export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, components: { securitySchemes: { DeskToken: { type: "http", scheme: "bearer" } } }, security: [{ DeskToken: [] }], paths: { "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "The ticket", content: { "application/json": { schema: { type: "object" } } } } }, }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. export const received: { url: string; authorization: string | null }[] = []; const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const request = new Request(input, init); if (new URL(request.url).hostname !== "desk.example") return realFetch(input, init); received.push({ url: request.url, authorization: request.headers.get("authorization") }); return Promise.resolve(Response.json({ id: "T-1", title: "Cannot log in", status: "open" })); }; ``` ```ts tenant.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { received } from "./desk.example"; import { config } from "./main"; const nour = { authContext: { user: { sub: "nour", tenant: "acme" } } }; const sam = { authContext: { user: { sub: "sam", tenant: "globex" } } }; test("nour's call uses her tenant's token", async () => { const server = await FrontMcpInstance.createDirect(config); const result = await server.callTool("getTicket", { id: "T-1" }, nour); await server.dispose(); expect(result.structuredContent).toMatchObject({ status: 200, ok: true }); expect(received.at(-1)?.authorization).toBe("Bearer desk-token-acme"); }); test("sam's tenant has no token, so his call is refused, and nothing is sent", async () => { const server = await FrontMcpInstance.createDirect(config); const before = received.length; await expect(server.callTool("getTicket", { id: "T-1" }, sam)).rejects.toThrow("Authentication required for tool 'getTicket'"); await server.dispose(); expect(received.length).toBe(before); }); ``` Returning `{}` gives the call no credential, so it's refused before anything is sent. `authProviderMapper` does the same with one function per security scheme, and falls back to `staticAuth` for a caller it has nothing for. [How credentials are chosen](https://frontmcp.dev/reference/adapters/openapi#how-credentials-are-chosen) lists every option, and the order they're tried in. > **Pitfall: Don't send the caller's token to the API** > > The token a client sends to your server was issued for your server. `passthroughCallerToken: true` forwards it to the API as the bearer token, and then whoever runs the API, or reads its logs, holds a token that works on your server as that user. The MCP specification forbids that kind of token passthrough. The adapter never sends the caller's token unless you set the option; set it only for an API that accepts the same tokens as your server, from the same identity provider, for the same audience. ## Choosing which operations become tools Most APIs have operations the model shouldn't call. `deleteTicket` is one: a support agent who asks the model to "clean up the duplicate" shouldn't end up with a ticket deleted for good. Leave it out with `generateOptions`, which decides which operations become tools. `filterFn` is called with each operation, its `method` and its `path`: Initial call configuration: ```js { tool: "listTickets", arguments: {} } ``` ```ts desk.app.ts active import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [ OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec, generateOptions: { // ✅ No deletes, and nothing tagged admin filterFn: (op) => op.method !== "delete" && !op.tags?.includes("admin"), }, }), ], }) export class DeskApp {} ``` ```ts desk-spec.ts const ok = { "200": { description: "OK", content: { "application/json": { schema: { type: "object" } } } } }; const id = [{ name: "id", in: "path", required: true, schema: { type: "string" } }]; export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, paths: { "/tickets": { get: { operationId: "listTickets", summary: "List support tickets, newest first", tags: ["tickets"], responses: ok }, post: { operationId: "createTicket", summary: "Open a support ticket", tags: ["tickets"], responses: ok }, }, "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", tags: ["tickets"], parameters: id, responses: ok }, delete: { operationId: "deleteTicket", summary: "Delete a support ticket", tags: ["tickets"], parameters: id, responses: ok }, }, "/admin/agents": { get: { operationId: "listAgents", summary: "List support agents, with their roles", tags: ["admin"], responses: ok }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. export const received: { method: string; url: string }[] = []; const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const request = new Request(input, init); if (new URL(request.url).hostname !== "desk.example") return realFetch(input, init); received.push({ method: request.method, url: request.url }); return Promise.resolve(Response.json({ ok: true })); }; ``` ```ts select.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { received } from "./desk.example"; import { spec } from "./desk-spec"; test("only the operations the filter keeps are tools", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name); expect(names).toEqual(["createTicket", "getTicket", "listTickets"]); }); test("a left-out operation can't be called at all", async ({ mcp }) => { const result = await mcp.tools.call("deleteTicket", { id: "T-2" }); expect(result).toBeError(); expect(result).toHaveTextContent('Tool "deleteTicket" not found'); expect(received.some((r) => r.method === "DELETE")).toBe(false); }); test("excludeMethods and excludeTags keep the same operations", async () => { @App({ id: "desk", name: "Desk", adapters: [ OpenapiAdapter.init({ name: "desk-by-fields", baseUrl: "https://desk.example/v1", spec, generateOptions: { excludeMethods: ["delete"], excludeTags: ["admin"] }, }), ], }) class DeskByFields {} const server = await FrontMcpInstance.createDirect({ info: { name: "desk", version: "1.0.0" }, apps: [DeskByFields] }); expect((await server.listTools()).tools.map((t) => t.name).sort()).toEqual(["createTicket", "getTicket", "listTickets"]); await server.dispose(); }); ``` An operation the filter leaves out isn't a tool: it's not listed, and a client that calls it by name gets `Tool "deleteTicket" not found`. That's the difference from hiding a tool, below. Two simpler options pick operations by `operationId`: `includeOperations: ["listTickets", "getTicket"]` keeps only those, and `excludeOperations: ["deleteTicket"]` leaves those out. An operation without an `operationId` can't be listed, so `includeOperations` leaves it out; `filterFn` sees every operation. > **Note** > > `generateOptions` also has fields for the usual cases: `includeTags` and `excludeTags`, `includeMethods` and `excludeMethods` (in any case, `"delete"` or `"DELETE"`; `OpenapiAdapter.init()` throws for a name that isn't an HTTP method), `includePaths` and `excludePaths`, and `readOnlyOnly`. `excludeMethods: ["delete"], excludeTags: ["admin"]` keeps the same operations as the `filterFn` above, as the last test shows. See [`generateOptions`](https://frontmcp.dev/reference/adapters/openapi#generateoptions). (Before FrontMCP 1.9, the adapter didn't pass these fields on, so they did nothing.) ## Naming tools for the model `listTickets` is the API's name, in the API's style. Next to your own tools, like `search_tickets`, the model reads a list in two styles. `toolTransforms` rewrites what the spec gave each tool: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts desk.app.ts active import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [ OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec, descriptionMode: "combined", // the summary, then the description toolTransforms: { // A POST here only adds: it never changes or deletes what's there generator: (tool) => (tool.metadata.method === "post" ? { annotations: { destructiveHint: false } } : undefined), perTool: { listTickets: { name: "list_tickets" }, getTicket: { name: "get_ticket" }, createTicket: { name: "create_ticket", description: (d) => `${d} Search with list_tickets first, to avoid duplicates.` }, }, }, }), ], }) export class DeskApp {} ``` ```ts desk-spec.ts const ok = { "200": { description: "OK", content: { "application/json": { schema: { type: "object" } } } } }; export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, paths: { "/tickets": { get: { operationId: "listTickets", summary: "List support tickets.", description: "Newest first, 20 at a time.", parameters: [{ name: "status", in: "query", schema: { type: "string", enum: ["open", "closed"] } }], responses: ok, }, post: { operationId: "createTicket", summary: "Open a support ticket.", requestBody: { content: { "application/json": { schema: { type: "object", properties: { title: { type: "string" } } } } } }, responses: ok, }, }, "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id.", parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: ok, }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input)); if (url.hostname !== "desk.example") return realFetch(input, init); return Promise.resolve(Response.json({ id: "T-1", title: "Cannot log in", status: "open" })); }; ``` ```ts names.test.ts import { test, expect } from "@frontmcp/testing"; const byName = async (mcp: any) => Object.fromEntries((await mcp.tools.list()).map((t: any) => [t.name, t])); test("the tools have the names you gave them", async ({ mcp }) => { expect(Object.keys(await byName(mcp))).toEqual(["create_ticket", "get_ticket", "list_tickets"]); }); test("descriptions combine the spec's summary and description, plus your words", async ({ mcp }) => { const tools = await byName(mcp); expect(tools.list_tickets.description).toBe("List support tickets.\n\nNewest first, 20 at a time."); expect(tools.create_ticket.description).toBe("Open a support ticket. Search with list_tickets first, to avoid duplicates."); }); test("annotations come from the HTTP method, and the generator corrects the POSTs", async ({ mcp }) => { const tools = await byName(mcp); expect(tools.get_ticket.annotations).toEqual({ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }); expect(tools.create_ticket.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }); }); test("the spec's summary is each tool's title", async ({ mcp }) => { expect((await byName(mcp)).list_tickets.title).toBe("List support tickets."); }); ``` - **`perTool`** is keyed by the tool's name before the transform. `description` takes a string, or a function that gets the current description. - **Annotations** start from each operation's HTTP method: a `GET` is `readOnlyHint` and `idempotentHint`, and a `POST`, `PUT`, `PATCH` or `DELETE` is `destructiveHint`. That's a guess from HTTP's rules. A `POST` that only adds, like `createTicket`, destroys nothing, so the `generator` says so, and what a transform sets is merged over the guess. - **`generator`** is called with every generated tool and returns a transform or `undefined`. `tool.metadata` has the operation's `method`, `path`, `operationId` and `tags`. - **The title** is the operation's `summary`, for clients to show people. The model reads the name and the description. - **`descriptionMode`** decides how the spec's `summary` and `description` make the tool's description. The default, `"summaryOnly"`, uses the `summary` alone when there is one. `toolTransforms` can also set `hideFromDiscovery: true`, which leaves a tool out of `tools/list`. It's still called by anyone who knows its name, so it's no way to protect an operation: leave the operation out with `generateOptions`, as above, or [require authorities](https://frontmcp.dev/learn/authorizing-calls). To fill in an argument on the server, like a tenant id, rather than asking the model for it, see [`inputTransforms`](https://frontmcp.dev/reference/adapters/openapi#filling-in-inputs-on-the-server). ## An API too big to list The Desk API has four operations; a billing or CRM API can have four hundred. One tool per operation then has the problem the [CodeCall lesson](https://frontmcp.dev/learn/letting-the-model-write-code-with-codecall) starts with: a tool list too long for the model to read. Three ways out, from the least change to the most: | | What the model sees | Use it when | | --- | --- | --- | | **Filter** with `generateOptions` | The operations you keep, as tools | The model needs a known handful of operations. | | **CodeCall** in front of the adapter | CodeCall's tools; it searches the operations and calls them, or runs a script | The model needs many operations, and the spec's summaries are good enough to search. | | **Skilled OpenAPI** instead of the adapter | Four tools that find and load **skills**, groups of operations with instructions you write, and run their operations | The API needs explaining, like which call comes first, or you want to limit who may run each operation. | The adapter's tools are ordinary tools, so CodeCall treats them like any other. Here the model finds `closeTicket` by searching, and calls it; the token still comes from `staticAuth`: Initial call configuration: ```js { tool: "codecall:search", arguments: { queries: ["close ticket"] } } ``` ```ts desk.app.ts active import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { CodeCallPlugin } from "@frontmcp/plugin-codecall"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec, staticAuth: { jwt: "desk-service-token" } })], plugins: [CodeCallPlugin.init({ mode: "codecall_only" })], }) export class DeskApp {} ``` ```ts desk-spec.ts const ticket = { type: "object", properties: { id: { type: "string" }, title: { type: "string" }, status: { type: "string" } } }; const id = [{ name: "id", in: "path", required: true, schema: { type: "string" } }]; const returns = (description: string) => ({ "200": { description, content: { "application/json": { schema: ticket } } } }); export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, components: { securitySchemes: { DeskToken: { type: "http", scheme: "bearer" } } }, security: [{ DeskToken: [] }], paths: { "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", parameters: id, responses: returns("The ticket") } }, "/tickets/{id}/close": { post: { operationId: "closeTicket", summary: "Close a support ticket", parameters: id, responses: returns("The closed ticket") } }, "/tickets/{id}/reopen": { post: { operationId: "reopenTicket", summary: "Reopen a closed support ticket", parameters: id, responses: returns("The reopened ticket") } }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. export const received: { method: string; url: string; authorization: string | null }[] = []; const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const request = new Request(input, init); const url = new URL(request.url); if (url.hostname !== "desk.example") return realFetch(input, init); received.push({ method: request.method, url: request.url, authorization: request.headers.get("authorization") }); const status = url.pathname.endsWith("/close") ? "closed" : "open"; return Promise.resolve(Response.json({ id: "T-1", title: "Cannot log in", status })); }; ``` ```ts behind-codecall.test.ts import { test, expect } from "@frontmcp/testing"; import { received } from "./desk.example"; test("the operations are behind CodeCall's tools", async ({ mcp }) => { const tools = await mcp.tools.list(); expect(tools).toContainTool("codecall:search"); expect(tools).not.toContainTool("closeTicket"); }); test("the model finds an operation by searching", async ({ mcp }) => { const { tools } = (await mcp.tools.call("codecall:search", { queries: ["close ticket"] })).json(); expect(tools[0]).toMatchObject({ name: "closeTicket", appId: "desk" }); }); test("and calls it, with the adapter's credentials", async ({ mcp }) => { const result = await mcp.tools.call("codecall:invoke", { tool: "closeTicket", input: { id: "T-1" } }); expect(result.json()).toEqual({ status: 200, ok: true, data: { id: "T-1", title: "Cannot log in", status: "closed" } }); expect(received.at(-1)).toEqual({ method: "POST", url: "https://desk.example/v1/tickets/T-1/close", authorization: "Bearer desk-service-token" }); }); ``` Skilled OpenAPI goes further. Instead of the spec, it serves a **bundle**: the API's operations, and skills, each a named group of operations with instructions in Markdown, like "read the invoice before refunding it, and refund at most its amount". The model sees four tools: `search_skill` finds a skill, `load_skill` reads its instructions and the operations it offers, `execute_action` runs one of them, and `run_workflow` runs a short script that chains several. Each call is checked against the operation's schema and the caller's authorities, and sent with credentials the model never sees: Initial call configuration: ```js { tool: "search_skill", arguments: { query: "refund an invoice" } } ``` ```ts main.ts active import { App, FrontMcp } from "@frontmcp/sdk"; import { SkilledOpenApiPlugin } from "@frontmcp/plugin-skilled-openapi"; import { bundle } from "./bundle"; @App({ id: "billing", name: "Billing" }) class BillingApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [BillingApp], plugins: [ SkilledOpenApiPlugin.init({ source: { type: "inline", content: bundle }, requireSignature: false, // a real server only accepts signed bundles credentials: { "billing-token": "billing-api-token" }, // in a real server, from the environment }), ], }) export default class Server {} ``` ```ts bundle.ts const invoice = { type: "object", properties: { id: { type: "string" }, amount: { type: "number" }, status: { type: "string" } } }; export const bundle = { schemaVersion: 1, bundleId: "acme:billing", version: "1.0.0", generatedAt: "2026-09-01T12:00:00.000Z", sourceDigest: "0".repeat(64), services: [{ id: "billing", baseUrl: "https://203.0.113.10/v1" }], authBindings: { api: { kind: "bearer", vaultRef: "billing-token" } }, skills: [ { id: "invoices", name: "Invoices", description: "Look up customer invoices and refund them.", instructions: "# Invoices\n\nRead an invoice with getInvoice before refunding it. Refund at most its amount.", operationIds: ["getInvoice", "refundInvoice"], }, ], operations: { getInvoice: { operationId: "getInvoice", serviceId: "billing", httpMethod: "GET", pathTemplate: "/invoices/{id}", summary: "Get an invoice", inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] }, outputSchema: invoice, mapper: [{ inputKey: "id", type: "path", key: "id", required: true }], authBindingRef: "api", }, refundInvoice: { operationId: "refundInvoice", serviceId: "billing", httpMethod: "POST", pathTemplate: "/invoices/{id}/refunds", summary: "Refund part or all of an invoice", inputSchema: { type: "object", properties: { id: { type: "string" }, amount: { type: "number" } }, required: ["id", "amount"] }, outputSchema: { type: "object" }, mapper: [ { inputKey: "id", type: "path", key: "id", required: true }, { inputKey: "amount", type: "body", key: "amount", required: true }, ], authBindingRef: "api", }, }, }; ``` ```ts skills.test.ts import { test, expect } from "@frontmcp/testing"; test("the model sees four tools, not one per operation", async ({ mcp }) => { expect((await mcp.tools.list()).map((t: { name: string }) => t.name).sort()).toEqual(["execute_action", "load_skill", "run_workflow", "search_skill"]); }); test("it finds a skill by what it does, and loads its instructions and operations", async ({ mcp }) => { const { skills } = (await mcp.tools.call("search_skill", { query: "refund an invoice" })).json(); expect(skills[0]).toMatchObject({ skillId: "invoices", name: "Invoices" }); const { skill } = (await mcp.tools.call("load_skill", { skillId: "invoices" })).json(); expect(skill.instructions).toContain("Refund at most its amount."); expect(skill.actions.map((a: { actionId: string }) => a.actionId)).toEqual(["getInvoice", "refundInvoice"]); }); ``` The price is the bundle: you write the skills, and a production server only applies bundles signed by a key it trusts. `compileSkilledBundleFromOpenApi()` builds a bundle's operations from the spec you already have. The plugin and the adapter work side by side, so a server can list the few operations the model needs in every conversation as adapter tools, and serve the long tail as skills. [Skilled OpenAPI](https://frontmcp.dev/reference/plugins/skilled-openapi) covers bundles, signing, credentials and authorization. The [Pet Store from OpenAPI](https://frontmcp.dev/examples/pet-store-from-openapi) example wraps the Swagger Petstore the same way, and shows what to check when you point the adapter at a live API. ## Recap - `OpenapiAdapter.init({ name, baseUrl, spec })` in an app's `adapters` turns every operation of an OpenAPI 3 spec into a tool, named by its `operationId`, whose input has a property for each parameter and body field. - A call sends the request the spec describes, once its arguments match the spec: one that doesn't is refused with `INVALID_INPUT`, and nothing is sent. The model gets `{ status, ok, data }`, or an error result that still carries the API's status and body. - Credentials go where the spec's security scheme says: `staticAuth` for one account, `securityResolver` or `authProviderMapper` per caller. Without them a secured call is refused, and the caller's own token is never sent unless you set `passthroughCallerToken`. - `generateOptions` decides which operations become tools at all: `filterFn`, or fields like `includeOperations`, `excludeMethods` and `excludeTags`. Annotations come from each operation's HTTP method; `toolTransforms` renames the tools, rewrites descriptions and corrects annotations. - For an API too big to list, put CodeCall in front of the adapter's tools, or serve the API as skills with Skilled OpenAPI. - Every option, and exactly what a call sends, is in the [OpenAPI adapter reference](https://frontmcp.dev/reference/adapters/openapi). ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Wrap the Desk API The Desk app has the Desk API's spec, but no tools. Turn the spec's operations into tools that call the API at `https://desk.example/v1`. ```ts desk.app.ts active import "./desk.example"; import { App } from "@frontmcp/sdk"; @App({ id: "desk", name: "Desk" }) export class DeskApp {} ``` **Solution file (alternative to the starter):** ```ts desk.app.ts solution import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec })], }) export class DeskApp {} ``` ```ts desk-spec.ts const ticket = { type: "object", properties: { id: { type: "string" }, title: { type: "string" }, status: { type: "string" } } }; export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, paths: { "/tickets": { get: { operationId: "listTickets", summary: "List support tickets, newest first", responses: { "200": { description: "The tickets", content: { "application/json": { schema: { type: "array", items: ticket } } } } }, }, }, "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "The ticket", content: { "application/json": { schema: ticket } } } }, }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. export const received: { method: string; url: string }[] = []; const tickets: Record = { "T-1": { id: "T-1", title: "Cannot log in", status: "open" } }; const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const request = new Request(input, init); const url = new URL(request.url); if (url.hostname !== "desk.example") return realFetch(input, init); received.push({ method: request.method, url: request.url }); if (url.pathname === "/v1/tickets") return Promise.resolve(Response.json(Object.values(tickets))); const ticket = tickets[url.pathname.replace("/v1/tickets/", "")]; return Promise.resolve(ticket ? Response.json(ticket) : Response.json({ message: "No ticket with that id" }, { status: 404 })); }; ``` **Hidden fixture/test file (runs with the example):** ```ts desk.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { received } from "./desk.example"; test("`listTickets` and `getTicket` are tools", async ({ mcp }) => { const tools = await mcp.tools.list(); expect(tools).toContainTool("listTickets"); expect(tools).toContainTool("getTicket"); }); test("`getTicket` returns the API's ticket", async ({ mcp }) => { const result = await mcp.tools.call("getTicket", { id: "T-1" }); expect(result.json()).toEqual({ status: 200, ok: true, data: { id: "T-1", title: "Cannot log in", status: "open" } }); }); test("the request goes to https://desk.example/v1", async ({ mcp }) => { await mcp.tools.call("getTicket", { id: "T-1" }); expect(received.at(-1)).toEqual({ method: "GET", url: "https://desk.example/v1/tickets/T-1" }); }); ``` **Hint:** `@App` has an `adapters` list, next to `tools`. The adapter needs three options. **Solution:** `OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec })` reads the spec when the server starts and makes a tool for each of its two operations. Each call adds the operation's path to `baseUrl`, with `{id}` filled in from the tool's input, and returns the API's status and body. ### Challenge: Send the API's token The Desk API requires a bearer token, and every call fails with `Authentication required for tool 'getTicket'`. The Desk team issued the token `desk-service-token` for the help desk server. Make the adapter send it, without the model ever seeing it. Initial call configuration: ```js { tool: "getTicket", arguments: { id: "T-1" } } ``` ```ts desk.app.ts active import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec })], }) export class DeskApp {} ``` **Solution file (alternative to the starter):** ```ts desk.app.ts solution import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec, staticAuth: { jwt: "desk-service-token" } })], }) export class DeskApp {} ``` ```ts desk-spec.ts export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, components: { securitySchemes: { DeskToken: { type: "http", scheme: "bearer" } } }, security: [{ DeskToken: [] }], paths: { "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }], responses: { "200": { description: "The ticket", content: { "application/json": { schema: { type: "object" } } } } }, }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. export const received: { url: string; authorization: string | null }[] = []; const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const request = new Request(input, init); if (new URL(request.url).hostname !== "desk.example") return realFetch(input, init); const authorization = request.headers.get("authorization"); received.push({ url: request.url, authorization }); if (authorization !== "Bearer desk-service-token") return Promise.resolve(Response.json({ message: "Invalid token" }, { status: 401 })); return Promise.resolve(Response.json({ id: "T-1", title: "Cannot log in", status: "open" })); }; ``` **Hidden fixture/test file (runs with the example):** ```ts token.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { received } from "./desk.example"; test("`getTicket` works", async ({ mcp }) => { const result = await mcp.tools.call("getTicket", { id: "T-1" }); expect(result).toBeSuccessful(); expect(result.json()).toMatchObject({ status: 200, ok: true }); }); test("the API gets `Authorization: Bearer desk-service-token`", async ({ mcp }) => { await mcp.tools.call("getTicket", { id: "T-1" }); expect(received.at(-1)?.authorization).toBe("Bearer desk-service-token"); }); test("the token isn't part of the tool's input", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t: { name: string }) => t.name === "getTicket"); expect(Object.keys(tool.inputSchema.properties)).toEqual(["id"]); }); ``` **Hint:** The spec names an HTTP bearer scheme. One adapter option gives every call the same credentials, and a bearer scheme reads the `jwt` field. **Solution:** `staticAuth: { jwt: "desk-service-token" }` gives every call that credential, and the adapter sends it where the spec's `DeskToken` scheme says: `Authorization: Bearer desk-service-token`. It stays on the server, out of every tool's input and result. In a real server the value comes from the environment, `staticAuth: { jwt: process.env.DESK_API_TOKEN }`, never from the source code. Adding the scheme to the model's input with `securitySchemesInInput` would make the calls work too, but the model would have to know the token, which is what the last check refuses. ### Challenge: Keep deleting out of the model's reach The model must not be able to delete tickets, or reach the API's admin operations. Make `deleteTicket`, and every operation tagged `admin`, impossible to call through the server, and keep the rest. Initial call configuration: ```js { tool: "listTickets", arguments: {} } ``` ```ts desk.app.ts active import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec })], }) export class DeskApp {} ``` **Solution file (alternative to the starter):** ```ts desk.app.ts solution import "./desk.example"; import { App } from "@frontmcp/sdk"; import { OpenapiAdapter } from "@frontmcp/adapters"; import { spec } from "./desk-spec"; @App({ id: "desk", name: "Desk", adapters: [ OpenapiAdapter.init({ name: "desk", baseUrl: "https://desk.example/v1", spec, generateOptions: { filterFn: (op) => op.method !== "delete" && !op.tags?.includes("admin") }, }), ], }) export class DeskApp {} ``` ```ts desk-spec.ts const ok = { "200": { description: "OK", content: { "application/json": { schema: { type: "object" } } } } }; const id = [{ name: "id", in: "path", required: true, schema: { type: "string" } }]; export const spec = { openapi: "3.0.3", info: { title: "Desk API", version: "1.0.0" }, paths: { "/tickets": { get: { operationId: "listTickets", summary: "List support tickets, newest first", tags: ["tickets"], responses: ok }, post: { operationId: "createTicket", summary: "Open a support ticket", tags: ["tickets"], responses: ok }, }, "/tickets/{id}": { get: { operationId: "getTicket", summary: "Get one support ticket by its id", tags: ["tickets"], parameters: id, responses: ok }, delete: { operationId: "deleteTicket", summary: "Delete a support ticket", tags: ["tickets"], parameters: id, responses: ok }, }, "/admin/agents": { get: { operationId: "listAgents", summary: "List support agents, with their roles", tags: ["admin"], responses: ok }, }, "/admin/agents/{id}": { put: { operationId: "setAgentRole", summary: "Change a support agent's role", tags: ["admin"], parameters: id, responses: ok }, }, }, }; ``` ```ts desk.example.ts // Plays the Desk API at https://desk.example, which the Playground can't reach. export const received: { method: string; path: string }[] = []; const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const request = new Request(input, init); const url = new URL(request.url); if (url.hostname !== "desk.example") return realFetch(input, init); received.push({ method: request.method, path: url.pathname }); return Promise.resolve(Response.json({ ok: true })); }; ``` **Hidden fixture/test file (runs with the example):** ```ts reach.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { received } from "./desk.example"; test("`deleteTicket` can't be called, even by name", async ({ mcp }) => { expect(await mcp.tools.list()).not.toContainTool("deleteTicket"); expect(await mcp.tools.call("deleteTicket", { id: "T-2" })).toBeError(); expect(received.some((r) => r.method === "DELETE")).toBe(false); }); test("neither can the admin operations", async ({ mcp }) => { await mcp.tools.call("listAgents", {}); await mcp.tools.call("setAgentRole", { id: "sam" }); expect(received.some((r) => r.path.startsWith("/v1/admin"))).toBe(false); }); test("the ticket operations that remain still work", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t: { name: string }) => t.name); expect(names).toEqual(["createTicket", "getTicket", "listTickets"]); expect(await mcp.tools.call("getTicket", { id: "T-1" })).toBeSuccessful(); }); ``` **Hint:** Hiding a tool from `tools/list` leaves it callable by name. Look for the option that decides which operations become tools in the first place, and which gets each operation's method and tags. **Solution:** `generateOptions.filterFn` runs for each operation, and an operation it returns `false` for never becomes a tool, so there's nothing to call: `deleteTicket`, `listAgents` and `setAgentRole` get an unknown-tool error, and the API receives nothing. Checking `op.tags` keeps out admin operations added to the spec later too. `excludeOperations: ["deleteTicket", "listAgents", "setAgentRole"]` would pass today, but not after the next admin operation. `toolTransforms` with `hideFromDiscovery` only takes tools out of the list, and the first check calls `deleteTicket` by name. --- # Testing and Shipping > How to test a FrontMCP server end to end with @frontmcp/testing, deploy it somewhere clients can reach, and run several instances of it behind a load balancer. Source: https://frontmcp.dev/learn/testing-and-shipping [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A FrontMCP server that works in the Playground has two more jobs before anyone relies on it: it has to keep working as you change it, and it has to run somewhere clients can reach. This chapter covers both: testing the server end to end, deploying it, and running several copies of it. **In this chapter** - [How to test a server end to end](https://frontmcp.dev/learn/testing-your-server) - [How to build and deploy a server](https://frontmcp.dev/learn/deploying-your-server) - [How to run several instances behind a load balancer](https://frontmcp.dev/learn/running-several-instances) ## Testing your server `@frontmcp/testing` starts your server, connects a real MCP client to it, and gives each test that client as `mcp`. You check what a model would see: which tools are listed, what a call returns, what an error looks like. Open the **Tests** tab: ```ts tickets.test.ts active import { test, expect } from "@frontmcp/testing"; test("lists get_ticket", async ({ mcp }) => { expect(await mcp.tools.list()).toContainTool("get_ticket"); }); test("returns a ticket by id", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ id: "T-1", title: "Cannot log in", status: "open" }); }); test("fails with a readable message for an unknown ticket", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-9" }); expect(result).toBeError(); expect(result).toHaveTextContent("There's no ticket T-9"); }); ``` ```ts get-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id. Returns the ticket's title and status.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` The same file runs in your project with `npx frontmcp test`. ### [Testing Your Server](https://frontmcp.dev/learn/testing-your-server) Learn the `mcp` fixture and the MCP matchers, what `result.json()` really returns, how to tell tool errors from protocol errors, how to test resources, prompts and tools that ask the user, and how to run tests in a project. ## Building and deploying `frontmcp build` packages your server for a target: a Node bundle, Vercel, AWS Lambda or a Cloudflare Worker. A deployed server runs in production mode, and a few things change there: - The MCP path in `frontmcp.config.ts` reaches the server only through the `frontmcp` command (`frontmcp dev` and the builds). Started any other way, it answers at `/` until you set `http.entryPath`, so a client pointed at `/mcp` gets `404`. - FrontMCP hides the message of any plain `Error` a tool throws. Fail with [`PublicMcpError`](https://frontmcp.dev/learn/your-first-tool#returning-results-and-errors) for anything the model should read. - Set `MCP_SESSION_SECRET` in production. Changed in 1.11.3: before, startup did not check this secret. HTTP startup now fails without it unless `transport.defaultProtocolVersion` is `"2026-07-28"`. With that fallback, startup warns and `/readyz` reports a degraded `session-secret` probe; older clients cannot initialize. Distributed deployments require the secret for session encryption in development too. ### [Deploying Your Server](https://frontmcp.dev/learn/deploying-your-server) Learn how to choose a target, set the endpoint path, give production mode the secrets it needs, run the build in a container, check a deployed server and point a client at it. ## Running several instances Behind a load balancer, each request goes to whichever instance it likes, and each instance has its own memory. Clients on MCP 2026-07-28 keep no session, so they need only the same secrets on every instance. Anything a provider keeps belongs in a store every instance reaches, and older clients' sessions and rate limits are shared through Redis. ### [Running Several Instances](https://frontmcp.dev/learn/running-several-instances) Learn what instances must share, which secrets every instance needs, how to share sessions and rate limits through Redis, what happens when Redis can't be reached, and the traps to avoid. [Auth in production](https://frontmcp.dev/reference/auth/production) has the full checklist, and [Deployment](https://frontmcp.dev/reference/deployment/production-build) has every target's options. ## What's next? Start the chapter with [Testing Your Server](https://frontmcp.dev/learn/testing-your-server). After it, [Escape Hatches](https://frontmcp.dev/learn/escape-hatches) covers what to do when FrontMCP's usual path isn't enough: reading the raw request, calling other services, and running FrontMCP outside a Node server. --- # Testing Your Server > End-to-end tests for a FrontMCP server with @frontmcp/testing: the mcp fixture, MCP matchers, results, errors, elicitation, plugins and hooks, and frontmcp test. Source: https://frontmcp.dev/learn/testing-your-server [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Calling a tool in the Call tab tells you it works today. A test tells you it still works after the next change. FrontMCP's testing library, `@frontmcp/testing`, starts your server, connects a real MCP client to it, and lets you check what a model would see: which tools are listed, what a call returns, and what an error looks like. **You will learn** - How to write a test with `test`, the `mcp` fixture and `expect` - What `result.json()` returns, and why a plain value comes back as `{ value }` - How to test tool errors and protocol errors, and why they're checked differently - How to test resources, prompts, tools that ask the user, and plugins and hooks - How to run the same tests in your project with `frontmcp test` ## Your first test A test file imports `test` and `expect` from `@frontmcp/testing`. Each `test()` gets an `mcp` fixture: an MCP client, already connected to your server. Open the **Tests** tab and the file runs by itself: ```ts tickets.test.ts active import { test, expect } from "@frontmcp/testing"; test.describe("get_ticket", () => { test("is listed, with a description and a required id", async ({ mcp }) => { const tools = await mcp.tools.list(); expect(tools).toContainTool("get_ticket"); const tool = tools.find((t) => t.name === "get_ticket"); expect(tool?.description).toContain("ticket"); expect(tool?.inputSchema.required).toEqual(["id"]); }); test("returns the ticket", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-2" }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ id: "T-2", title: "Invoice total is wrong", status: "closed" }); }); }); ``` ```ts get-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id. Returns the ticket's title and status.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}. Search by title with search_tickets.`)); return ticket; } } ``` Change the expected title and watch the test fail: the Tests tab shows what it expected and what it got. - `test(name, fn)` declares a test. `test.describe(name, fn)` groups tests under a heading. - `mcp.tools.list()` returns the tools exactly as `tools/list` sends them, which is what a model reads. Testing names, descriptions and schemas protects the contract, not only the code. - `mcp.tools.call(name, args)` sends a `tools/call` and wraps the result. - `expect` is Jest's `expect` with MCP matchers added: `toContainTool` checks a tool list, `toBeSuccessful` a call's outcome. Each test sends real JSON-RPC to a running server. Tick **Include requests sent by tests** in the Wire tab to see them. ## Reading results `mcp.tools.call()` returns a wrapper around the result. `result.json()` parses the result's **first text block**, and that has a consequence people don't expect: ```ts count-open.test.ts active import { test, expect } from "@frontmcp/testing"; test("a plain value comes back wrapped in { value }", async ({ mcp }) => { const result = await mcp.tools.call("count_open", {}); expect(result.json()).toEqual({ value: 2 }); expect(result.text()).toBe('{"value":2}'); expect(result).toHaveTextContent('"value":2'); }); test("an object comes back as it is", async ({ mcp }) => { const result = await mcp.tools.call("ticket_stats", {}); expect(result.json()).toEqual({ open: 2, closed: 1 }); expect(result.raw.structuredContent).toEqual({ open: 2, closed: 1 }); }); ``` ```ts count-open.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; import { tickets } from "./store"; @Tool({ name: "count_open", description: "How many tickets are open", inputSchema: {} }) export class CountOpen extends ToolContext { async execute() { return tickets.filter((t) => t.status === "open").length; } } @Tool({ name: "ticket_stats", description: "Count open and closed tickets", inputSchema: {} }) export class TicketStats extends ToolContext { async execute() { const open = tickets.filter((t) => t.status === "open").length; return { open, closed: tickets.length - open }; } } ``` ```ts store.ts export const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; ``` `count_open` returns the number `2`, but FrontMCP sends plain values as `{"value":2}`, so that's the text `json()` parses. An object is sent as it is. `result.text()` gives you the raw text, `toHaveTextContent()` checks that it contains a string, and `result.raw` is the whole MCP result: `content`, `structuredContent`, `isError` and `_meta`. Return objects from your tools. They're easier for a model to read, and easier to test. ## Testing errors A call can fail in two ways, and they're checked differently. A **tool error** is a normal result with `isError: true`: the request was fine, but the tool couldn't do it. A **protocol error** is a JSON-RPC `error` response with a numeric code: the request itself couldn't be handled. ```ts errors.test.ts active import { test, expect } from "@frontmcp/testing"; test.describe("tool errors", () => { test("an unknown ticket fails with a message the model can read", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-9" }); expect(result).toBeError(); expect(result).toHaveTextContent("There's no ticket T-9"); expect(result.raw._meta?.code).toBe("PUBLIC_ERROR"); }); test("a malformed id is rejected before execute() runs", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "ticket two" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); }); test.describe("protocol errors", () => { test("reading a resource that doesn't exist is error -32602", async ({ mcp }) => { const content = await mcp.resources.read("docs://no-such-page"); expect(content).toBeError(-32602); }); }); ``` ```ts get-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id. Returns the ticket's title and status.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}. Search by title with search_tickets.`)); return ticket; } } ``` ```ts refund-policy.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "refund-policy", uri: "docs://refund-policy", mimeType: "text/markdown", description: "When customers can get a refund", }) export class RefundPolicy extends ResourceContext { async execute(uri: string) { return { contents: [{ uri, mimeType: "text/markdown", text: "# Refunds\n\nFull refund within 30 days of purchase." }] }; } } ``` - `toBeError()` with no argument passes for either kind. - `toBeError(code)` with a number compares a **JSON-RPC error code**, so it only matches protocol errors, like `-32602` for a resource that doesn't exist. (That's the code under protocol 2026-07-28, which the Playground speaks. Older protocol versions use `-32002` for it.) - Tool errors have no JSON-RPC code. Their kind is in `result.raw._meta.code`, which `toBeError(code)` with a string compares: `INVALID_INPUT` when the arguments didn't match the schema, `PUBLIC_ERROR` for `this.fail(new PublicMcpError(...))` (or the code you gave the error), and `TOOL_EXECUTION_ERROR` when `execute()` threw a plain `Error`. The [error codes](https://frontmcp.dev/reference/errors) page lists them all. > **Pitfall: toBeError(-32602) doesn't match bad tool input** > > Invalid params is `-32602` in JSON-RPC, so it's tempting to write `expect(result).toBeError(-32602)` for a tool call with bad arguments. It fails: FrontMCP reports bad tool input as a tool error, with `_meta.code` set to `"INVALID_INPUT"`, so that the model can read what was wrong and try again. Pass the code as a string instead: `toBeError("INVALID_INPUT")` checks `result.raw._meta?.code`. ## Testing resources and prompts Resources and prompts have their own methods on `mcp` and their own matchers: ```ts content.test.ts active import { test, expect } from "@frontmcp/testing"; test("the refund policy is listed and is Markdown", async ({ mcp }) => { expect(await mcp.resources.list()).toContainResource("docs://refund-policy"); const policy = await mcp.resources.read("docs://refund-policy"); expect(policy).toHaveMimeType("text/markdown"); expect(policy).toHaveTextContent("30 days"); }); test("summarize_ticket asks about the right ticket", async ({ mcp }) => { expect(await mcp.prompts.list()).toContainPrompt("summarize_ticket"); const prompt = await mcp.prompts.get("summarize_ticket", { id: "T-1" }); expect(prompt).toHaveMessages(1); expect(prompt.messages[0].role).toBe("user"); expect(prompt.messages[0].content).toMatchObject({ type: "text", text: expect.stringContaining("T-1") }); }); ``` ```ts refund-policy.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "refund-policy", uri: "docs://refund-policy", mimeType: "text/markdown", description: "When customers can get a refund", }) export class RefundPolicy extends ResourceContext { async execute(uri: string) { return { contents: [{ uri, mimeType: "text/markdown", text: "# Refunds\n\nFull refund within 30 days of purchase." }] }; } } ``` ```ts summarize.prompt.ts import { Prompt, PromptContext } from "@frontmcp/sdk"; @Prompt({ name: "summarize_ticket", description: "Summarize a support ticket for a handover", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class SummarizeTicket extends PromptContext { async execute({ id }: { id: string }) { return { messages: [ { role: "user" as const, content: { type: "text" as const, text: `Summarize ticket ${id} in three bullet points for the next agent.` } }, ], }; } } ``` | Method | Returns | Matchers | | --- | --- | --- | | `mcp.resources.list()` | the resources from `resources/list` | `toContainResource(uri)` | | `mcp.resources.read(uri)` | a wrapper with `text()`, `json()`, `mimeType()` and `raw` | `toHaveMimeType(type)`, `toHaveTextContent(text)`, `toBeError(code)` | | `mcp.prompts.list()` | the prompts from `prompts/list` | `toContainPrompt(name)` | | `mcp.prompts.get(name, args)` | a wrapper with `messages` and `description` | `toHaveMessages(count)` | ## Testing a tool that asks the user When a tool calls `this.elicit()`, nobody is there to answer. `mcp.onElicitation()` sets the answer the test client gives. The handler receives the question, with its `message` and `requestedSchema`, and returns `{ action, content }`: ```ts close-ticket.test.ts active import { test, expect } from "@frontmcp/testing"; test("asks with a confirm checkbox, and closes on yes", async ({ mcp }) => { let schema: unknown; mcp.onElicitation((request) => { schema = request.requestedSchema; return { action: "accept", content: { confirm: true } }; }); const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(schema).toMatchObject({ properties: { confirm: { type: "boolean" } } }); expect(result.json()).toEqual({ id: "T-1", closed: true }); }); test("stays open when the user declines", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "decline" })); const result = await mcp.tools.call("close_ticket", { id: "T-2" }); expect(result.json()).toEqual({ id: "T-2", closed: false }); }); ``` ```ts close-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket. Asks the user to confirm first.", inputSchema: { id: z.string() }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const answer = await this.elicit(`Close ${id}?`, z.object({ confirm: z.boolean() })); return { id, closed: answer.status === "accept" && answer.content?.confirm === true }; } } ``` Register the handler before the call that asks. A test that answers `decline` and `cancel` as well as `accept` covers the paths users actually take. [Asking the User Mid-Call](https://frontmcp.dev/learn/asking-the-user) explains what happens between the question and the answer. ## Testing plugins and hooks A plugin works around your tools, so a call's result often can't show what it did. A cached answer carries the same data as a fresh one, and a refused call doesn't say whether the tool ran first. Two techniques do most of the work: count what the tool does, and call as more than one user. This help desk caches ticket lookups, freezes ticket changes with a hook of its own, lets only agents close tickets, and allows two exports an hour: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts plugins.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; import { FreezePlugin } from "./freeze.plugin"; import { desk } from "./desk"; const asNour = { authContext: { user: { sub: "nour", roles: ["agent"] } } }; test("a repeat lookup is answered from the cache", async ({ mcp }) => { const before = desk.lookups; const first = await mcp.tools.call("get_ticket", { id: "T-2" }); const second = await mcp.tools.call("get_ticket", { id: "T-2" }); expect(desk.lookups - before).toBe(1); expect(first.raw._meta?.cache).toBeUndefined(); expect(second.raw._meta?.cache).toBe("hit"); expect(second.json()).toEqual(first.json()); }); test("only an agent sees close_ticket", async ({ mcp }) => { expect(await mcp.tools.list()).not.toContainTool("close_ticket"); const server = await FrontMcpInstance.createDirect(config); try { const { tools } = await server.listTools(asNour); expect(tools.map((t) => t.name)).toContain("close_ticket"); } finally { await server.dispose(); } }); test("the freeze refuses an agent's call before execute() runs", async () => { const server = await FrontMcpInstance.createDirect(config); try { // createDirect() throws the error a client would get as a result await expect(server.callTool("close_ticket", { id: "T-1" }, asNour)).rejects.toMatchObject({ code: "CHANGE_FREEZE" }); expect(desk.tickets.get("T-1")?.status).toBe("open"); } finally { await server.dispose(); } }); test("with the freeze lifted, the agent can close a ticket", async () => { const server = await FrontMcpInstance.createDirect({ ...config, plugins: [FreezePlugin.init({ frozen: false })] }); try { const result = await server.callTool("close_ticket", { id: "T-3" }, asNour); expect(result.structuredContent).toEqual({ id: "T-3", status: "closed" }); } finally { await server.dispose(); } }); test("the third export in an hour is refused", async ({ mcp }) => { expect(await mcp.tools.call("export_tickets")).toBeSuccessful(); expect(await mcp.tools.call("export_tickets")).toBeSuccessful(); expect(await mcp.tools.call("export_tickets")).toBeError("RATE_LIMIT_EXCEEDED"); }); ``` ```ts freeze.plugin.ts import { DynamicPlugin, FlowCtxOf, Plugin, PublicMcpError, ToolHook } from "@frontmcp/sdk"; type FreezeOptions = { frozen: boolean }; @Plugin({ name: "freeze", description: "Refuses every tool that changes tickets during a change freeze" }) export class FreezePlugin extends DynamicPlugin { constructor(private readonly options: FreezeOptions) { super(); } @ToolHook.Will("execute", { filter: (ctx) => !ctx.state.tool?.metadata.annotations?.readOnlyHint }) async refuse(ctx: FlowCtxOf<"tools:call-tool">) { if (!this.options.frozen) return; throw new PublicMcpError(`Ticket changes are frozen until the release ships, so ${ctx.state.tool?.metadata.name} is unavailable.`, "CHANGE_FREEZE"); } } ``` ```ts tools.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { desk } from "./desk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true }, cache: { ttl: 300 }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return desk.lookup(id); } } @Tool({ name: "close_ticket", description: "Close a support ticket. Support agents only.", inputSchema: { id: z.string() }, authorities: "agent" }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = desk.tickets.get(id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); ticket.status = "closed"; return { id, status: ticket.status }; } } @Tool({ name: "export_tickets", description: "Export every ticket as CSV. At most 2 exports an hour.", inputSchema: {}, annotations: { readOnlyHint: true }, rateLimit: { maxRequests: 2, windowMs: 60 * 60_000 }, }) export class ExportTickets extends ToolContext { async execute() { return { csv: [...desk.tickets.values()].map((t) => `${t.id},${t.status}`).join("\n") }; } } ``` ```ts desk.ts import { PublicMcpError } from "@frontmcp/sdk"; // Stands in for the ticket database, and counts the lookups it answers. export const desk = { lookups: 0, tickets: new Map([ ["T-1", { id: "T-1", title: "Cannot log in", status: "open" }], ["T-2", { id: "T-2", title: "Invoice total is wrong", status: "open" }], ["T-3", { id: "T-3", title: "Login link expired", status: "open" }], ]), lookup(id: string) { desk.lookups++; const ticket = desk.tickets.get(id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}.`); return { ...ticket }; }, }; ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { CloseTicket, ExportTickets, GetTicket } from "./tools"; import { FreezePlugin } from "./freeze.plugin"; @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, CloseTicket, ExportTickets], plugins: [CachePlugin.init({ type: "memory", keyByIdentity: false })], }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], plugins: [FreezePlugin.init({ frozen: true })], authorities: { claimsMapping: { roles: "roles" }, profiles: { agent: { roles: { any: ["agent"] } } }, }, }; @FrontMcp(config) export default class Server {} ``` What each test relies on: - **Count the work behind the tool.** `desk` counts the lookups it answers, so the cache test can tell a hit from a miss: two calls, one lookup. The cache also marks a hit with `_meta.cache: "hit"`. The freeze test checks the ticket is still open, which proves the hook stopped the call before `execute()` changed anything, and not after. - **Call as the user the plugin cares about.** The Playground's client is anonymous and has no roles, so `authorities` hides `close_ticket` from it, and a call by name is refused with `AUTHORITY_DENIED` before the freeze hook is reached. [`createDirect()`](https://frontmcp.dev/learn/running-frontmcp-anywhere) runs the same configuration in-process as `nour`, an agent: a second client, with its own list. `createDirect()` throws a failed call's error rather than returning it, so the test checks its `code` with `rejects`. The cache cares about the caller too: it keeps one entry per caller unless `keyByIdentity` is `false`, as here, and under MCP 2026-07-28 the Playground's client is a new anonymous caller on every request ([Caching Results](https://frontmcp.dev/learn/caching-results#sharing-answers-between-callers)). - **Build a second server to test another setting.** The freeze is on in `config`, so the test that lifts it starts a server with `FreezePlugin.init({ frozen: false })` in place of the original. - **Tests share a server, and its memory.** A cache entry stored by one test answers the next test's call, and a rate limit counts every test's calls. So the cache test measures `desk.lookups - before` and uses a ticket no other test looks up, and only one test calls `export_tickets`. Under `frontmcp test`, the tests of a file share one server in the same way. [Limiting and Timing Out Calls](https://frontmcp.dev/learn/limiting-calls) covers what a refused call returns. In a project, `createDirect()` works the same way. To call over HTTP as a signed-in user instead, `server.createClient({ token })` connects another client with a token from the `auth` fixture: see [Calling as a signed-in user](https://frontmcp.dev/reference/testing/auth#calling-as-a-signed-in-user). ## Running tests in your project The tests on this page are the same code you run in a project. There, instead of a Playground wrapping your files, `test.use()` points at your server's entry file. A project made by `frontmcp create` already has what `frontmcp test` needs, Jest 30 included; in another project, install the package, Jest and `tsx`, which starts your server: ```bash npm install -D @frontmcp/testing jest tsx ``` ```ts e2e/tickets.e2e.spec.ts import { test, expect } from "@frontmcp/testing"; test.use({ server: "./src/main.ts" }); test.describe("get_ticket", () => { test("returns the ticket", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-2" }); expect(result).toBeSuccessful(); expect(result.json()).toMatchObject({ id: "T-2", status: "closed" }); }); }); ``` ```bash npx frontmcp test ``` `@frontmcp/testing` starts the server from `./src/main.ts` on a free port, connects the client, runs the tests, and stops the server. `frontmcp test` sets up Jest for you, and by default it looks for `e2e/**/*.e2e.spec.ts` and `src/**/*.spec.ts`, so name your files that way (the Playground also accepts `*.test.ts`). Useful flags: ```bash npx frontmcp test --runInBand # one file at a time, the usual choice for E2E tests npx frontmcp test --watch # rerun on change npx frontmcp test --coverage # collect coverage ``` `test.use()` takes more options, such as `port`, `env` and `publicMode`; [`test.use(options)`](https://frontmcp.dev/reference/testing#testuseoptions) lists them. The [`@frontmcp/testing` reference](https://frontmcp.dev/reference/testing) covers the rest of the test API. > **Note: Where the Playground and frontmcp test differ** > > The Playground's client speaks MCP 2026-07-28. `@frontmcp/testing` defaults to 2025-06-18; set `test.use({ protocolVersion: "2026-07-28" })` to use the same revision. The clients differ in a few ways: > > - By default it speaks protocol version 2025-06-18, where a resource that doesn't exist is error `-32002` rather than `-32602`. > - It asks for progress only after `mcp.notifications.collectProgress()`. Both clients request debug logs automatically, and receive the call's notifications before its result. [Checking notifications](https://frontmcp.dev/reference/testing#checking-notifications) shows a test for both. > - Without `mcp.onElicitation()`, it answers every question with `decline`, where the Playground fails the test. ## Recap - `test(name, async ({ mcp }) => ...)` runs against your server with a connected client. `test.describe` groups tests, and `test.use({ server })` points at your entry file in a project. - Test what the model sees: `mcp.tools.list()` with `toContainTool`, and each tool's description and schema. - `result.json()` parses the first text block. A plain value `5` comes back as `{ value: 5 }`, so return objects. - `toBeError()` passes for any error. `toBeError(-32602)` checks a JSON-RPC code, which only protocol errors have; `toBeError("INVALID_INPUT")` checks a tool error's `_meta.code`. - `toContainResource`, `toHaveMimeType`, `toContainPrompt` and `toHaveMessages` cover resources and prompts. `mcp.onElicitation()` answers a tool's questions. - To test a plugin or a hook, count the work behind the tool, and call as each kind of user it treats differently, with `createDirect()` in the Playground. Tests share a server, so cache entries and rate-limit counts carry over from one test to the next. - Run the tests with `npx frontmcp test`. ## Try some challenges Each challenge runs hidden checks against your code, and runs your visible tests too. Edit the code, then press **Check**. ### Challenge: Fix the tests, not the server The server is right, and both tests are wrong: one misreads what `json()` returns, and the other expects the wrong kind of error. Fix the tests so they pass, without changing the tools. ```ts tickets.test.ts active import { test, expect } from "@frontmcp/testing"; test("counts the open tickets", async ({ mcp }) => { const result = await mcp.tools.call("count_open", {}); expect(result.json()).toBe(2); }); test("rejects an id that isn't T-", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "ticket two" }); expect(result).toBeError(-32602); }); ``` **Solution file (alternative to the starter):** ```ts tickets.test.ts solution import { test, expect } from "@frontmcp/testing"; test("counts the open tickets", async ({ mcp }) => { const result = await mcp.tools.call("count_open", {}); expect(result.json()).toEqual({ value: 2 }); }); test("rejects an id that isn't T-", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "ticket two" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); ``` ```ts tickets.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; @Tool({ name: "count_open", description: "How many tickets are open", inputSchema: {} }) export class CountOpen extends ToolContext { async execute() { return tickets.filter((t) => t.status === "open").length; } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } ``` **Hidden fixture/test file (runs with the example):** ```ts server.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`count_open` still returns the plain number 2", async ({ mcp }) => { const result = await mcp.tools.call("count_open", {}); expect(result.raw.structuredContent).toEqual({ value: 2 }); }); test("`get_ticket` still rejects a malformed id with INVALID_INPUT", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "ticket two" }); expect(result.raw.isError).toBe(true); expect(result.raw._meta?.code).toBe("INVALID_INPUT"); }); ``` **Hint:** Look at the failure messages in the Checks tab. What text does `count_open` send? And does a tool error have a JSON-RPC code? **Solution:** `count_open` returns a plain number, which FrontMCP sends as `{"value":2}`, so `json()` is `{ value: 2 }`. And a bad argument is a tool error, not a protocol error: the result has `isError: true` and `_meta.code: "INVALID_INPUT"`, but no JSON-RPC code for `toBeError(-32602)` to match. The hidden checks make sure the tools weren't changed to fit the old tests. ### Challenge: Catch the bug, then fix it Users say `close_ticket` closes tickets even when they click **Decline**. Write a test that declines and expects `closed: false` (use `T-2`), watch it fail, then fix the tool so it passes. ```ts close-ticket.test.ts active import { test, expect } from "@frontmcp/testing"; test("closes the ticket when the user confirms", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirm: true } })); const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result.json()).toEqual({ id: "T-1", closed: true }); }); // Your test: the user declines, and the ticket stays open. ``` **Solution file (alternative to the starter):** ```ts close-ticket.test.ts solution import { test, expect } from "@frontmcp/testing"; test("closes the ticket when the user confirms", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirm: true } })); const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result.json()).toEqual({ id: "T-1", closed: true }); }); test("leaves the ticket open when the user declines", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "decline" })); const result = await mcp.tools.call("close_ticket", { id: "T-2" }); expect(result.json()).toEqual({ id: "T-2", closed: false }); }); ``` ```ts close-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; const closed = new Set(); @Tool({ name: "close_ticket", description: "Close a support ticket. Asks the user to confirm first.", inputSchema: { id: z.string().regex(/^T-\d+$/) }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const answer = await this.elicit(`Close ${id}?`, z.object({ confirm: z.boolean() })); if (answer.content?.confirm === false) return { id, closed: false }; closed.add(id); return { id, closed: true }; } } ``` **Solution file (alternative to the starter):** ```ts close-ticket.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; const closed = new Set(); @Tool({ name: "close_ticket", description: "Close a support ticket. Asks the user to confirm first.", inputSchema: { id: z.string().regex(/^T-\d+$/) }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const answer = await this.elicit(`Close ${id}?`, z.object({ confirm: z.boolean() })); if (answer.status !== "accept" || answer.content?.confirm !== true) return { id, closed: false }; closed.add(id); return { id, closed: true }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts checks.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("declining leaves the ticket open", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "decline" })); expect((await mcp.tools.call("close_ticket", { id: "T-3" })).json()).toEqual({ id: "T-3", closed: false }); }); test("cancelling leaves the ticket open", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "cancel" })); expect((await mcp.tools.call("close_ticket", { id: "T-4" })).json()).toEqual({ id: "T-4", closed: false }); }); test("confirming still closes it", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirm: true } })); expect((await mcp.tools.call("close_ticket", { id: "T-5" })).json()).toEqual({ id: "T-5", closed: true }); }); ``` **Hint:** A declined question has `status: "decline"` and no `content` at all. What does `answer.content?.confirm === false` do when `content` is missing? **Solution:** The tool only refused when `confirm` was exactly `false`. A decline or a cancel has no `content`, so `answer.content?.confirm` is `undefined`, the check didn't match, and the tool closed the ticket. The fix turns the condition around: close only on `accept` with `confirm === true`. Your decline test failed before the fix and passes after it, which is what makes it worth keeping. ### Challenge: Make the tests pass These tests describe what the refund policy and the handover prompt should be. The server doesn't match them yet. Change the resource and the prompt, not the tests, until every test passes. ```ts content.test.ts active import { test, expect } from "@frontmcp/testing"; test("the refund policy is Markdown", async ({ mcp }) => { expect(await mcp.resources.list()).toContainResource("docs://refund-policy"); const policy = await mcp.resources.read("docs://refund-policy"); expect(policy).toHaveMimeType("text/markdown"); expect(policy).toHaveTextContent("# Refunds"); }); test("the handover prompt is a single user message about the ticket", async ({ mcp }) => { expect(await mcp.prompts.list()).toContainPrompt("summarize_ticket"); const prompt = await mcp.prompts.get("summarize_ticket", { id: "T-7" }); expect(prompt).toHaveMessages(1); expect(prompt.messages[0].role).toBe("user"); expect(prompt.messages[0].content).toMatchObject({ text: expect.stringContaining("T-7") }); }); ``` ```ts refund-policy.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "refund-policy", uri: "docs://refund-policy", mimeType: "text/plain", description: "When customers can get a refund", }) export class RefundPolicy extends ResourceContext { async execute(uri: string) { return { contents: [{ uri, mimeType: "text/plain", text: "Refunds: full refund within 30 days of purchase." }] }; } } ``` **Solution file (alternative to the starter):** ```ts refund-policy.resource.ts solution import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "refund-policy", uri: "docs://refund-policy", mimeType: "text/markdown", description: "When customers can get a refund", }) export class RefundPolicy extends ResourceContext { async execute(uri: string) { return { contents: [{ uri, mimeType: "text/markdown", text: "# Refunds\n\nFull refund within 30 days of purchase." }] }; } } ``` ```ts summarize.prompt.ts import { Prompt, PromptContext } from "@frontmcp/sdk"; @Prompt({ name: "summarize_ticket", description: "Summarize a support ticket for a handover", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class SummarizeTicket extends PromptContext { async execute({ id }: { id: string }) { return { messages: [ { role: "user" as const, content: { type: "text" as const, text: "You are a support agent handing over a ticket." } }, { role: "user" as const, content: { type: "text" as const, text: `Summarize ticket ${id} in three bullet points.` } }, ], }; } } ``` **Solution file (alternative to the starter):** ```ts summarize.prompt.ts solution import { Prompt, PromptContext } from "@frontmcp/sdk"; @Prompt({ name: "summarize_ticket", description: "Summarize a support ticket for a handover", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class SummarizeTicket extends PromptContext { async execute({ id }: { id: string }) { return { messages: [ { role: "user" as const, content: { type: "text" as const, text: `You're handing over a support ticket. Summarize ticket ${id} in three bullet points.` }, }, ], }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts checks.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("`docs://refund-policy` is text/markdown and starts with a heading", async ({ mcp }) => { const policy = await mcp.resources.read("docs://refund-policy"); expect(policy).toHaveMimeType("text/markdown"); expect(policy.text()?.startsWith("# ")).toBe(true); }); test("the resource still mentions the 30 days", async ({ mcp }) => { expect(await mcp.resources.read("docs://refund-policy")).toHaveTextContent("30 days"); }); test("`summarize_ticket` returns one user message naming the ticket", async ({ mcp }) => { const prompt = await mcp.prompts.get("summarize_ticket", { id: "T-8" }); expect(prompt).toHaveMessages(1); expect(prompt.messages[0]).toMatchObject({ role: "user", content: { type: "text", text: expect.stringContaining("T-8") } }); }); ``` **Hint:** The resource's MIME type appears twice: in `@Resource` and in what `execute()` returns. The prompt needs its two messages combined into one. **Solution:** The resource now says `text/markdown` in both places and its text is Markdown, and the prompt sends one user message that includes the ticket id. Writing the tests first and changing the server until they pass is a good way to pin down what a resource or prompt should look like before a client depends on it. --- # Deploying Your Server > How to take a FrontMCP server from frontmcp build to a running server clients can reach. Choosing a target, the endpoint path, production mode and its secrets, running in a container, health checks, and connecting a client. Source: https://frontmcp.dev/learn/deploying-your-server [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `frontmcp dev`, from the FrontMCP CLI, runs your server on your machine, restarts it when a file changes, and forgives a lot. A deployed server runs from a build, in production mode, somewhere clients can reach, and nobody is watching its log. This lesson takes the help desk from `frontmcp build` to a running server a client can connect to, and stops at the places where a server that worked in development stops working once it's deployed. **You will learn** - How `frontmcp build` packages your server, and which target to choose - Where the MCP endpoint is, and why to set `http.entryPath` in the server - What production mode hides from callers, and which secrets it needs - How to run the build in a container - How to check a deployed server, and point a client at it ## Building the server `frontmcp build` compiles your TypeScript and packages it for a **target**. Without `--target`, it builds each entry of `deployments` in `frontmcp.config.ts`, and a project from `frontmcp create --target node` lists one, `node`: ```bash npx frontmcp build ``` ```text [build:exec] bundle created: dist/node/help-desk.bundle.js (6.6 KB) [build:exec] manifest: dist/node/help-desk.manifest.json [build:exec] runner: dist/node/help-desk [build:exec] installer: dist/node/install-help-desk.sh ``` The file names come from `name` in `frontmcp.config.ts`. Start the bundle and ask it whether it's alive: ```bash PORT=3000 node dist/node/help-desk.bundle.js curl http://127.0.0.1:3000/healthz ``` ```json {"status":"ok","server":{"name":"help-desk","version":"1.0.0"},"runtime":{"platform":"darwin","runtime":"node","deployment":"standalone","env":"development"},"uptime":2.698} ``` The bundle is a few kilobytes because it's only your code. It imports `@frontmcp/sdk` and FrontMCP's other packages from `node_modules`, so it runs in a folder where your production dependencies are installed, with `npm ci --omit=dev`. ### Choosing a target The same `@FrontMcp` entry file builds for several platforms. Pick one with `--target`, or list it in `deployments` so that `npm run build` builds it: | Target | Runs as | Know this first | | --- | --- | --- | | `node` | An HTTP server, on a machine, a VM or in a container | Needs `node_modules` beside it. The rest of this lesson uses it. | | `vercel` | A Vercel function | One bundle with FrontMCP inside. In production mode when `NODE_ENV=production`, which Vercel sets. No `/readyz`. | | `lambda` | An AWS Lambda handler | Like `vercel`, but Lambda doesn't set `NODE_ENV`: set it yourself. The build needs `@codegenie/serverless-express` installed, which `frontmcp create --target lambda` adds. | | `cloudflare` | A Cloudflare Worker | Experimental. Can't use Redis, and keeps no sessions for clients before MCP 2026-07-28. | Each target has a page in the Reference: [Node.js and Docker](https://frontmcp.dev/reference/deployment/node), [Vercel](https://frontmcp.dev/reference/deployment/vercel), [AWS Lambda](https://frontmcp.dev/reference/deployment/aws-lambda) and [Cloudflare Workers](https://frontmcp.dev/reference/deployment/cloudflare-workers). ## Where the endpoint is A project from `frontmcp create` sets the MCP path in `frontmcp.config.ts`, as `transport: { http: { port: 3000, path: "/mcp" } }`. `frontmcp dev` reads it and says so when it starts: ```text [dev] listening on port: 3000 [dev] MCP endpoint path: /mcp ``` So you point your client at `http://localhost:3000/mcp`, and it works. But `frontmcp.config.ts` is read by the `frontmcp` command, never by your server. `frontmcp dev` passes the path on when it starts the server, and `frontmcp build` writes it into what it builds: the `node` bundle sets it as it starts, unless `FRONTMCP_HTTP_ENTRY_PATH` is already set, and the serverless builds write it into their setup file. Start the server any other way, like with `tsx` or from your own `tsc` output, and it serves MCP at `/`, so every request to `/mcp` fails: ```bash PORT=3000 npx tsx src/main.ts curl -s -w '%{http_code}\n' -X POST http://127.0.0.1:3000/mcp -H 'content-type: application/json' -d '{}' ``` ```text Error
              Cannot POST /mcp
              404 ``` A server you embed in other code with `createFetchHandler()`, as the tests below do, serves `/` too: it's given a configuration, and nothing else. Put the path in the server itself, and every way of starting it agrees: ```ts src/main.ts import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; import { HelpDesk } from "./help-desk.app"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp" }, // ✅ the same path however the server is started }) export default class Server {} ``` > **Note: Changed in 1.9: the node bundle serves the configured path** > > In 1.8.7, `node dist/node/.bundle.js` didn't pass the path on, so a container built from the Dockerfile that `frontmcp create` writes served MCP at `/`, and answered clients at `/mcp` with `404` until `http.entryPath` was set. A server has one MCP endpoint. The tests below send a call the way a client on MCP 2026-07-28 does, to `/mcp` and to `/`. Delete the `http` line in `config.ts` and watch them fail the way a server started without the path does: ```ts endpoint.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; // One tools/call, as a 2026-07-28 client sends it to this URL function getTicket(url: string) { return new Request(url, { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "get_ticket" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "get_ticket", arguments: { id: "T-1" }, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } test("the server answers at /mcp", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); const response = await handler(getTicket("https://desk.example.com/mcp")); expect(response.status).toBe(200); expect((await response.json()).result.structuredContent).toEqual({ id: "T-1", title: "Cannot log in", status: "open" }); }); test("and nowhere else", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); const response = await handler(getTicket("https://desk.example.com/")); expect(response.status).toBe(404); expect(await response.json()).toEqual({ error: "Not Found", entryPaths: ["/mcp"] }); }); ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp" }, }; ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id. Returns the ticket's title and status.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` The tests use [`createFetchHandler()`](https://frontmcp.dev/learn/running-frontmcp-anywhere#serving-mcp-from-any-runtime), which takes the same configuration as `@FrontMcp`, so they can send requests without a port. Its `404` is JSON and names the endpoint; FrontMCP's Node server answers a wrong path with Express's `Cannot POST /` page instead. ## Production mode A server is in production when `NODE_ENV` is `production` as it starts. (Vercel sets it for its functions, Lambda doesn't, and a Worker is in production once `wrangler deploy` bundles it.) Two things change that you'll notice. ### Errors the model can read In development, a tool that throws a plain `Error` sends the model its message and stack. In production, FrontMCP sends an error ID instead, and writes the message to the log next to it. That's right for a database error, and wrong for a message the model needs: Initial call configuration: ```js { tool: "sync_ticket", arguments: { id: "T-1" } } ``` ```ts tools.ts active import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "sync_ticket", description: "Copy a ticket to the CRM.", inputSchema: { id: z.string() } }) export class SyncTicket extends ToolContext { async execute({ id }: { id: string }): Promise<{ synced: string }> { throw new Error(`connect ECONNREFUSED 10.0.4.12:5432 while syncing ${id}`); } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { if (id !== "T-1") this.fail(new PublicMcpError(`There's no ticket ${id}. Ticket ids look like T-1.`)); return { id, title: "Cannot log in", status: "open" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SyncTicket, GetTicket] }) export class HelpDesk {} ``` ```ts production.test.ts import { test, expect } from "@frontmcp/testing"; import { createErrorHandler, FrontMcpInstance } from "@frontmcp/sdk"; import { HelpDesk } from "./tools"; // Formats errors the way tools/call does with NODE_ENV=production const production = createErrorHandler({ isDevelopment: false }); async function errorFrom(name: string, args: Record): Promise { const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }); try { await server.callTool(name, args); } catch (error) { return error; } finally { await server.dispose(); } throw new Error(`${name} didn't fail`); } test("a plain Error reaches the model as an error ID", async () => { const result = production.handle(await errorFrom("sync_ticket", { id: "T-1" })); expect(result.content[0].text).toBe(`Internal FrontMCP error. Please contact support with error ID: ${result._meta?.errorId}`); expect(result._meta?.code).toBe("TOOL_EXECUTION_ERROR"); }); test("a PublicMcpError keeps its message", async () => { const result = production.handle(await errorFrom("get_ticket", { id: "T-9" })); expect(result.content[0].text).toBe("There's no ticket T-9. Ticket ids look like T-1."); expect(result._meta?.code).toBe("PUBLIC_ERROR"); }); ``` The Call tab shows what development sends: the database's address, and a stack. The Playground formats errors the way development does, so the tests format the same errors with `createErrorHandler({ isDevelopment: false })`, which is what `NODE_ENV=production` means to `tools/call`. The `node` build, started with `NODE_ENV=production`, returns the same result: ```json {"content":[{"type":"text","text":"Internal FrontMCP error. Please contact support with error ID: err_e4fad6ec3f5b44e9"}],"isError":true,"_meta":{"errorId":"err_e4fad6ec3f5b44e9","code":"TOOL_EXECUTION_ERROR",…}} ``` Its log has `Internal error: Tool "sync_ticket" execution failed: connect ECONNREFUSED 10.0.4.12:5432 while syncing T-1`, with the stack and the same `errorId`. So fail with [`PublicMcpError`](https://frontmcp.dev/learn/your-first-tool#returning-results-and-errors) for anything the model should read, and let everything else become an ID you can look up. ### The secrets it needs In development on a non-distributed deployment, FrontMCP makes up the secrets it needs and logs a warning. In production it refuses to, so a deployed server needs them in its environment: | Variable | Needed when | Without it, in production | | --- | --- | --- | | `MCP_SESSION_SECRET` | Production HTTP with the default legacy fallback. | Startup fails with `SESSION_SECRET_REQUIRED`. | | `JWT_SECRET` | The server issues its own tokens: `local` or `remote` [auth](https://frontmcp.dev/learn/authenticating-clients). At least 32 bytes. | The server doesn't start. | | `VAULT_SECRET` | A tool [asks the user](https://frontmcp.dev/learn/asking-the-user) more than one question, and the server runs as [several instances](https://frontmcp.dev/learn/running-several-instances). | See the next lesson. | Changed in 1.11.3: before, startup did not check this secret. The Node HTTP server refuses to start in production without `MCP_SESSION_SECRET`. The error code is `SESSION_SECRET_REQUIRED`. Generate the secret once, keep it in your platform's secret store, and give it to the process: ```bash openssl rand -hex 32 # store the output as MCP_SESSION_SECRET ``` For a server whose clients all use MCP 2026-07-28, you can set `transport.defaultProtocolVersion: "2026-07-28"` instead. It starts without the secret with a warning; `/readyz` reports a degraded `session-secret` probe, and older clients cannot initialize. Stdio needs no session secret. Changed in 1.12.1: before, distributed deployments could encrypt session ids without `MCP_SESSION_SECRET` outside production. They now require it for session encryption in development too. With it set, the same `initialize` answers `200` with an `Mcp-Session-Id` header. Keep secrets out of the image and the repository: they belong in the environment the platform starts the process with. > **Note** > > FrontMCP logs `JWT_SECRET is not set` when a server with `static` or `local` auth starts, and not for a public one. Only `local` and `remote` auth use it, and a production server with `local` auth and no `JWT_SECRET` doesn't start. In production the server also prints a few `[Security]` lines about CORS, the address it listens on and host checks: they describe the configuration and change nothing. ## Running it in a container `frontmcp create --target node` writes a `ci/Dockerfile` that builds in one stage and runs in another. This is it, with its comments left out; the last line runs the bundle the build writes, named after the `name` in your `frontmcp.config.ts`: ```text title="ci/Dockerfile" FROM node:24-slim AS builder WORKDIR /app COPY package*.json package-lock.json* ./ RUN npm ci COPY . . RUN npm run build RUN npm prune --omit=dev FROM node:24-slim AS runner WORKDIR /app ENV NODE_ENV=production ENV FRONTMCP_BIND_ADDRESS=all RUN chown node:node /app COPY --from=builder --chown=node:node /app/node_modules ./node_modules COPY --from=builder --chown=node:node /app/dist ./dist COPY --from=builder --chown=node:node /app/package.json ./ USER node EXPOSE 3000 HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || 3000) + '/health').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))" CMD ["node", "dist/node/help-desk.bundle.js"] ``` ```bash docker build -f ci/Dockerfile -t help-desk . docker run -p 127.0.0.1:3000:3000 -e MCP_SESSION_SECRET="$(openssl rand -hex 32)" help-desk ``` The container logs `MCP HTTP (Express) on 0.0.0.0:3000`, and `docker inspect` reports it `healthy`. Three lines matter more than they look: - **`FRONTMCP_BIND_ADDRESS=all`.** FrontMCP listens on `127.0.0.1` unless told otherwise, and a published container port can't reach that address: `curl` gets `Empty reply from server`. - **`USER node`.** The server runs as the image's unprivileged user, not root. - **`HEALTHCHECK`.** It calls `/health` with Node's `fetch`, because the `node:24-slim` image has neither `curl` nor `wget`. `/health` answers like `/healthz`, and stays where it is if you move `/healthz` with `health.healthzPath`. (In 1.9.2 the check called `/healthz`.) You don't need `--init`: the server handles `SIGTERM` itself, finishes the requests in flight, and exits, so `docker stop` returns at once with exit code `0`. (Before 1.9.2 the generated Dockerfile had no health check and ran as root, and Node ignored `SIGTERM` as the container's first process, so `docker stop` waited ten seconds unless the container ran with `--init`.) ## Checking that it works A server that deploys isn't necessarily one clients can use. Check three things, in this order: 1. **`GET /healthz`** answers `200` while the process runs. It checks nothing else, so point liveness checks at it. 2. **`GET /readyz`** runs readiness probes, like pinging Redis once the server uses it, and answers `503` when one fails. Point a load balancer's readiness check at it. (Vercel and Lambda functions answer it with `404`, and so does a Worker until you turn it on.) 3. **A real MCP call**, because neither health check sees a missing secret or a wrong path. With the key, if the server has one: ```bash curl -s http://127.0.0.1:3000/mcp \ -H 'content-type: application/json' \ -H 'mcp-protocol-version: 2026-07-28' \ -H 'mcp-method: tools/call' \ -H 'mcp-name: get_ticket' \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_ticket","arguments":{"id":"T-1"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}' ``` ```json {"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"id\":\"T-1\",\"title\":\"Cannot log in\",\"status\":\"open\"}"}],"structuredContent":{"id":"T-1","title":"Cannot log in","status":"open"},"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"help-desk","version":"1.0.0"}}}} ``` Then send the older client's `initialize` from [the secrets section](https://frontmcp.dev/learn/deploying-your-server#the-secrets-it-needs), which is the request a missing `MCP_SESSION_SECRET` breaks. Health checks answer without credentials, even on a server that requires a key. That's what lets a load balancer check it, and it's also why a `200` from `/healthz` says nothing about whether your client can call the server: ```ts checks.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; function getTicket(headers: Record = {}) { return new Request("https://desk.example.com/mcp", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "get_ticket", ...headers }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "get_ticket", arguments: { id: "T-1" }, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } test("/healthz answers without a key", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); const response = await handler(new Request("https://desk.example.com/healthz")); expect(response.status).toBe(200); expect(await response.json()).toMatchObject({ status: "ok", server: { name: "help-desk", version: "1.0.0" } }); }); test("🚩 an MCP call without the key is refused", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); const response = await handler(getTicket()); expect(response.status).toBe(401); expect(response.headers.get("www-authenticate")).toContain("Bearer"); }); test("✅ with the key, the call works", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); const response = await handler(getTicket({ authorization: "Bearer desk-key-1" })); expect(response.status).toBe(200); expect((await response.json()).result.structuredContent).toEqual({ id: "T-1", title: "Cannot log in", status: "open" }); }); ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp" }, // In a real server: tokens: [process.env.DESK_API_KEY!] auth: { mode: "static" as const, tokens: ["desk-key-1"] }, }; ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id. Returns the ticket's title and status.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` A fetch handler answers `/healthz` with a fixed `{ status, server, transport }`; FrontMCP's Node server answers with `runtime` and `uptime` in place of `transport`, as above. [Health checks and metrics](https://frontmcp.dev/reference/deployment/health-and-metrics) covers `/readyz` probes, Kubernetes and Prometheus. ## Connecting a client A client connects to the server's public address plus its endpoint: `https://desk.example.com/mcp`. Most clients keep their servers in a JSON file with an `mcpServers` object: ```json { "mcpServers": { "help-desk": { "url": "https://desk.example.com/mcp" } } } ``` The field that marks an entry as a URL (`type`, `transport`, or none) differs between clients, so check your client's settings. For a server with a key, clients that support it send a header: ```json { "mcpServers": { "help-desk": { "url": "https://desk.example.com/mcp", "headers": { "Authorization": "Bearer ${DESK_API_KEY}" } } } } ``` A desktop client can also start the server itself, as a process on the user's machine, and talk to it over stdin and stdout. Point it at the start script the `node` build writes, with `--stdio`: ```json { "mcpServers": { "help-desk": { "command": "/opt/help-desk/dist/node/help-desk", "args": ["--stdio"] } } } ``` The script checks the Node version, and serves one client on stdio with no port open; the log goes to stderr. It needs the project's `node_modules` next to `dist/`, like any `node` build. `node dist/node/help-desk.bundle.js --stdio` does the same since 1.9. [Connecting MCP clients](https://frontmcp.dev/reference/deployment/mcp-clients) has the details. Two things depend on starting the server this way. A client starts one process per session, so three windows run three copies of the server; an entry file that calls `runShared()` makes them sessions of one local process, which stays up while a session is attached ([Sharing a server between local clients](https://frontmcp.dev/reference/deployment/mcp-clients#sharing-a-server-between-local-clients)). And a [channel](https://frontmcp.dev/reference/sdk/channel), which pushes events into an open Claude Code session, needs a server Claude Code started over stdio: a URL entry doesn't do it. Since FrontMCP 1.12.0 the `--stdio` server above, a `runShared()` entry and `frontmcp dev --stdio` all send channel events to the client that started them ([Pushing events into a Claude Code session](https://frontmcp.dev/reference/deployment/mcp-clients#pushing-events-into-a-claude-code-session)). ### Behind a proxy FrontMCP speaks plain HTTP, so TLS ends in front of it: a load balancer, your platform's edge, or a proxy like nginx on the same machine. Before anything else, the server checks each request's `Host` header against the names it answers to. A server listening on `127.0.0.1` answers only its local names, like `localhost` and `127.0.0.1`, so a proxy that forwards the public host name is refused: ```bash PORT=3000 node dist/node/help-desk.bundle.js curl http://127.0.0.1:3000/healthz -H 'Host: desk.example.com' ``` ```json {"error":"Forbidden","message":"Invalid Host header"} ``` List the names clients use in `FRONTMCP_ALLOWED_HOSTS`. The list replaces the default one, so add the address your own health checks use, too. The image above checks `127.0.0.1:3000`, and with a list that leaves it out, Docker reports the container `unhealthy`: ```bash FRONTMCP_ALLOWED_HOSTS=desk.example.com,127.0.0.1:3000 PORT=3000 node dist/node/help-desk.bundle.js ``` In code, the same list is `http.security.dnsRebindingProtection.allowedHosts`, which wins over the variable. A server listening on all interfaces, like the container above, answers any host name until you set one of them, and its log says so: `DNS-rebinding protection is not enforcing a Host allow-list`. With `local` or `remote` auth behind a proxy, also set `FRONTMCP_PUBLIC_URL`, as [Auth in production](https://frontmcp.dev/reference/auth/production#https-and-the-public-url) explains. ## Recap - `frontmcp build` builds the targets in `frontmcp.config.ts`, or `--target`. The `node` bundle is only your code, and runs next to your production `node_modules`. - A server serves MCP at `http.entryPath`, else the `transport.http.path` of `frontmcp.config.ts` when the `frontmcp` command passes it on (`frontmcp dev` and every build), else `/`. Set `http: { entryPath: "/mcp" }` in `@FrontMcp`, so every way of starting it agrees. - With `NODE_ENV=production`, a plain `Error` reaches the model as an error ID. Fail with `PublicMcpError` for messages the model should read. - Production HTTP needs `MCP_SESSION_SECRET` unless its fallback is MCP 2026-07-28, and `JWT_SECRET` for `local` and `remote` auth. Lambda does not set `NODE_ENV`: set it there. - The Dockerfile `frontmcp create` writes runs the bundle as an unprivileged user, with `FRONTMCP_BIND_ADDRESS=all` and a health check. Give the container `MCP_SESSION_SECRET`; `docker stop` ends it cleanly. - Check `/healthz`, `/readyz`, then a real call. Behind a proxy, list your host names in `FRONTMCP_ALLOWED_HOSTS`. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Serve the path the clients use The help desk also runs inside the company's API gateway, which builds it with `createFetchHandler(config)`, as the checks do. Its clients are set up with `https://desk.example.com/mcp`, and the gateway answers them with `404`. Change the configuration so the server serves MCP at `/mcp`. ```ts config.ts active import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], }; ``` **Solution file (alternative to the starter):** ```ts config.ts solution import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp" }, }; ``` ```ts frontmcp.config.ts // Read by the frontmcp command (dev, build, test), never by the server. export default { name: "help-desk", entry: "./src/main.ts", deployments: [{ target: "node" }], transport: { default: "http", http: { port: 3000, path: "/mcp" } }, }; ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` **Hidden fixture/test file (runs with the example):** ```ts endpoint.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; function getTicket(url: string) { return new Request(url, { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "get_ticket" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "get_ticket", arguments: { id: "T-1" }, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } test("a call to `/mcp` is answered", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); const response = await handler(getTicket("https://desk.example.com/mcp")); expect(response.status).toBe(200); expect((await response.json()).result.structuredContent).toEqual({ id: "T-1", title: "Cannot log in", status: "open" }); }); test("the 404 for other paths names `/mcp`", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); expect(await (await handler(getTicket("https://desk.example.com/api"))).json()).toEqual({ error: "Not Found", entryPaths: ["/mcp"] }); }); ``` **Hint:** `frontmcp.config.ts` already says `/mcp`. Who reads that file, and who reads `config.ts`? **Solution:** `transport.http.path` in `frontmcp.config.ts` is read by the `frontmcp` command, which passes it on to the server it starts and the builds it writes, but `createFetchHandler()` is given `config.ts` and nothing else. A server reads its own configuration, so the path goes in `http.entryPath`. Now `frontmcp dev`, every build, the gateway and these tests serve the same path. ### Challenge: Tell the model what went wrong, in production `get_customer` fails with a plain `Error` when a customer doesn't exist. In development the model reads the message; in production it only gets an error ID, and can't tell the user to check the id. Make the message reach the model in production, and keep the database error hidden. Initial call configuration: ```js { tool: "get_customer", arguments: { id: "C-9" } } ``` ```ts get-customer.tool.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { findCustomer } from "./db"; @Tool({ name: "get_customer", description: "Get a customer by id, like C-1.", inputSchema: { id: z.string() }, }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { const customer = await findCustomer(id); if (!customer) throw new Error(`There's no customer ${id}. Customer ids look like C-1.`); return customer; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetCustomer] }) export class HelpDesk {} ``` **Solution file (alternative to the starter):** ```ts get-customer.tool.ts solution import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { findCustomer } from "./db"; @Tool({ name: "get_customer", description: "Get a customer by id, like C-1.", inputSchema: { id: z.string() }, }) export class GetCustomer extends ToolContext { async execute({ id }: { id: string }) { const customer = await findCustomer(id); if (!customer) this.fail(new PublicMcpError(`There's no customer ${id}. Customer ids look like C-1.`)); return customer; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetCustomer] }) export class HelpDesk {} ``` ```ts db.ts const customers = [ { id: "C-1", name: "Acme Corp", plan: "business" }, { id: "C-2", name: "Globex", plan: "starter" }, ]; export async function findCustomer(id: string) { if (id === "C-500") throw new Error("connect ECONNREFUSED 10.0.4.12:5432"); // the database is down return customers.find((c) => c.id === id); } ``` **Hidden fixture/test file (runs with the example):** ```ts production.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { createErrorHandler, FrontMcpInstance } from "@frontmcp/sdk"; import { HelpDesk } from "./get-customer.tool"; const production = createErrorHandler({ isDevelopment: false }); async function inProduction(id: string) { const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }); try { return { ok: await server.callTool("get_customer", { id }) }; } catch (error) { return { error: production.handle(error) }; } finally { await server.dispose(); } } test("in production, an unknown customer's message reaches the model", async () => { const { error } = await inProduction("C-9"); expect(error?.content[0].text).toBe("There's no customer C-9. Customer ids look like C-1."); }); test("in production, the database error is still hidden", async () => { const { error } = await inProduction("C-500"); expect(error?.content[0].text).toMatch(/^Internal FrontMCP error\. Please contact support with error ID: err_/); }); test("a known customer is still returned", async ({ mcp }) => { const result = await mcp.tools.call("get_customer", { id: "C-1" }); expect(result.json()).toEqual({ id: "C-1", name: "Acme Corp", plan: "business" }); }); ``` **Hint:** In production, FrontMCP keeps the message of one kind of error. Which one does `get_ticket` use? **Solution:** `this.fail(new PublicMcpError(...))` marks the message as meant for the caller, so production sends it as it is. The database error in `db.ts` is still a plain `Error`, so it still becomes an error ID, and its message stays in the log. ### Challenge: Answer only your own host name The help desk runs behind a proxy that forwards requests for `desk.example.com`. Make the server answer requests for that host, health checks included, and refuse requests sent to any other name with `403`. ```ts config.ts active import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp" }, }; ``` **Solution file (alternative to the starter):** ```ts config.ts solution import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp", security: { dnsRebindingProtection: { allowedHosts: ["desk.example.com"] } }, }, }; ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` **Hidden fixture/test file (runs with the example):** ```ts hosts.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; function getTicket(url: string) { return new Request(url, { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "get_ticket" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "get_ticket", arguments: { id: "T-1" }, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } test("a call for `desk.example.com` is answered", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); expect((await handler(getTicket("https://desk.example.com/mcp"))).status).toBe(200); }); test("a call for another host name gets `403`", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); const response = await handler(getTicket("https://desk.attacker.example/mcp")); expect(response.status).toBe(403); expect(await response.json()).toEqual({ error: "Forbidden", message: "Invalid Host header" }); }); test("`/healthz` for `desk.example.com` still answers", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); expect((await handler(new Request("https://desk.example.com/healthz"))).status).toBe(200); }); ``` **Hint:** On a Node server you'd set `FRONTMCP_ALLOWED_HOSTS`. The same list has a place in `http`, under `security`. **Solution:** `allowedHosts` lists the host names the server answers, and anything else gets `403` before any tool runs, health checks included. The list is enforced on its own, under `createFetchHandler()` and on FrontMCP's Node server alike; `enabled: false` would turn it off. A real server lists every name its clients and health checks use, like `127.0.0.1:3000` for a container's `HEALTHCHECK`. --- # Running Several Instances > Run multiple FrontMCP instances behind a load balancer. Share required secrets and state, accounting for each client's MCP revision. Source: https://frontmcp.dev/learn/running-several-instances [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 One server is one process. When it restarts, it's gone for a moment, and when it's busy, every client waits. Running several copies of it, **instances**, behind a load balancer fixes both, and the load balancer sends each request to whichever instance it likes. That's only safe for what every instance can answer the same way. This lesson shows what a FrontMCP server's instances must share, why clients on MCP 2026-07-28 need less of it than older clients, and how Redis carries the rest. **You will learn** - Why an instance's memory is its own, and what that breaks - What clients on MCP 2026-07-28 need from several instances, and what older clients need - Which secrets every instance must share - How to share sessions and rate limits through Redis, with a load balancer in front - The traps: `REDIS_URL` alone, and rate limits that need Redis of their own ## Each instance has its own memory Support agents add notes to tickets. `add_note` keeps them in a provider, which lives in the server's memory. That's fine for one instance. The tests below start two instances from the same configuration, as two processes behind a load balancer would be, and send calls to each. Open the **Tests** tab: Initial call configuration: ```js { tool: "add_note", arguments: { id: "T-1", note: "Asked for a screenshot" } } ``` ```ts instances.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; // One tools/call, as a 2026-07-28 client sends it function call(name: string, args: Record) { return new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": name }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } async function send(instance: (request: Request) => Promise, name: string, args: Record) { return (await (await instance(call(name, args))).json()).result.structuredContent; } test("either instance answers a call that carries what it needs", async () => { const a = await FrontMcpInstance.createFetchHandler(config); const b = await FrontMcpInstance.createFetchHandler(config); expect(await send(a, "get_ticket", { id: "T-1" })).toEqual({ id: "T-1", title: "Cannot log in", status: "open" }); expect(await send(b, "get_ticket", { id: "T-1" })).toEqual({ id: "T-1", title: "Cannot log in", status: "open" }); }); test("🚩 a note added on one instance is missing on the other", async () => { const a = await FrontMcpInstance.createFetchHandler(config); const b = await FrontMcpInstance.createFetchHandler(config); await send(a, "add_note", { id: "T-1", note: "Asked for a screenshot" }); expect(await send(a, "get_notes", { id: "T-1" })).toEqual({ id: "T-1", notes: ["Asked for a screenshot"] }); expect(await send(b, "get_notes", { id: "T-1" })).toEqual({ id: "T-1", notes: [] }); }); ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { NoteStore } from "./note-store"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return ticket; } } @Tool({ name: "add_note", description: "Add an internal note to a ticket.", inputSchema: { id: z.string(), note: z.string() } }) export class AddNote extends ToolContext { async execute({ id, note }: { id: string; note: string }) { const notes = this.get(NoteStore); notes.add(id, note); return { id, notes: notes.list(id) }; } } @Tool({ name: "get_notes", description: "Get a ticket's internal notes.", inputSchema: { id: z.string() } }) export class GetNotes extends ToolContext { async execute({ id }: { id: string }) { return { id, notes: this.get(NoteStore).list(id) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket, AddNote, GetNotes], providers: [NoteStore] }) export class HelpDesk {} ``` ```ts note-store.ts import { Provider } from "@frontmcp/sdk"; // 🚩 One Map per server: each instance has its own @Provider({ name: "NoteStore" }) export class NoteStore { private notes = new Map(); add(id: string, note: string) { this.notes.set(id, [...this.list(id), note]); } list(id: string) { return this.notes.get(id) ?? []; } } ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], }; ``` Each `createFetchHandler()` builds a server of its own, with its own providers, the way each process does. `get_ticket` works on both, because everything it needs is in the code and the request. The note only exists on the instance that took it, so an agent whose next request lands on the other instance sees no notes at all. The fix is to keep the notes somewhere every instance reaches, and give each instance a store that talks to it. A provider can be handed to the server from outside, with `useValue`: Initial call configuration: ```js { tool: "get_notes", arguments: { id: "T-1" } } ``` ```ts note-store.ts active import { Provider } from "@frontmcp/sdk"; // ✅ The notes live wherever `db` is, and every instance is given the same one @Provider({ name: "NoteStore" }) export class NoteStore { constructor(private readonly db: Map) {} add(id: string, note: string) { this.db.set(id, [...this.list(id), note]); } list(id: string) { return this.db.get(id) ?? []; } } ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; import { NoteStore } from "./note-store"; export function createServer(notes: NoteStore) { return { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], providers: [{ provide: NoteStore, name: "NoteStore", useValue: notes }], }; } ``` ```ts instances.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { createServer } from "./config"; import { NoteStore } from "./note-store"; function call(name: string, args: Record) { return new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": name }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } async function send(instance: (request: Request) => Promise, name: string, args: Record) { return (await (await instance(call(name, args))).json()).result.structuredContent; } test("✅ a note added on one instance is there on the other", async () => { const db = new Map(); // stands in for the database both instances connect to const a = await FrontMcpInstance.createFetchHandler(createServer(new NoteStore(db))); const b = await FrontMcpInstance.createFetchHandler(createServer(new NoteStore(db))); await send(a, "add_note", { id: "T-1", note: "Asked for a screenshot" }); expect(await send(b, "get_notes", { id: "T-1" })).toEqual({ id: "T-1", notes: ["Asked for a screenshot"] }); }); ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { NoteStore } from "./note-store"; @Tool({ name: "add_note", description: "Add an internal note to a ticket.", inputSchema: { id: z.string(), note: z.string() } }) export class AddNote extends ToolContext { async execute({ id, note }: { id: string; note: string }) { const notes = this.get(NoteStore); notes.add(id, note); return { id, notes: notes.list(id) }; } } @Tool({ name: "get_notes", description: "Get a ticket's internal notes.", inputSchema: { id: z.string() } }) export class GetNotes extends ToolContext { async execute({ id }: { id: string }) { return { id, notes: this.get(NoteStore).list(id) }; } } // No NoteStore in the app: the server provides it @App({ id: "help-desk", name: "Help Desk", tools: [AddNote, GetNotes] }) export class HelpDesk {} ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { createServer } from "./config"; import { NoteStore } from "./note-store"; // The server the Call tab talks to @FrontMcp(createServer(new NoteStore(new Map()))) export default class Server {} ``` Both instances run in this page, so handing them one `Map` is the Playground's stand-in for a database they both connect to. Two real processes share nothing, not even a module variable: in production, `NoteStore` reads and writes your database, or Redis, and each instance is started with one connected to the same place. The tools don't change, which is the point of [putting state in a provider](https://frontmcp.dev/learn/sharing-state-with-providers#swapping-a-provider-in-tests). ## What clients need from several instances The same question, "does another instance know about this?", decides what FrontMCP's own state needs, and the answer depends on the client. A client on **MCP 2026-07-28** keeps no session. Every request carries what the server needs to answer it, the way `get_ticket` did above. A client on an **older protocol version** starts with `initialize`, gets an `Mcp-Session-Id`, and sends it with every request after that. The session lives in the memory of the instance that created it. To see the difference, the help desk gets two more tools next to `get_ticket`: one that [asks the user](https://frontmcp.dev/learn/asking-the-user) two questions, and one with a [rate limit](https://frontmcp.dev/learn/limiting-calls): ```ts src/help-desk.app.ts @Tool({ name: "assign_ticket", description: "Assign a ticket to a support agent. Asks the user who, then asks to confirm.", inputSchema: { id: z.string() }, }) export class AssignTicket extends ToolContext { async execute({ id }: { id: string }) { const who = await this.elicit(`Who should take ${id}?`, z.object({ agent: z.enum(["Nour", "Sam", "Priya"]) })); const agent = who.status === "accept" ? who.content?.agent : undefined; if (!agent) return { id, assigned: null }; const sure = await this.elicit(`Assign ${id} to ${agent}?`, z.object({ confirm: z.boolean() })); return { id, assigned: sure.status === "accept" && sure.content?.confirm === true ? agent : null }; } } @Tool({ name: "export_tickets", description: "Export every support ticket as CSV. At most 2 exports an hour.", inputSchema: {}, rateLimit: { maxRequests: 2, windowMs: 60 * 60_000 }, }) export class ExportTickets extends ToolContext { async execute() { return { csv: ["id,title,status", ...tickets.map((t) => `${t.id},${t.title},${t.status}`)].join("\n") }; } } ``` Built with the `main.ts` from [the next section](https://frontmcp.dev/learn/running-several-instances#sharing-sessions-and-limits-through-redis), and started as two instances on one machine with no shared state and nothing set but the port: ```bash PORT=4001 node dist/node/help-desk.bundle.js & PORT=4002 node dist/node/help-desk.bundle.js & ``` What a client sees when its requests reach both: | The client | Sends | Gets | | --- | --- | --- | | On MCP 2026-07-28 | `get_ticket` to 4001, then to 4002 | The ticket, from both. | | On MCP 2025-06-18 | `initialize` to 4001, then `get_ticket` with its session id to 4002 | `404` `{"code":-32000,"message":"invalid session id"}` from 4002, which can't read an id that 4001 encrypted with its own secret. | | On MCP 2026-07-28 | `assign_ticket` to 4001, the answer to its first question to 4002, the answer to its second to 4001 | The first question again, `Who should take T-1?`, and 4001 logs `rejected requestState` with `reason: 'bad-signature'` and a hint that names `VAULT_SECRET`. | | Either | `export_tickets` five times, alternating | Four exports: each instance counts its own two. | The second row shows what a session id is: it's encrypted, and an instance serves only an id it can decrypt. Give both instances the same `MCP_SESSION_SECRET` and 4002 reads the id, but it still has no such session, so it answers `404` `session not initialized`. Keeping the session where 4002 can find it is Redis's job, [below](https://frontmcp.dev/learn/running-several-instances#sharing-sessions-and-limits-through-redis). The third row is the surprising one. Between questions, a 2026-07-28 client carries the earlier answers in a `requestState` the server signed, and each instance made up its own signing key. Nothing is stored, so Redis doesn't help; a shared secret does ([`elicit()`](https://frontmcp.dev/reference/sdk/elicit) says which one signs it). With the same `VAULT_SECRET` on both instances, the same client gets `{"id":"T-1","assigned":"Priya"}`. Without it, the rejected state is logged with the fix: ```text WARN mcp-20260728: rejected requestState { method: 'tools/call', reason: 'bad-signature', hint: 'requestState is signed with a per-process key; set VAULT_SECRET (or JWT_SECRET) to the same value on every instance so a round can land on any of them' } ``` So a 2026-07-28 client needs every instance to run the same build with the same secrets. An older client also needs its session to be found wherever its request lands. ### The secrets every instance shares | Variable | Every instance needs the same one when | Otherwise | | --- | --- | --- | | `MCP_SESSION_SECRET` | Clients before MCP 2026-07-28 connect. Session encryption requires it in production and in distributed development deployments ([previous lesson](https://frontmcp.dev/learn/deploying-your-server#the-secrets-it-needs)). | It encrypts their session ids. An instance answers `404` `invalid session id` to an id made under another secret ([High availability](https://frontmcp.dev/reference/deployment/high-availability#caveats)). | | `VAULT_SECRET`, or `JWT_SECRET` | A tool asks the user more than one question. | The first question is asked again, as above. | | `JWT_SECRET` | The server uses `local` or `remote` auth. | Tokens issued by one instance fail on another with `signature verification failed`. | Generate each once, keep it in your platform's secret store, and give every instance the same value. [Auth in production](https://frontmcp.dev/reference/auth/production#running-several-instances) lists the rest of what authenticated servers share. A production server that shares state through `redis`, or through a `transport.persistence` object, and has neither `VAULT_SECRET` nor `JWT_SECRET`, warns once as it starts: ```text WARN requestState is signed with a per-process key (neither VAULT_SECRET nor JWT_SECRET is set). Multi-round tools (elicit/sample) restart when a round lands on another instance; set VAULT_SECRET (or JWT_SECRET) to the same value on every instance. ``` A server without either option gets no warning at startup, and the `hint` above is the only sign, when a round lands on the wrong instance. A blank value counts as unset. > **Note: Changed in 1.8.6: a session id made under another secret is refused** > > In 1.8.5, a public server served a session id that another instance had made under a different `MCP_SESSION_SECRET`. Now the id has to decrypt under this instance's secret: any other id gets `404` `invalid session id`, and the log says `mcp-session-id is not a session this server verified`. So when you rotate `MCP_SESSION_SECRET`, each client that still holds an old id gets that `404` once, and starts a new session with `initialize`. Clients on MCP 2026-07-28 have no session id and don't notice. ## Sharing sessions and limits through Redis `@FrontMcp({ redis })` moves the state FrontMCP keeps between requests into Redis: older clients' sessions, background tasks, and questions waiting for an answer. Rate-limit counts have an option of their own, `throttle.storage`. Read the address from the environment, so the same build runs with or without Redis: ```ts src/main.ts import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; import { HelpDesk } from "./help-desk.app"; const url = process.env.REDIS_URL; // like redis://redis:6379, or rediss://default:…@cache.example.com:6380 @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp" }, elicitation: { enabled: true }, ...(url ? { redis: { url }, throttle: { enabled: true, storage: { type: "redis", redis: { url } } } } : {}), }) export default class Server {} ``` Both options take the URL: `redis` as `{ url }`, and `throttle.storage` under its `redis` key. (`redis` also takes `host`, `port`, `password`, `db` and `tls` as fields.) Docker Compose can run the whole setup on one machine: Redis, two instances of the image from [the last lesson](https://frontmcp.dev/learn/deploying-your-server#running-it-in-a-container), and nginx in front of them, sending requests to each in turn: ```yaml ci/compose.yml services: redis: image: redis:7-alpine healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 3s timeout: 5s retries: 3 desk: build: context: .. dockerfile: ci/Dockerfile init: true deploy: replicas: 2 environment: MCP_SESSION_SECRET: ${MCP_SESSION_SECRET:?set MCP_SESSION_SECRET} VAULT_SECRET: ${VAULT_SECRET:?set VAULT_SECRET} REDIS_URL: redis://redis:6379 depends_on: redis: condition: service_healthy lb: image: nginx:1.27-alpine ports: - "127.0.0.1:3000:80" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro depends_on: - desk ``` ```text title="ci/nginx.conf" upstream desk { server desk:3000; } server { listen 80; location / { proxy_pass http://desk; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Connection ""; proxy_buffering off; proxy_read_timeout 1h; } } ``` ```bash export MCP_SESSION_SECRET="$(openssl rand -hex 32)" VAULT_SECRET="$(openssl rand -hex 32)" docker compose -f ci/compose.yml up -d --build ``` Each instance logs that it found Redis: ```text [TransportService] redis session store will be initialized for transport persistence [TransportService] Session store connection validated successfully ``` Now every client in the table above is served through `http://127.0.0.1:3000/mcp`. The older client's `initialize` and its next four calls all succeed, though nginx sent some of them to the other instance, which logs `Recreating transport from stored session` as it picks the session up from Redis. `assign_ticket` finishes with `{"id":"T-1","assigned":"Priya"}`, and the third export in the hour is refused, whichever instance gets it. Redis holds a key for each: ```bash docker compose -f ci/compose.yml exec redis redis-cli --scan ``` ```text mcp:session: mcp:guard:export_tickets:global:rl: ``` `/readyz` now pings Redis too, so a load balancer that checks it stops sending traffic to an instance that can't reach it. [Redis](https://frontmcp.dev/reference/deployment/redis) has every option, `tls` for managed Redis among them, and [High availability](https://frontmcp.dev/reference/deployment/high-availability) the rest of what instances share. > **Pitfall: REDIS_URL or REDIS_HOST alone doesn't share sessions** > > The `ci/docker-compose.yml` that `frontmcp create` writes sets `REDIS_HOST=redis` for the app, and the `main.ts` it writes doesn't read it. FrontMCP picks up `REDIS_HOST`, or `REDIS_URL`, for background tasks and pending questions, not for sessions or rate limits (`Created task store { type: 'redis', … }`), so the log looks as if Redis is in use. Behind the load balancer above, with that `main.ts`, the older client's calls fail whenever they reach the other instance, with `404` `session not initialized`, and four exports get through where two should. Read the variable into `redis` and `throttle.storage`, as the `main.ts` above does. ### What else lives in one instance's memory | State | Shared through | | --- | --- | | Sessions of clients before MCP 2026-07-28 | `redis` | | Background tasks, and questions waiting for an answer | `redis` | | Rate-limit and concurrency counts | `throttle.storage` ([Guard options](https://frontmcp.dev/reference/sdk/guard#storage-and-keyprefix)) | | Plugin stores, like the [Cache plugin's](https://frontmcp.dev/reference/plugins/cache#stores) | The plugin's `type: "global-store"`, which uses `redis` | | Job and workflow runs | Inherit `redis` except Vercel KV (or `sqlite` on one machine); `jobs.store` overrides it, and `jobs.store: false` forces memory ([Where runs are kept](https://frontmcp.dev/learn/running-jobs-in-the-background#where-runs-are-kept)). | | Sign-ins and refresh tokens of `local` and `remote` auth | `auth.tokenStorage` ([Local auth](https://frontmcp.dev/reference/auth/local#storage)) | | Credentials from [`this.authProviders`](https://frontmcp.dev/reference/sdk/auth-providers#where-credentials-are-kept) | `auth.tokenStorage` too, with the same `VAULT_SECRET` or `JWT_SECRET` on every instance | | Your own state, like the notes | Your database, or Redis, given to every instance | FrontMCP checks `redis` as the server is built, and refuses some of these at startup when they're wrong, which a test can catch before you deploy. The Playground can't reach Redis, but it can build the server: ```ts config.test.ts active import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance, redisOptionsSchema } from "@frontmcp/sdk"; import { CachePlugin } from "@frontmcp/plugin-cache"; import { GetTicket, HelpDesk } from "./help-desk.app"; const info = { name: "help-desk", version: "1.0.0" }; test("`redis` takes the URL a managed Redis hands you", () => { expect(redisOptionsSchema.parse({ url: "rediss://default:s3cr3t@cache.example.com:6380/2" })).toMatchObject({ host: "cache.example.com", port: 6380, password: "s3cr3t", db: 2, tls: true, }); }); test("a `redis` URL that names another user is refused", async () => { const server = FrontMcpInstance.createFetchHandler({ info, apps: [HelpDesk], redis: { url: "rediss://support:s3cr3t@cache.example.com:6380" } }); await expect(server).rejects.toThrow("only the default user is supported"); }); test("🚩 a plugin's global store needs `redis` on the server", async () => { @App({ id: "cached", name: "Cached", tools: [GetTicket], plugins: [CachePlugin.init({ type: "global-store" })] }) class Cached {} await expect(FrontMcpInstance.createFetchHandler({ info, apps: [Cached] })).rejects.toThrow( 'Plugin "CachePlugin" requires global "redis" configuration.', ); }); ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` `redis` takes a `redis://` or `rediss://` URL, the form managed Redis services hand you, and splits it into `host`, `port`, `password`, `db` and `tls`. A URL that names a user other than `default` is refused: the error says `redis.url names the ACL user "support"; only the default user is supported`, and a deployed server exits with it at startup. The last test is about plugins: one whose store is `"global-store"` uses the server's `redis`, and a server without it doesn't start. > **Note: Changed in 1.9: `redis` takes a URL** > > In 1.8.7, `redis: { url }` failed with a `ZodError` saying `host` was missing, and a deployed server exited with it, so a managed Redis's URL had to be split into fields by hand. > **Note: When Redis can't be reached** > > An instance whose `redis` can't be reached when it starts still starts, keeps sessions in its memory, logs `Failed to connect to redis - session persistence disabled`, and answers `/readyz` with `503`. FrontMCP keeps trying, with a growing delay, and when Redis answers it logs `Session store recovered after startup failure`: the instance uses Redis from then on, and `/readyz` is `200` again, with no restart. A Redis that goes away while the instance runs does the same: sessions stay in memory, `/readyz` answers `503`, and the log has one `[RedisStorage] Redis connection error` line every 30 seconds or so. > > Rate limits are stricter, because they're a security control: in production, an instance whose `throttle.storage` can't reach its Redis doesn't start. It exits with: > > ```text > GuardStorageUnavailableError: throttle.storage (redis) is unavailable: Failed to connect to Redis: connect ECONNREFUSED 127.0.0.1:6379. Rate limits fail closed, so the server will not start without it. Set throttle.storage.fallback: 'memory' to start with per-instance counters instead. > ``` > > If Redis goes away while the instance runs, a call to a tool with a limit fails with the tool error `GUARD_STORAGE_UNAVAILABLE`, and works again when Redis does; tools without a limit aren't affected. To start anyway, and to keep serving meanwhile, with each instance counting its own limits, add `fallback: "memory"` next to `type`: two instances then let through four exports an hour, not two, until Redis answers, and share one count again after that. Point the load balancer's readiness check at `/readyz` either way, so an instance without Redis gets no traffic. [When Redis can't be reached](https://frontmcp.dev/reference/deployment/redis#when-redis-cant-be-reached) has the details, and [the guard reference](https://frontmcp.dev/reference/sdk/guard#the-server-doesnt-start-throttlestorage-redis-is-unavailable) shows the errors in Playgrounds. ### Work that should run once, not once per instance Memory is not the only thing each instance has for itself. A `setInterval()` in a provider runs in every instance, so with three of them the nightly cleanup runs three times and the nine o'clock report is sent three times. FrontMCP's background work is declared with a scope instead, and the instances use the server's `redis` to agree on which one of them runs it: | The work | Declare it as | Among instances that share `redis` | | --- | --- | --- | | Runs, ends, and runs again, every interval or on a cron schedule | [`@Duty`](https://frontmcp.dev/reference/sdk/duty) with `scope: "cluster"` | One instance holds the duty's lease and runs it; another takes over when it stops | | Never ends by itself: a connection, a watcher, a queue consumer | [`@Worker`](https://frontmcp.dev/reference/sdk/worker) with `scope: "cluster"` | One instance runs it, and the others stand by | | A workflow on a cron schedule | [`@Workflow({ trigger: "schedule" })`](https://frontmcp.dev/reference/sdk/workflow#schedule-options) | One instance starts each scheduled run | `scope: "cluster"` is new in 1.12.0, like workers and scheduled workflows. Three things go wrong here: - **`scope: "machine"` behind a load balancer.** With `redis`, a machine lease is per hostname, and every container or pod has its own, so each instance runs the work. Use `"cluster"`. - **`scope: "cluster"` without `redis`.** The server doesn't start: `Duty "…" has scope 'cluster', which keeps one lease for every machine in Redis, and none is configured`. - **Different `info.name`s.** The lease's key is made from the server's name, so instances share it only when they have the same one. An instance that shuts down hands its work over: it releases the lease, and another instance takes it at its next check. One that crashes is taken over once its lease expires. Each instance's `/readyz` says what it holds, `"holdsLease": true` for a duty and `"state": "running"` for a worker, and all of them stay ready. [Scheduling Work and Running Workers](https://frontmcp.dev/learn/scheduling-work-and-running-workers) teaches the three, and [High availability](https://frontmcp.dev/reference/deployment/high-availability#background-work-across-instances) has the whole table. ### What distributed mode adds The `node` build above is all several instances need: any of them loads an older client's session from Redis. `frontmcp build --target distributed` (or `FRONTMCP_DEPLOYMENT_MODE=distributed`) does it the other way round: an instance keeps serving the sessions it made, and another instance that gets one of their requests relays it to that instance over Redis and streams the answer back. Each instance writes a heartbeat to Redis. One stopped with `SIGTERM` deletes its heartbeat as it shuts down, so whichever instance gets its sessions' next requests takes them over at once; one that crashed has them taken over once its heartbeat expires, 30 seconds after it stopped, and until then those requests answer `503` with `Retry-After: 30`. Every answer names the instance that served it in an `X-FrontMCP-Machine-Id` header, for load balancers that route by it. [High availability](https://frontmcp.dev/reference/deployment/high-availability#distributed-mode) has the details. Changed in 1.9: in 1.8.7 a request that carried a session another instance had made answered `500` (`RemoteTransporter.handleRequest() is not implemented`), so in distributed mode an older client had to reach the instance that made its session. Vercel and Lambda functions are several instances by themselves: each can run many copies at once, and none keeps anything between invocations. They need the same things: shared secrets, and for older clients' sessions a store every copy reaches, like a Redis in the function's network or, on Vercel, [Vercel KV](https://frontmcp.dev/reference/deployment/vercel#storage), which can't serve background tasks and questions waiting for an answer: FrontMCP skips tasks with a warning, and refuses `elicitation` unless it has a Redis of its own. ### What about sticky sessions? A load balancer can pin each client to one instance, usually with a cookie, so an older client's session is always where its requests go. That avoids Redis for sessions, but an instance that stops or restarts takes its sessions with it, and the rest of the state in the table above still isn't shared. Redis doesn't make pinning useless either: a client that holds an event stream open, like one on the older SSE transport, holds it with one instance, and only that instance can write to it. Give such clients affinity at the load balancer. ## Recap - Each instance has its own memory: its providers, and FrontMCP's own state. A request that lands on another instance doesn't see it. - Clients on MCP 2026-07-28 carry everything in each request, so they need every instance to run the same build with the same secrets. Older clients also need their session found, through `redis` or a load balancer that pins them. - Give every instance the same `MCP_SESSION_SECRET`, the same `VAULT_SECRET` for tools that ask more than one question, and the same `JWT_SECRET` for `local` and `remote` auth. - `redis` shares sessions, tasks and pending questions, `throttle.storage` shares rate limits, and your own state belongs in a database or Redis that every instance is given. Both options take a `redis://` URL. - `REDIS_URL` or `REDIS_HOST` alone moves tasks and pending questions, but not sessions or rate limits: read it into `redis` and `throttle.storage`. - A timer in a provider runs in every instance. A `@Duty` or `@Worker` with `scope: "cluster"`, and a scheduled workflow, run in one of the instances that share `redis`. - A Redis that's down at startup or goes away later is retried: the instance keeps working in memory, and rate-limited tools fail with `GUARD_STORAGE_UNAVAILABLE` unless `throttle.storage` has `fallback: "memory"`. ## Try some challenges Each challenge runs hidden checks against your code. Edit the code, then press **Check**. ### Challenge: Give every instance the same on-call list `set_on_call` records which agent is on call, and `who_is_on_call` tells the model. The checks start two instances with `createServer(db)`, handing both the same `db`, and `createServer` ignores it, so each instance keeps its own list. Make every instance keep the on-call agent in the `db` it's given. Initial call configuration: ```js { tool: "who_is_on_call", arguments: {} } ``` ```ts config.ts active import { HelpDesk } from "./on-call.tools"; export function createServer(db: Map) { return { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], }; } ``` **Solution file (alternative to the starter):** ```ts config.ts solution import { HelpDesk } from "./on-call.tools"; import { OnCallStore } from "./on-call-store"; export function createServer(db: Map) { return { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], providers: [{ provide: OnCallStore, name: "OnCallStore", useValue: new OnCallStore(db) }], }; } ``` ```ts on-call-store.ts import { Provider } from "@frontmcp/sdk"; @Provider({ name: "OnCallStore" }) export class OnCallStore { private db = new Map(); set(agent: string) { this.db.set("on-call", agent); } get() { return this.db.get("on-call") ?? "nobody"; } } ``` **Solution file (alternative to the starter):** ```ts on-call-store.ts solution import { Provider } from "@frontmcp/sdk"; @Provider({ name: "OnCallStore" }) export class OnCallStore { constructor(private readonly db: Map) {} set(agent: string) { this.db.set("on-call", agent); } get() { return this.db.get("on-call") ?? "nobody"; } } ``` ```ts on-call.tools.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { OnCallStore } from "./on-call-store"; @Tool({ name: "set_on_call", description: "Record which support agent is on call.", inputSchema: { agent: z.enum(["Nour", "Sam", "Priya"]) }, }) export class SetOnCall extends ToolContext { async execute({ agent }: { agent: string }) { this.get(OnCallStore).set(agent); return { onCall: agent }; } } @Tool({ name: "who_is_on_call", description: "Which support agent is on call right now.", inputSchema: {} }) export class WhoIsOnCall extends ToolContext { async execute() { return { onCall: this.get(OnCallStore).get() }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetOnCall, WhoIsOnCall], providers: [OnCallStore] }) export class HelpDesk {} ``` **Solution file (alternative to the starter):** ```ts on-call.tools.ts solution import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { OnCallStore } from "./on-call-store"; @Tool({ name: "set_on_call", description: "Record which support agent is on call.", inputSchema: { agent: z.enum(["Nour", "Sam", "Priya"]) }, }) export class SetOnCall extends ToolContext { async execute({ agent }: { agent: string }) { this.get(OnCallStore).set(agent); return { onCall: agent }; } } @Tool({ name: "who_is_on_call", description: "Which support agent is on call right now.", inputSchema: {} }) export class WhoIsOnCall extends ToolContext { async execute() { return { onCall: this.get(OnCallStore).get() }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SetOnCall, WhoIsOnCall] }) export class HelpDesk {} ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { createServer } from "./config"; // The server the Call tab talks to @FrontMcp(createServer(new Map())) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts on-call.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { createServer } from "./config"; function call(name: string, args: Record) { return new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": name }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } async function send(instance: (request: Request) => Promise, name: string, args: Record = {}) { return (await (await instance(call(name, args))).json()).result.structuredContent; } test("an agent set on one instance is on call on the other", async () => { const db = new Map(); const a = await FrontMcpInstance.createFetchHandler(createServer(db)); const b = await FrontMcpInstance.createFetchHandler(createServer(db)); await send(a, "set_on_call", { agent: "Priya" }); expect(await send(b, "who_is_on_call")).toEqual({ onCall: "Priya" }); }); test("a change on the second instance reaches the first", async () => { const db = new Map(); const a = await FrontMcpInstance.createFetchHandler(createServer(db)); const b = await FrontMcpInstance.createFetchHandler(createServer(db)); await send(a, "set_on_call", { agent: "Nour" }); await send(b, "set_on_call", { agent: "Sam" }); expect(await send(a, "who_is_on_call")).toEqual({ onCall: "Sam" }); }); test("the agent is kept in the `db` the server is given", async () => { const db = new Map(); const a = await FrontMcpInstance.createFetchHandler(createServer(db)); await send(a, "set_on_call", { agent: "Nour" }); expect([...db.values()]).toEqual(["Nour"]); }); ``` **Hint:** The second example in [Each instance has its own memory](https://frontmcp.dev/learn/running-several-instances#each-instance-has-its-own-memory) does the same for notes. Three files change, and one of the changes is a removal. **Solution:** `OnCallStore` now keeps the agent in the `db` it's constructed with, and `createServer` hands every server a store built on the `db` it was given, with `useValue`. The app's own `providers: [OnCallStore]` had to go: an app's provider comes before the server's, so each instance kept building a store of its own. On a real server, `db` would be a connection to the same database or Redis in every process. ### Challenge: Page through tickets on any instance `list_tickets` returns open tickets two at a time, and remembers in the server's memory where the last page ended. Behind a load balancer, the next page comes from whichever instance answers. Make each answer include a `nextCursor` (a string, or `null` on the last page) and make the tool take an optional `cursor`, so that the next page works on any instance. Initial call configuration: ```js { tool: "list_tickets", arguments: {} } ``` ```ts list-tickets.tool.ts active import { App, Provider, Tool, ToolContext } from "@frontmcp/sdk"; import { tickets } from "./tickets"; // 🚩 Where the last page ended, in this instance's memory @Provider({ name: "Paging" }) export class Paging { next = 0; } @Tool({ name: "list_tickets", description: "List open tickets, two at a time. Call it again for the next two.", inputSchema: {}, }) export class ListTickets extends ToolContext { async execute() { const paging = this.get(Paging); const page = tickets.slice(paging.next, paging.next + 2); paging.next += 2; return { tickets: page }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ListTickets], providers: [Paging] }) export class HelpDesk {} ``` **Solution file (alternative to the starter):** ```ts list-tickets.tool.ts solution import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @Tool({ name: "list_tickets", description: "List open tickets, two at a time. For the next two, call it again with the nextCursor of the last answer.", inputSchema: { cursor: z.string().optional().describe("The nextCursor of the previous answer") }, }) export class ListTickets extends ToolContext { async execute({ cursor }: { cursor?: string }) { const start = cursor ? Number(cursor) : 0; const next = start + 2; return { tickets: tickets.slice(start, next), nextCursor: next < tickets.length ? String(next) : null }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ListTickets] }) export class HelpDesk {} ``` ```ts tickets.ts export const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-3", title: "Login link expired" }, { id: "T-4", title: "Export is empty" }, { id: "T-6", title: "Wrong time zone in emails" }, { id: "T-7", title: "Invoice PDF won't open" }, ]; ``` ```ts config.ts import { HelpDesk } from "./list-tickets.tool"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }; ``` **Hidden fixture/test file (runs with the example):** ```ts paging.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; function list(args: Record) { return new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "list_tickets" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_tickets", arguments: args, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } async function page(instance: (request: Request) => Promise, args: Record) { return (await (await instance(list(args))).json()).result.structuredContent; } const ids = (answer: { tickets: { id: string }[] }) => answer.tickets.map((t) => t.id); test("the first page has two tickets and a `nextCursor`", async () => { const a = await FrontMcpInstance.createFetchHandler(config); const first = await page(a, {}); expect(ids(first)).toEqual(["T-1", "T-3"]); expect(typeof first.nextCursor).toBe("string"); }); test("the `nextCursor` from one instance gets the next page from another", async () => { const a = await FrontMcpInstance.createFetchHandler(config); const b = await FrontMcpInstance.createFetchHandler(config); const second = await page(b, { cursor: (await page(a, {})).nextCursor }); expect(ids(second)).toEqual(["T-4", "T-6"]); }); test("the last page has `nextCursor: null`", async () => { const a = await FrontMcpInstance.createFetchHandler(config); const b = await FrontMcpInstance.createFetchHandler(config); const second = await page(b, { cursor: (await page(a, {})).nextCursor }); const last = await page(a, { cursor: second.nextCursor }); expect(ids(last)).toEqual(["T-7"]); expect(last.nextCursor).toBeNull(); }); test("a call without a cursor always starts at the first page", async ({ mcp }) => { await mcp.tools.call("list_tickets", {}); expect(ids((await mcp.tools.call("list_tickets", {})).json())).toEqual(["T-1", "T-3"]); }); ``` **Hint:** The instance can't remember where the page ended, so the model has to. What could each answer give it to send back? **Solution:** The position moves out of the server and into the conversation: each answer says where the next page starts, and the model sends that back. No instance has to remember anything, so the next page works wherever the request lands, and the `Paging` provider can go. The description says how to get the next page, so the model knows to pass the cursor. MCP's own lists, like `tools/list`, page the same way. ### Challenge: Count the exports in Redis too The help desk reads `REDIS_URL` into `redis`, so older clients' sessions are shared, but each instance still counts `export_tickets` on its own: behind two instances, four exports an hour get through, not two. Change `createConfig()` so that, with `REDIS_URL` set, rate limits are counted in that Redis too. Without `REDIS_URL`, the server must still start without Redis. Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts config.ts active import { HelpDesk } from "./help-desk.app"; export function createConfig(env: Record) { const url = env.REDIS_URL; return { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], ...(url ? { redis: { url } } : {}), }; } ``` **Solution file (alternative to the starter):** ```ts config.ts solution import { HelpDesk } from "./help-desk.app"; export function createConfig(env: Record) { const url = env.REDIS_URL; return { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], ...(url ? { redis: { url }, throttle: { enabled: true, storage: { type: "redis" as const, redis: { url } } } } : {}), }; } ``` ```ts help-desk.app.ts import { App, Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "export_tickets", description: "Export every support ticket as CSV. At most 2 exports an hour.", inputSchema: {}, rateLimit: { maxRequests: 2, windowMs: 60 * 60_000 }, }) export class ExportTickets extends ToolContext { async execute() { return { csv: "id,title,status\nT-1,Cannot log in,open" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ExportTickets] }) export class HelpDesk {} ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { createConfig } from "./config"; // The server the Call tab talks to: no REDIS_URL here @FrontMcp(createConfig({})) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts config.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance, redisOptionsSchema } from "@frontmcp/sdk"; import { createConfig } from "./config"; const url = "rediss://default:s3cr3t@cache.example.com:6380"; function exportTickets() { return new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "export_tickets" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "export_tickets", arguments: {}, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } test("with `REDIS_URL`, sessions still go to that Redis", () => { const config = createConfig({ REDIS_URL: url }) as { redis?: unknown }; expect(redisOptionsSchema.parse(config.redis)).toMatchObject({ host: "cache.example.com", port: 6380, tls: true }); }); test("with `REDIS_URL`, rate limits are counted in that Redis", () => { const config = createConfig({ REDIS_URL: url }) as { throttle?: { enabled?: boolean; storage?: unknown } }; expect(config.throttle?.enabled).not.toBe(false); expect(config.throttle?.storage).toEqual({ type: "redis", redis: { url } }); }); test("without `REDIS_URL`, the server starts with no Redis and still limits exports", async () => { const config = createConfig({}) as { redis?: unknown; throttle?: { storage?: unknown } }; expect(config.redis).toBeUndefined(); expect(config.throttle?.storage).toBeUndefined(); const server = await FrontMcpInstance.createFetchHandler(createConfig({})); const codes = []; for (let i = 0; i < 3; i++) codes.push((await (await server(exportTickets())).json()).result._meta?.code ?? "ok"); expect(codes).toEqual(["ok", "ok", "RATE_LIMIT_EXCEEDED"]); }); ``` **Hint:** Rate-limit counts have an option of their own in `@FrontMcp`, under `throttle`. It takes the same URL as `redis`, in a slightly different place. **Solution:** `throttle.storage` is where the guard keeps its counts, and `{ type: "redis", redis: { url } }` puts them in the Redis that `redis` uses, so every instance adds to the same count. `throttle` needs `enabled: true` once it's set. Without `REDIS_URL` neither option is there, and the guard counts in memory, which is what one instance, or a test, wants. --- # Escape Hatches > Stepping outside FrontMCP's declarative model when you have to. Reading the request behind a call, calling other services from a tool, and running FrontMCP without its built-in server. Source: https://frontmcp.dev/learn/escape-hatches [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Most of FrontMCP is declarative. You describe a tool's name, schema and handler, and FrontMCP does the rest: it validates arguments, shapes results, and speaks the protocol over HTTP. Now and then a server has to step outside that model: to look at the request itself, to reach a service on the other side of the network, or to run somewhere FrontMCP's own server doesn't. Most servers never need these. When yours does, this chapter shows how, and what to watch out for. **In this chapter** - [How to read the request behind a call](https://frontmcp.dev/learn/reading-the-request) - [How to call other services from a tool](https://frontmcp.dev/learn/calling-other-services) - [How to run FrontMCP without its built-in server](https://frontmcp.dev/learn/running-frontmcp-anywhere) ## Reading the request A tool gets its arguments in `execute()`. Everything else about the call is on `this`: `this.context` holds an id for the request and its trace, and `this.auth` the caller your authentication established. The request id is what ties a failure the user reports to the line in your logs: Initial call configuration: ```js { tool: "describe_call", arguments: {} } ``` ```ts describe-call.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "describe_call", description: "Describe the request this call arrived in. For debugging.", inputSchema: {}, }) export class DescribeCall extends ToolContext { async execute() { return { requestId: this.context.requestId, traceId: this.context.traceContext.traceId, caller: this.auth.user.sub, }; } } ``` Call it again and all three change: the Playground has no authentication, so every request is a new anonymous caller. Only the caller comes from something your server checked. The arguments, the client's name and its headers are whatever the client chose to send. ### [Reading the Request](https://frontmcp.dev/learn/reading-the-request) Learn what `this.context` and `this.auth` hold, how to tag logs and errors with the request id, where the caller's identity should come from, and why client info and arguments prove nothing. ## Calling other services `this.fetch()` is `fetch` with the current request attached: it tells the service which request is calling, and gives up after 30 seconds. The rest is up to the tool. It sends the service's own credentials rather than the caller's, and passes on only what the model needs: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-1" } } ``` ```ts get-invoice.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const res = await this.fetch(`https://billing.example/invoices/${id}`, { headers: { Authorization: "Bearer bk_test_7Hq2" }, // billing's key, from your secrets in a real server signal: AbortSignal.timeout(2_000), }); const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` The billing service here is played by `billing.example.ts`, because the Playground can't reach the internet. Try `INV-9` or `INV-7`: this version still passes billing's errors off as invoices, which is one of the things the lesson fixes. ### [Calling Other Services](https://frontmcp.dev/learn/calling-other-services) Learn what `this.fetch()` adds to a request, why it keeps the caller's token to itself, and how to turn failures and timeouts into errors the model can act on. ## Running FrontMCP anywhere `@FrontMcp` normally starts an HTTP server for you. Underneath it, `FrontMcpInstance.createFetchHandler()` turns your server into a function from `Request` to `Response`, for Cloudflare Workers and any other runtime that speaks the web's `fetch` API. It's what runs this Playground. Open the **Tests** tab: ```ts worker.ts active import { FrontMcpInstance } from "@frontmcp/sdk"; import { HelpDesk } from "./help-desk.app"; const handler = FrontMcpInstance.createFetchHandler({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }); export default { async fetch(request: Request): Promise { return (await handler)(request); }, }; ``` ```ts worker.test.ts import { test, expect } from "@frontmcp/testing"; import worker from "./worker"; test("the worker answers health checks", async () => { const res = await worker.fetch(new Request("https://desk.example.com/healthz")); expect(await res.json()).toMatchObject({ status: "ok", server: { name: "help-desk" } }); }); test("the worker answers MCP requests", async () => { const res = await worker.fetch( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/list" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } } }), }), ); expect((await res.json()).result.tools).toContainTool("get_ticket"); }); ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "open" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND")); return ticket; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` Two more entry points skip HTTP altogether: `connect()` gives your own code an MCP client connected in memory, and `createDirect()` runs tools with no client at all, for scripts and jobs. ### [Running FrontMCP Anywhere](https://frontmcp.dev/learn/running-frontmcp-anywhere) Learn when to take over from `@FrontMcp`, how to serve MCP from any web-standard runtime, and how `connect()` and `createDirect()` differ from a real client in identity, errors and formatting. ## What's next? Start the chapter with [Reading the Request](https://frontmcp.dev/learn/reading-the-request). This is the last chapter of Learn. From here, the [Reference](https://frontmcp.dev/reference) covers each API in detail. --- # Reading the Request > What a tool can learn about the call it's handling beyond its input, like the request id, the trace, the caller and the client, and which of those a client can simply make up. Source: https://frontmcp.dev/learn/reading-the-request [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Most tools need nothing but their input. Now and then a tool needs to know about the call itself: which request this is, so its logs and errors can be found later; who is calling, so it can decide what they may do; which client is on the other end. FrontMCP keeps all of that on `this`, next to the helpers you already use. This lesson covers what's there in FrontMCP 1.8, what it's for, and which parts you can't trust. **You will learn** - What `this.context` and `this.auth` tell a tool about the call and the caller - How to tag logs and error messages with the request id - Where the caller's identity should come from - Why arguments, client info and headers are claims, not facts ## What a tool knows about the call `execute()` receives the arguments. Everything else about the call is on `this`. This tool returns the parts you'll use most. You wouldn't ship it, but call it a few times and watch what changes: Initial call configuration: ```js { tool: "describe_call", arguments: {} } ``` ```ts describe-call.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "describe_call", description: "Describe the request this call arrived in. For debugging.", inputSchema: {}, }) export class DescribeCall extends ToolContext { async execute() { return { requestId: this.context.requestId, traceId: this.context.traceContext.traceId, caller: this.auth.user.sub, client: this.clientInfo ?? null, platform: this.platform, }; } } ``` `requestId` and `traceId` are new on every call, and here so is the caller: the Playground has no authentication, so each request comes from a new anonymous caller, `anon:` and a random id. `client` is the Playground's own description of itself, which it sends with every request. Here is what `this` offers: | On `this` | What it is | | --- | --- | | `this.context.requestId` | A UUID that FrontMCP gives each request. It isn't the JSON-RPC `id`, and the client never sees it unless you put it in a result. | | `this.context.traceContext` | The request's W3C trace context: `traceId`, `parentId`, and `raw`, the value of a `traceparent` header. A request without one starts a new trace. | | `this.contextLogger` | A logger whose lines carry the request id and the trace id. | | `this.auth` | The caller, as your server's authentication established it: `user.sub` says who, `isAnonymous` whether they signed in, `scopes` and `roles` what they were granted, and `claims` what their token said, with checks like `hasRole()`. See [Authorizing Calls](https://frontmcp.dev/learn/authorizing-calls). | | `this.context.authInfo` | The raw result of authentication that `this.auth` is built from, including `token`, the caller's token itself. | | `this.clientInfo` and `this.platform` | The client's name and version, and the AI platform FrontMCP guesses from the name, like `"claude"` or `"cursor"`. | | `this.context.metadata` | Parts of the HTTP request: `userAgent`, `clientIp`, and `customHeaders`, which holds every `x-frontmcp-*` header. | Not all of them are filled in for every call. The deep dive below shows what FrontMCP fills in for each way of running a server. ### What each way of running a server fills in What's on `this` depends on how the request reached FrontMCP: | | Node HTTP server (`frontmcp dev`, a Node build) | `createFetchHandler()` (Workers, this Playground) | In-process (`connect()`, `create()`) | | --- | --- | --- | --- | | `traceContext` | Read from the request's `traceparent` header, or new | Read from the request's `traceparent` header, or new | New, unless a `create()` call's `metadata` continues a trace with `x-frontmcp-trace-id` | | `metadata` | User agent, client IP, `x-frontmcp-*` headers | User agent, `x-frontmcp-*` headers, and the client IP when the runtime gives it (Bun, Deno, Cloudflare) or `FRONTMCP_TRUST_PROXY=1` is set | Empty with `connect()`; with `create()`, what each call's `metadata` option passes | | `clientInfo`, `platform` | From `initialize`, or from each 2026-07-28 request's `_meta` | From each request's `_meta` | From `connect()`'s `clientInfo` option; not set with `create()` | | The caller, in `this.auth` | From your auth configuration | From your auth configuration | Whatever the calling code passes: the user and their scopes | Clients before MCP 2026-07-28 open a session with an `initialize` request that includes their `clientInfo`, and FrontMCP keeps it for the rest of the session. MCP 2026-07-28 has no sessions: a client sends its info in every request's `_meta`, as `io.modelcontextprotocol/clientInfo`, and FrontMCP reads it from there. The Playground calls itself `frontmcp.dev playground`, which isn't a platform FrontMCP recognizes, so `this.platform` is `"generic-mcp"`. The tests below send a request to a fetch handler with headers of their own, connect with FrontMCP's in-process client, `connect()`, which sends `initialize`, and call the tool with `create()`, which has no client at all (see [Running FrontMCP Anywhere](https://frontmcp.dev/learn/running-frontmcp-anywhere)): Initial call configuration: ```js { tool: "describe_request", arguments: {} } ``` ```ts help-desk.app.ts active import { App, Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "describe_request", description: "Which client sent this request, and its trace and headers. For debugging.", inputSchema: {} }) export class DescribeRequest extends ToolContext { async execute() { return { client: this.clientInfo ?? null, platform: this.platform, traceparent: this.context.traceContext.raw, headers: this.context.metadata.customHeaders, }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DescribeRequest] }) export class HelpDesk {} ``` ```ts request.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance, connect, create } from "@frontmcp/sdk"; import { DescribeRequest, HelpDesk } from "./help-desk.app"; const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }; test("the Playground names itself in every request", async ({ mcp }) => { const result = await mcp.tools.call("describe_request", {}); expect(result.json()).toMatchObject({ client: { name: "frontmcp.dev playground", version: "1.0.0" }, platform: "generic-mcp" }); }); test("behind createFetchHandler(), the request's trace and headers reach the tool", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); const traceparent = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"; const response = await handler( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "describe_request", traceparent, "x-frontmcp-desk": "berlin", }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "describe_request", arguments: {}, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": { name: "cursor", version: "1.4.0" }, }, }, }), }), ); const { result } = await response.json(); expect(result.structuredContent).toEqual({ client: { name: "cursor", version: "1.4.0" }, platform: "cursor", traceparent, headers: { "x-frontmcp-desk": "berlin" }, }); }); test("connect() sends the clientInfo you give it, and no headers", async () => { const client = await connect(config, { clientInfo: { name: "cursor", version: "1.4.0" } }); const result = await client.callTool("describe_request", {}); await client.close(); expect(result).toMatchObject({ structuredContent: { client: { name: "cursor", version: "1.4.0" }, platform: "cursor", headers: {} } }); }); test("create() has no client, and passes the metadata each call gives it", async () => { const server = await create({ info: { name: "help-desk", version: "1.0.0" }, tools: [DescribeRequest] }); const result = await server.callTool("describe_request", {}, { metadata: { customHeaders: { "x-frontmcp-desk": "berlin" } } }); await server.dispose(); expect(result.structuredContent).toMatchObject({ client: null, platform: "unknown", headers: { "x-frontmcp-desk": "berlin" } }); }); ``` Either way it's the client's own description of itself, fine for choosing a format and useless as proof. ## Tagging logs and errors with the request id When a tool fails for a reason that isn't the model's fault, like a database that's having a bad day, the model can only tell the user something went wrong. This tool does exactly that: Initial call configuration: ```js { tool: "reopen_ticket", arguments: { id: "T-2" } } ``` ```ts reopen-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { reopen } from "./store"; @Tool({ name: "reopen_ticket", description: "Reopen a closed support ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class ReopenTicket extends ToolContext { async execute({ id }: { id: string }) { try { return await reopen(id); } catch { this.fail(new PublicMcpError("Something went wrong. Please try again later.")); } } } ``` ```ts store.ts const tickets = new Map([ ["T-1", { id: "T-1", status: "closed" }], ["T-2", { id: "T-2", status: "closed" }], ]); export async function reopen(id: string) { // T-2 stands in for a database that's having a bad day. if (id === "T-2") throw new Error("SQLITE_BUSY: database is locked (tickets.db)"); const ticket = tickets.get(id); if (!ticket) throw new Error(`no row for ${id}`); ticket.status = "open"; return ticket; } ``` It's safe: the database error stays hidden. But when the user writes to support, "the assistant said something went wrong", nobody can find out which call failed or why. FrontMCP does log the failure, as a warning with an error id, but that line holds only the message the tool wrote: the database error is gone. And the message the model got has nothing for the user to quote. Log the real error with `this.contextLogger`, and give the user a reference to quote: Initial call configuration: ```js { tool: "reopen_ticket", arguments: { id: "T-2" } } ``` ```ts reopen-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { reopen } from "./store"; @Tool({ name: "reopen_ticket", description: "Reopen a closed support ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class ReopenTicket extends ToolContext { async execute({ id }: { id: string }) { try { return await reopen(id); } catch (err) { this.contextLogger.error(`reopen ${id} failed: ${String(err)}`); this.fail( new PublicMcpError( `The ticket system couldn't reopen ${id} just now. Try again in a minute. ` + `If it keeps failing, tell the user to give support this reference: ${this.context.requestId}`, "STORE_UNAVAILABLE", ), ); } } } ``` ```ts store.ts const tickets = new Map([ ["T-1", { id: "T-1", status: "closed" }], ["T-2", { id: "T-2", status: "closed" }], ]); export async function reopen(id: string) { // T-2 stands in for a database that's having a bad day. if (id === "T-2") throw new Error("SQLITE_BUSY: database is locked (tickets.db)"); const ticket = tickets.get(id); if (!ticket) throw new Error(`no row for ${id}`); ticket.status = "open"; return ticket; } ``` ```ts reopen.test.ts import { test, expect } from "@frontmcp/testing"; test("the error gives a reference to quote", async ({ mcp }) => { const result = await mcp.tools.call("reopen_ticket", { id: "T-2" }); expect(result.raw._meta?.code).toBe("STORE_UNAVAILABLE"); expect(result.text()).toMatch(/reference: [0-9a-f-]{36}$/); }); test("the database error stays out of the message", async ({ mcp }) => { const result = await mcp.tools.call("reopen_ticket", { id: "T-2" }); expect(result.text()).not.toContain("SQLITE_BUSY"); }); ``` Open the **Logs** tab. After the time, the error line shows two ids in brackets, like `[[1f0c2a9e:5d1b4c7e]]`: the first eight characters of the request id and of the trace id. The message the model got ends with the full request id, so support can search the logs for its first eight characters and find the real error. The same id also reaches other services: [`this.fetch()`](https://frontmcp.dev/learn/calling-other-services) sends it upstream as `x-request-id`. ## Who is calling `this.auth` describes the caller: `user.sub` says who they are, `isAnonymous` whether they signed in, `scopes` and `roles` what they were granted, and `claims` what their token said. It's filled in from what your server's authentication checked, usually a token the client sent, so it's the one part of the request a tool can base a decision on. [Authenticating Clients](https://frontmcp.dev/learn/authenticating-clients) covers where it comes from, and [Authorizing Calls](https://frontmcp.dev/learn/authorizing-calls) what each field holds in each auth mode. This tool lists the tickets assigned to whoever is calling. It has no argument for "who", because the caller doesn't get to choose: Initial call configuration: ```js { tool: "my_tickets", arguments: {} } ``` ```ts my-tickets.tool.ts active import { PublicMcpError, Tool, ToolContext } from "@frontmcp/sdk"; const assigned: Record = { nour: ["T-1", "T-3"], sam: ["T-2"] }; @Tool({ name: "my_tickets", description: "List the support tickets assigned to the signed-in agent.", inputSchema: {}, annotations: { readOnlyHint: true }, }) export class MyTickets extends ToolContext { async execute() { if (this.auth.isAnonymous) { this.fail(new PublicMcpError("Only signed-in agents have tickets. Ask the user to sign in.", "SIGN_IN_REQUIRED")); } const agent = this.auth.user.sub; return { agent, tickets: assigned[agent] ?? [] }; } } ``` ```ts my-tickets.test.ts import { test, expect } from "@frontmcp/testing"; import { create } from "@frontmcp/sdk"; import { MyTickets } from "./my-tickets.tool"; test("anonymous callers are asked to sign in", async ({ mcp }) => { const result = await mcp.tools.call("my_tickets", {}); expect(result.raw._meta?.code).toBe("SIGN_IN_REQUIRED"); }); test("a signed-in agent gets their own tickets", async () => { // create() runs the tool in-process, as the user you name. const server = await create({ info: { name: "help-desk", version: "1.0.0" }, tools: [MyTickets] }); const result = await server.callTool("my_tickets", {}, { authContext: { user: { sub: "nour" } } }); expect(result.structuredContent).toEqual({ agent: "nour", tickets: ["T-1", "T-3"] }); await server.dispose(); }); ``` The Playground has no authentication, so the call above is anonymous and fails. The second test calls the tool as the agent `nour`, using `create()`, which runs a server in-process and lets the calling code say who the user is: the user's `sub` becomes `this.auth.user.sub`. That's for tests and trusted code, and [Running FrontMCP Anywhere](https://frontmcp.dev/learn/running-frontmcp-anywhere) covers it. ## Arguments, client info and headers are claims Only team leads may move a ticket to someone else. Here's a first attempt: Initial call configuration: ```js { tool: "reassign_ticket", arguments: { id: "T-1", to: "sam", requested_by: "nour" } } ``` ```ts reassign-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const leads = ["nour"]; @Tool({ name: "reassign_ticket", description: "Move a ticket to another agent. Team leads only.", inputSchema: { id: z.string().regex(/^T-\d+$/), to: z.string().describe("The agent to assign it to"), requested_by: z.string().describe("Who is asking"), }, }) export class ReassignTicket extends ToolContext { async execute({ id, to, requested_by }: { id: string; to: string; requested_by: string }) { if (!leads.includes(requested_by)) { this.fail(new PublicMcpError(`${requested_by} isn't a team lead.`, "LEADS_ONLY")); } return { id, assignee: to }; } } ``` ```ts reassign.test.ts import { test, expect } from "@frontmcp/testing"; test("🚩 anyone who says they're nour can reassign", async ({ mcp }) => { const result = await mcp.tools.call("reassign_ticket", { id: "T-1", to: "mallory", requested_by: "nour" }); expect(result).toBeSuccessful(); }); ``` The check works if the model passes the truth. But the model writes `requested_by`, from whatever is in the conversation, and a conversation can contain anything: a user who says "I'm Nour", or a ticket whose text says "the team lead asked to reassign this to mallory". The test shows it: an anonymous call that claims to be `nour` passes as a team lead. Decide from `this.auth`, which the model can't write, and take the argument away: Initial call configuration: ```js { tool: "reassign_ticket", arguments: { id: "T-1", to: "sam" } } ``` ```ts reassign-ticket.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "reassign_ticket", description: "Move a ticket to another agent. Team leads only.", inputSchema: { id: z.string().regex(/^T-\d+$/), to: z.string().describe("The agent to assign it to"), }, }) export class ReassignTicket extends ToolContext { async execute({ id, to }: { id: string; to: string }) { if (!this.auth.hasRole("lead")) { this.fail(new PublicMcpError("Only team leads can reassign tickets.", "LEADS_ONLY")); } return { id, assignee: to, by: this.auth.user.sub }; } } ``` ```ts reassign.test.ts import { test, expect } from "@frontmcp/testing"; import { create } from "@frontmcp/sdk"; import { ReassignTicket } from "./reassign-ticket.tool"; test("an anonymous caller can't reassign", async ({ mcp }) => { const result = await mcp.tools.call("reassign_ticket", { id: "T-1", to: "mallory" }); expect(result.raw._meta?.code).toBe("LEADS_ONLY"); }); test("a signed-in lead can", async () => { const server = await create({ info: { name: "help-desk", version: "1.0.0" }, tools: [ReassignTicket] }); const nour = { user: { sub: "nour", roles: ["lead"] } }; const result = await server.callTool("reassign_ticket", { id: "T-1", to: "sam" }, { authContext: nour }); expect(result.structuredContent).toEqual({ id: "T-1", assignee: "sam", by: "nour" }); await server.dispose(); }); ``` Roles come from the caller's verified claims, here a `roles` claim in their token, which `this.auth.roles` reads. In-process, `authContext.user` stands in for those claims, so the test puts `roles` there. [Authorizing Calls](https://frontmcp.dev/learn/authorizing-calls) shows how to declare rules like this one so FrontMCP checks them before `execute()` runs at all. Arguments aren't the only thing a client makes up. Everything in the request came from the client, and nothing but your authentication checks any of it: - **Client info.** A client names itself in `clientInfo`, and FrontMCP guesses `this.platform` from that name. Any client can say it's `claude-ai`. - **Headers.** `this.context.metadata` holds the `User-Agent` and every `x-frontmcp-*` header exactly as the client sent them. If you let [`this.fetch()`](https://frontmcp.dev/reference/sdk/fetch) pass the `x-frontmcp-*` ones on to a service, don't let that service trust them either. - **`_meta`.** Trace ids, progress tokens and client capabilities travel in the request's `_meta`, written by the client. Use these for what they're good for: formatting a result for a client, logging, joining up a trace. Base access decisions only on the caller your authentication established, in `this.auth`. ## Recap - Everything about a call beyond its arguments is on `this`: `this.context` for the request, `this.auth` for the caller, `this.clientInfo` for the client. - `this.context.requestId` is new for every request. Put it in log lines with `this.contextLogger`, and in errors a person may have to report. - Take the caller's identity and claims from `this.auth`, never from an argument. The model writes the arguments. - Client info, headers and `_meta` are whatever the client sent. Use them for formatting, logging and tracing, not for access. - How much of the request reaches `this` depends on how the server runs: in-process calls have no headers and a new trace, and `create()` has no client info. - Every member of `this.context` and `this.auth`, per entry point, is in the [`this.context`](https://frontmcp.dev/reference/sdk/context) and [`this.auth`](https://frontmcp.dev/reference/sdk/auth) references. ## Try some challenges ### Challenge: Give support a reference `export_tickets` fails when the storage bucket rejects the upload, and its error passes the storage error straight to the model, access key and all. Keep the storage error in the logs, and give the model a message with a reference support can search for: this call's request id. Keep the code `EXPORT_FAILED`. Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts export-tickets.tool.ts active import { PublicMcpError, Tool, ToolContext } from "@frontmcp/sdk"; import { upload } from "./storage"; @Tool({ name: "export_tickets", description: "Export every support ticket to a CSV file and return a link to it.", inputSchema: {}, }) export class ExportTickets extends ToolContext { async execute() { try { return { url: await upload("tickets.csv", "id,title\nT-1,Cannot log in\n") }; } catch (err) { this.fail(new PublicMcpError(`Export failed: ${String(err)}`, "EXPORT_FAILED")); } } } ``` ```ts storage.ts export async function upload(name: string, csv: string): Promise { // Stands in for a bucket whose credentials were just rotated. throw new Error(`AccessDenied: key AKIA4EXAMPLE7Q is not allowed to write ${name} (${csv.length} bytes) to desk-exports`); } ``` **Solution file (alternative to the starter):** ```ts export-tickets.tool.ts solution import { PublicMcpError, Tool, ToolContext } from "@frontmcp/sdk"; import { upload } from "./storage"; @Tool({ name: "export_tickets", description: "Export every support ticket to a CSV file and return a link to it.", inputSchema: {}, }) export class ExportTickets extends ToolContext { async execute() { try { return { url: await upload("tickets.csv", "id,title\nT-1,Cannot log in\n") }; } catch (err) { this.contextLogger.error(`export failed: ${String(err)}`); this.fail( new PublicMcpError( `The export couldn't be saved. Tell the user to try again later, and to give support this reference: ${this.context.requestId}`, "EXPORT_FAILED", ), ); } } } ``` **Hidden fixture/test file (runs with the example):** ```ts export.test.ts hidden import { test, expect } from "@frontmcp/testing"; const uuid = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/; test("the error keeps the code `EXPORT_FAILED`", async ({ mcp }) => { const result = await mcp.tools.call("export_tickets", {}); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("EXPORT_FAILED"); }); test("the storage error stays out of the message", async ({ mcp }) => { const text = (await mcp.tools.call("export_tickets", {})).text() ?? ""; expect(text).not.toContain("AccessDenied"); expect(text).not.toContain("AKIA"); }); test("the message includes the request id as a reference", async ({ mcp }) => { const first = (await mcp.tools.call("export_tickets", {})).text() ?? ""; const second = (await mcp.tools.call("export_tickets", {})).text() ?? ""; expect(first).toMatch(uuid); expect(first.match(uuid)?.[0]).not.toBe(second.match(uuid)?.[0]); }); ``` **Hint:** `this.contextLogger` writes a log line tagged with the request, and `this.context.requestId` is the id to put in the message. **Solution:** The storage error now goes to the log, in a line tagged with the first eight characters of the request id, and the model gets a message it can pass on with the full id. Each call has its own id, so support can find exactly the failure a user reports. The model never sees the key, which would reach it word for word in production too: a `PublicMcpError`'s message is shown as is. ### Challenge: Record who closed the ticket `close_ticket` asks the model who is closing the ticket, so the audit trail says whatever the model wrote. Take the agent from the signed-in caller instead: remove `closed_by` from the input, record the caller's `user.sub`, and refuse anonymous callers with the code `SIGN_IN_REQUIRED`. ```ts close-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/), closed_by: z.string().describe("The agent closing the ticket"), }, }) export class CloseTicket extends ToolContext { async execute({ id, closed_by }: { id: string; closed_by: string }) { return { id, status: "closed", closed_by }; } } ``` **Solution file (alternative to the starter):** ```ts close-ticket.tool.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket.", inputSchema: { id: z.string().regex(/^T-\d+$/) }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { if (this.auth.isAnonymous) { this.fail(new PublicMcpError("Only signed-in agents can close tickets. Ask the user to sign in.", "SIGN_IN_REQUIRED")); } return { id, status: "closed", closed_by: this.auth.user.sub }; } } ``` **Hidden fixture/test file (runs with the example):** ```ts close-ticket.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { create } from "@frontmcp/sdk"; import { CloseTicket } from "./close-ticket.tool"; test("`closed_by` isn't an argument any more", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "close_ticket"); expect(Object.keys(tool?.inputSchema.properties ?? {})).toEqual(["id"]); }); test("anonymous callers get `SIGN_IN_REQUIRED`", async ({ mcp }) => { const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("SIGN_IN_REQUIRED"); }); test("a signed-in agent is recorded as the closer", async () => { const server = await create({ info: { name: "help-desk", version: "1.0.0" }, tools: [CloseTicket] }); try { const result = await server.callTool("close_ticket", { id: "T-1", closed_by: "mallory" }, { authContext: { user: { sub: "sam" } } }); expect(result.structuredContent).toEqual({ id: "T-1", status: "closed", closed_by: "sam" }); } finally { await server.dispose(); } }); ``` **Hint:** `this.auth.user.sub` is the caller, and `this.auth.isAnonymous` says whether they signed in. Remember that `this.fail()` ends the call, so nothing after it runs. **Solution:** The model can no longer name the closer, because there's nothing to fill in: FrontMCP drops `closed_by` if a client sends it anyway, as the last test does. The agent comes from `this.auth`, which the model can't touch, and an anonymous call fails before anything is recorded. ### Challenge: Don't unlock notes by client name `customer_notes` returns internal notes only to the help desk's own console, which it recognizes by `clientInfo.name`. Any client can use that name. Show the notes to callers whose token has the `agent` role instead, whatever client they use, and refuse everyone else with the code `AGENTS_ONLY`. ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const notes: Record = { "C-881": "Legacy plan. Don't offer a refund." }; @Tool({ name: "customer_notes", description: "Internal notes about a customer. Help desk staff only.", inputSchema: { customer: z.string().describe("Customer id, like C-881") }, }) export class CustomerNotes extends ToolContext { async execute({ customer }: { customer: string }) { if (this.clientInfo?.name !== "desk-console") { this.fail(new PublicMcpError("Internal notes are only available in the help desk console.", "AGENTS_ONLY")); } return { customer, notes: notes[customer] ?? "" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CustomerNotes] }) export class HelpDesk {} ``` **Solution file (alternative to the starter):** ```ts help-desk.app.ts solution import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const notes: Record = { "C-881": "Legacy plan. Don't offer a refund." }; @Tool({ name: "customer_notes", description: "Internal notes about a customer. Help desk staff only.", inputSchema: { customer: z.string().describe("Customer id, like C-881") }, }) export class CustomerNotes extends ToolContext { async execute({ customer }: { customer: string }) { if (!this.auth.hasRole("agent")) { this.fail(new PublicMcpError("Internal notes are only available to help desk agents.", "AGENTS_ONLY")); } return { customer, notes: notes[customer] ?? "" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CustomerNotes] }) export class HelpDesk {} ``` **Hidden fixture/test file (runs with the example):** ```ts notes.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { connect, create } from "@frontmcp/sdk"; import { CustomerNotes, HelpDesk } from "./help-desk.app"; const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }; test("a client that calls itself desk-console gets no notes", async () => { const client = await connect(config, { clientInfo: { name: "desk-console", version: "1.0.0" } }); const result = await client.callTool("customer_notes", { customer: "C-881" }); await client.close(); expect(result).toMatchObject({ isError: true, _meta: { code: "AGENTS_ONLY" } }); }); test("a caller with the `agent` role gets the notes", async () => { const server = await create({ info: { name: "help-desk", version: "1.0.0" }, tools: [CustomerNotes] }); const sam = { user: { sub: "sam", roles: ["agent"] } }; const result = await server.callTool("customer_notes", { customer: "C-881" }, { authContext: sam }); await server.dispose(); expect(result.structuredContent).toEqual({ customer: "C-881", notes: "Legacy plan. Don't offer a refund." }); }); test("anonymous callers get `AGENTS_ONLY`", async ({ mcp }) => { const result = await mcp.tools.call("customer_notes", { customer: "C-881" }); expect(result.raw._meta?.code).toBe("AGENTS_ONLY"); }); ``` **Hint:** The tests use FrontMCP's in-process entry points, which let them choose the client's name and the signed-in user. Only one of those is checked by anything. The caller's roles are in `this.auth.roles`, as in `reassign_ticket` above. **Solution:** The first test connects with the console's name and no user, and the starter gave it the notes. A name is just a string the client sends. The solution checks the caller's claims instead, so the notes follow the signed-in agent wherever they work, and a client that only borrows the console's name gets nothing. --- # Calling Other Services > How a tool calls an HTTP API with this.fetch(), what it adds to each request, whose credentials it sends, and how to turn a slow or failing service into errors the model can act on. Source: https://frontmcp.dev/learn/calling-other-services [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Sooner or later a tool needs data that lives somewhere else: a billing API, a CRM, another team's service. In a FrontMCP tool, `this.fetch()` is the web's `fetch` with the current request attached. Making the call is the easy part. This lesson is about everything around it: a service that's down or slow, a response full of data the model shouldn't see, and credentials that end up where they shouldn't. **You will learn** - What `this.fetch()` adds to a request - Which credentials to send, and why not the caller's - How to turn failures and timeouts into errors the model can act on - How to keep upstream secrets and raw responses away from the model ## Calling a service from a tool Support agents often need a customer's invoice, and invoices live in the billing service. Here's a first version of a tool that fetches one. (If the service has an OpenAPI description, the [OpenAPI adapter](https://frontmcp.dev/learn/wrapping-an-openapi-service) can generate a tool for each operation instead; this lesson writes the tool by hand, which is what you do when you want to shape what the model sees.) Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-1" } } ``` ```ts get-invoice.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const res = await fetch(`https://billing.example/invoices/${id}`); return await res.json(); } } ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` ```ts get-invoice.test.ts import { test, expect } from "@frontmcp/testing"; test("🚩 the model gets the customer's card token", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-1" }); expect(result.json()).toHaveProperty("card_token"); }); test("🚩 a missing invoice looks like a result", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-9" }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ error: "not_found" }); }); ``` > **Note** > > The Playground runs in your browser and can't reach a real billing service, so every example on this page has a `billing.example.ts` file that plays one. It answers requests for `https://billing.example` in-process, and records what it received so tests can check it. You won't need it in a real server. The tool works, and it has four problems, which the rest of this lesson fixes one at a time: 1. **The model gets everything the service sent**, including a card token and internal notes it should never see. 2. **Failures look like answers.** A 404 comes back as a successful result that says `{"error":"not_found"}`. 3. **Nothing limits how long it waits.** If billing hangs, so does the call. 4. **Billing can't tell who is calling.** Nothing links its logs to yours. ## Using `this.fetch()` Start with the last problem, and the first. Switch `fetch` to `this.fetch()`, and build the result from the fields the model needs: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-1" } } ``` ```ts get-invoice.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const res = await this.fetch(`https://billing.example/invoices/${id}`); const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` ```ts get-invoice.test.ts import { test, expect } from "@frontmcp/testing"; import { received } from "./billing.example"; test("the model gets only what it needs", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-1" }); expect(result.json()).toEqual({ id: "INV-1", status: "paid", total: "120.00 EUR", due: "2026-09-01" }); }); test("billing is told which request is calling", async ({ mcp }) => { await mcp.tools.call("get_invoice", { id: "INV-1" }); const { headers } = received[received.length - 1]; expect(headers["x-request-id"]).toMatch(/^[0-9a-f-]{36}$/); expect(headers["traceparent"]).toMatch(/^00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]$/); }); ``` `this.fetch()` takes the same arguments as `fetch` and returns the same `Response`. What it adds is the request you're in. Each of these is added only if you haven't set it yourself: | Added | Value | | --- | --- | | `x-request-id` header | [`this.context.requestId`](https://frontmcp.dev/learn/reading-the-request), so billing's logs can be matched with yours. | | `traceparent` header | The request's trace context, so a tracing system can join your server's work and billing's into one trace. | | A timeout | 30 seconds, when you don't pass a `signal` of your own. | What it doesn't add matters as much: the caller's token and their `x-frontmcp-*` headers stay on your server, as the next section shows. The other change is the result: the tool picks four fields and formats the total, and everything else the service sent stays in the tool. The service's JSON is a lot like a database row. It carries whatever billing needed, it can grow new fields without telling you, and [Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results) explains why the model should get a result you built on purpose. ## Sending your own credentials Your server authenticates its clients, usually with an OAuth access token. That token was issued for your MCP server, not for billing, and `this.fetch()` doesn't send it on. The Playground has no authentication, so this test uses `create()` to call the tool as a signed-in user whose token is `mcp-token-for-nour`, and looks at what billing received: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-1" } } ``` ```ts get-invoice.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const res = await this.fetch(`https://billing.example/invoices/${id}`); const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` ```ts credentials.test.ts import { test, expect } from "@frontmcp/testing"; import { create } from "@frontmcp/sdk"; import { received } from "./billing.example"; import { GetInvoice } from "./get-invoice.tool"; test("the caller's token stays on your server", async () => { const server = await create({ info: { name: "help-desk", version: "1.0.0" }, tools: [GetInvoice] }); await server.callTool("get_invoice", { id: "INV-1" }, { authContext: { token: "mcp-token-for-nour", user: { sub: "nour" } } }); await server.dispose(); expect(received[received.length - 1].headers).not.toHaveProperty("authorization"); }); ``` Forwarding it would hand the user's credential to another service, and if that service accepted it, the model could reach it with the user's rights, which nobody agreed to. The MCP specification calls this token passthrough and forbids it. So billing gets no credentials at all. Give each service its own. `this.fetch()` never replaces an `Authorization` header you set: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-1" } } ``` ```ts get-invoice.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { BILLING_API_KEY } from "./secrets"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const res = await this.fetch(`https://billing.example/invoices/${id}`, { headers: { Authorization: `Bearer ${BILLING_API_KEY}` }, }); const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` ```ts secrets.ts // In a real server, read this from the environment or a secret store. export const BILLING_API_KEY = "bk_test_7Hq2"; ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` ```ts credentials.test.ts import { test, expect } from "@frontmcp/testing"; import { create } from "@frontmcp/sdk"; import { received } from "./billing.example"; import { GetInvoice } from "./get-invoice.tool"; test("billing gets its own key, not the caller's token", async () => { const server = await create({ info: { name: "help-desk", version: "1.0.0" }, tools: [GetInvoice] }); await server.callTool("get_invoice", { id: "INV-1" }, { authContext: { token: "mcp-token-for-nour", user: { sub: "nour" } } }); await server.dispose(); expect(received[received.length - 1].headers["authorization"]).toBe("Bearer bk_test_7Hq2"); }); ``` Keep the key where the model can't see it: out of results, out of error messages, and out of URLs, which tend to end up in logs. The same goes for anything the service sends back about itself. > **Note** > > Sometimes a service of your own accepts the same tokens as your MCP server, because both trust the same identity provider. Then you can let the caller's token through to that service, and only to it, by listing its origin in `@FrontMcp({ fetch: { forwardCallerTokenTo: ["https://tickets-api.example.com"] } })`. [`this.fetch()`](https://frontmcp.dev/reference/sdk/fetch#forwarding-the-callers-token-to-your-own-service) shows how. For a service where each user has an account of their own, register a credential provider in `@FrontMcp({ authProvidersVault })` that finds the caller's credential, and pass `credentials: { provider }`: [`this.authProviders`](https://frontmcp.dev/reference/sdk/auth-providers) shows how. ## When the service fails Now the second problem. A response isn't an answer until you've checked its status. The obvious fix is to pass billing's error on: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-7" } } ``` ```ts get-invoice.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { BILLING_API_KEY } from "./secrets"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const res = await this.fetch(`https://billing.example/invoices/${id}`, { headers: { Authorization: `Bearer ${BILLING_API_KEY}` }, }); if (!res.ok) { this.fail(new PublicMcpError(`Billing error ${res.status}: ${await res.text()}`)); } const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` ```ts secrets.ts // In a real server, read this from the environment or a secret store. export const BILLING_API_KEY = "bk_test_7Hq2"; ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` The model now learns the name and port of billing's database server, and nothing it can do about it. And because the message is in a `PublicMcpError`, it gets it word for word in production too. The model needs to know one of two things: that it asked for something that doesn't exist, so it should fix its request, or that billing is having trouble, so it should wait or carry on without the invoice. Say exactly that, and log the details for yourself: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-7" } } ``` ```ts get-invoice.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { BILLING_API_KEY } from "./secrets"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; const unavailable = () => new PublicMcpError( "The billing service isn't answering right now. Try again in a few minutes, or carry on without the invoice.", "BILLING_UNAVAILABLE", ); @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { let res: Response; try { res = await this.fetch(`https://billing.example/invoices/${id}`, { headers: { Authorization: `Bearer ${BILLING_API_KEY}` }, }); } catch (err) { this.contextLogger.error(`billing request failed: ${String(err)}`); this.fail(unavailable()); } if (res.status === 404) { this.fail(new PublicMcpError(`There's no invoice ${id}. Check the id with the user.`, "INVOICE_NOT_FOUND")); } if (!res.ok) { this.contextLogger.error(`billing answered ${res.status}: ${await res.text()}`); this.fail(unavailable()); } const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` ```ts secrets.ts // In a real server, read this from the environment or a secret store. export const BILLING_API_KEY = "bk_test_7Hq2"; ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` ```ts errors.test.ts import { test, expect } from "@frontmcp/testing"; test("a missing invoice is INVOICE_NOT_FOUND", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-9" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("INVOICE_NOT_FOUND"); }); test("an outage is BILLING_UNAVAILABLE, without billing's details", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-7" }); expect(result.raw._meta?.code).toBe("BILLING_UNAVAILABLE"); expect(result.text()).not.toContain("pg-billing"); }); test("a real invoice still comes back", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-1" }); expect(result).toBeSuccessful(); }); ``` Each failure gets a code, so programs and tests can tell them apart, and a message that says what to do next. The `catch` handles the other way a call fails: `this.fetch()` throws, rather than returning a response, when the service can't be reached at all. The details go to the log, tagged with the request id, as in [Reading the Request](https://frontmcp.dev/learn/reading-the-request). > **Pitfall: this.fail() throws, and catch catches it** > > `this.fail()` ends the call by throwing. Call it inside a `try`, and your own `catch` receives it. A "no such invoice" error would turn into "billing isn't answering" before the model ever saw it. Keep the `try` around the `this.fetch()` call only, as above, and fail after it. The second challenge shows the bug. ## When the service is slow The last problem left is waiting. `INV-8` never answers. With no `signal`, `this.fetch()` waits 30 seconds before it gives up, and the user waits with it. Decide how long this service may take, pass that as `signal`, and tell the model what happened when the time runs out: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-8" } } ``` ```ts get-invoice.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { BILLING_API_KEY } from "./secrets"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; const unavailable = () => new PublicMcpError( "The billing service isn't answering right now. Try again in a few minutes, or carry on without the invoice.", "BILLING_UNAVAILABLE", ); @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { let res: Response; try { res = await this.fetch(`https://billing.example/invoices/${id}`, { headers: { Authorization: `Bearer ${BILLING_API_KEY}` }, signal: AbortSignal.timeout(2_000), }); } catch (err) { if ((err as Error).name === "TimeoutError") { this.fail(new PublicMcpError("The billing service didn't answer within 2 seconds. Try again later, or carry on without the invoice.", "BILLING_TIMEOUT")); } this.contextLogger.error(`billing request failed: ${String(err)}`); this.fail(unavailable()); } if (res.status === 404) { this.fail(new PublicMcpError(`There's no invoice ${id}. Check the id with the user.`, "INVOICE_NOT_FOUND")); } if (!res.ok) { this.contextLogger.error(`billing answered ${res.status}: ${await res.text()}`); this.fail(unavailable()); } const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` ```ts secrets.ts // In a real server, read this from the environment or a secret store. export const BILLING_API_KEY = "bk_test_7Hq2"; ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` ```ts timeout.test.ts import { test, expect } from "@frontmcp/testing"; test("a hung service is BILLING_TIMEOUT after 2 seconds", async ({ mcp }) => { const started = Date.now(); const result = await mcp.tools.call("get_invoice", { id: "INV-8" }); expect(result.raw._meta?.code).toBe("BILLING_TIMEOUT"); expect(Date.now() - started).toBeLessThan(4_000); }); ``` `AbortSignal.timeout()` aborts the request, and `this.fetch()` rejects with an error named `TimeoutError`. Passing your own `signal` replaces the 30-second default, so the limit is yours. Keep it well under what a client will wait for a whole tool call, or the client gives up first and the model never sees your message. ### A time limit for the whole call `@Tool` also takes `timeout: { executeMs }`, a limit on the whole of `execute()`, however many requests it makes: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-8" } } ``` ```ts get-invoice.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, timeout: { executeMs: 1_000 }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const res = await this.fetch(`https://billing.example/invoices/${id}`); return { status: res.status }; } } ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` After a second the call fails with the code `EXECUTION_TIMEOUT` and `Execution of "get_invoice" timed out after 1000ms`, in production too. It makes a good backstop, but it doesn't say which service was slow or what to do instead. A timeout on the request, with a message you wrote, tells the model what to do. ## Recap - `this.fetch()` is `fetch` plus the request: it sends `x-request-id` and `traceparent`, and gives up after 30 seconds unless you pass a `signal`. - `this.fetch()` keeps the caller's token and `x-frontmcp-*` headers on your server. Send each service its own credentials in `Authorization`. - Check `res.ok`. Map "doesn't exist" and "not available right now" to different codes and messages that tell the model what to do. - Keep upstream error bodies, host names and keys out of results and error messages. Log them with `this.contextLogger` instead. - Set a timeout per request with `signal: AbortSignal.timeout(ms)`, and catch the `TimeoutError`. - Keep `this.fail()` out of `try` blocks whose `catch` would swallow it. ## Try some challenges ### Challenge: Tell the model how long to wait When billing is busy it answers `429 Too Many Requests` with a `Retry-After` header, the number of seconds to wait. `get_invoice` treats that like an outage. Fail with the code `BILLING_BUSY` instead, and a message that says how many seconds to wait. Try it with `INV-6`. Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-6" } } ``` ```ts get-invoice.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { BILLING_API_KEY } from "./secrets"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; const unavailable = () => new PublicMcpError( "The billing service isn't answering right now. Try again in a few minutes, or carry on without the invoice.", "BILLING_UNAVAILABLE", ); @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { let res: Response; try { res = await this.fetch(`https://billing.example/invoices/${id}`, { headers: { Authorization: `Bearer ${BILLING_API_KEY}` }, signal: AbortSignal.timeout(2_000), }); } catch (err) { this.contextLogger.error(`billing request failed: ${String(err)}`); this.fail(unavailable()); } if (res.status === 404) { this.fail(new PublicMcpError(`There's no invoice ${id}. Check the id with the user.`, "INVOICE_NOT_FOUND")); } if (!res.ok) { this.contextLogger.error(`billing answered ${res.status}: ${await res.text()}`); this.fail(unavailable()); } const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` **Solution file (alternative to the starter):** ```ts get-invoice.tool.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { BILLING_API_KEY } from "./secrets"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; const unavailable = () => new PublicMcpError( "The billing service isn't answering right now. Try again in a few minutes, or carry on without the invoice.", "BILLING_UNAVAILABLE", ); @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { let res: Response; try { res = await this.fetch(`https://billing.example/invoices/${id}`, { headers: { Authorization: `Bearer ${BILLING_API_KEY}` }, signal: AbortSignal.timeout(2_000), }); } catch (err) { this.contextLogger.error(`billing request failed: ${String(err)}`); this.fail(unavailable()); } if (res.status === 404) { this.fail(new PublicMcpError(`There's no invoice ${id}. Check the id with the user.`, "INVOICE_NOT_FOUND")); } if (res.status === 429) { const seconds = Number(res.headers.get("retry-after")) || 60; this.fail(new PublicMcpError(`The billing service is busy. Try again in ${seconds} seconds.`, "BILLING_BUSY")); } if (!res.ok) { this.contextLogger.error(`billing answered ${res.status}: ${await res.text()}`); this.fail(unavailable()); } const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` ```ts secrets.ts // In a real server, read this from the environment or a secret store. export const BILLING_API_KEY = "bk_test_7Hq2"; ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` **Hidden fixture/test file (runs with the example):** ```ts busy.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("a 429 fails with `BILLING_BUSY`", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-6" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("BILLING_BUSY"); }); test("the message says to wait 30 seconds, as billing asked", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-6" }); expect(result.text()).toContain("30 seconds"); }); test("an outage is still `BILLING_UNAVAILABLE`", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-7" }); expect(result.raw._meta?.code).toBe("BILLING_UNAVAILABLE"); }); ``` **Hint:** Check for `429` before the general `!res.ok` branch. `res.headers.get("retry-after")` returns the header as a string, or `null` if it's missing. **Solution:** A rate limit isn't an outage: billing is fine, and it has said exactly when to come back. Passing that on lets the model wait and retry, or tell the user when to try again, instead of giving up. The fallback of 60 seconds covers a service that forgets the header. ### Challenge: Let the not-found error through This version of `get_invoice` wraps everything in one `try`. Ask it for `INV-9`, which doesn't exist, and the model hears that billing is down. Make a missing invoice fail with `INVOICE_NOT_FOUND` again, without changing how outages are reported. Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-9" } } ``` ```ts get-invoice.tool.ts active import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { BILLING_API_KEY } from "./secrets"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { try { const res = await this.fetch(`https://billing.example/invoices/${id}`, { headers: { Authorization: `Bearer ${BILLING_API_KEY}` }, signal: AbortSignal.timeout(2_000), }); if (res.status === 404) { this.fail(new PublicMcpError(`There's no invoice ${id}. Check the id with the user.`, "INVOICE_NOT_FOUND")); } if (!res.ok) throw new Error(`billing answered ${res.status}: ${await res.text()}`); const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } catch (err) { this.contextLogger.error(`billing request failed: ${String(err)}`); this.fail( new PublicMcpError( "The billing service isn't answering right now. Try again in a few minutes, or carry on without the invoice.", "BILLING_UNAVAILABLE", ), ); } } } ``` **Solution file (alternative to the starter):** ```ts get-invoice.tool.ts solution import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; import { BILLING_API_KEY } from "./secrets"; type Invoice = { id: string; status: string; total_cents: number; currency: string; due_date: string }; const unavailable = () => new PublicMcpError( "The billing service isn't answering right now. Try again in a few minutes, or carry on without the invoice.", "BILLING_UNAVAILABLE", ); @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status, total and due date.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, annotations: { readOnlyHint: true, openWorldHint: true }, }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { let res: Response; try { res = await this.fetch(`https://billing.example/invoices/${id}`, { headers: { Authorization: `Bearer ${BILLING_API_KEY}` }, signal: AbortSignal.timeout(2_000), }); } catch (err) { this.contextLogger.error(`billing request failed: ${String(err)}`); this.fail(unavailable()); } if (res.status === 404) { this.fail(new PublicMcpError(`There's no invoice ${id}. Check the id with the user.`, "INVOICE_NOT_FOUND")); } if (!res.ok) { this.contextLogger.error(`billing answered ${res.status}: ${await res.text()}`); this.fail(unavailable()); } const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total: `${(invoice.total_cents / 100).toFixed(2)} ${invoice.currency}`, due: invoice.due_date, }; } } ``` ```ts secrets.ts // In a real server, read this from the environment or a secret store. export const BILLING_API_KEY = "bk_test_7Hq2"; ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` **Hidden fixture/test file (runs with the example):** ```ts not-found.test.ts hidden import { test, expect } from "@frontmcp/testing"; test("a missing invoice fails with `INVOICE_NOT_FOUND`", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-9" }); expect(result).toBeError(); expect(result.raw._meta?.code).toBe("INVOICE_NOT_FOUND"); }); test("an outage is still `BILLING_UNAVAILABLE`", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-7" }); expect(result.raw._meta?.code).toBe("BILLING_UNAVAILABLE"); }); test("a real invoice still comes back", async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id: "INV-1" }); expect(result.json()).toEqual({ id: "INV-1", status: "paid", total: "120.00 EUR", due: "2026-09-01" }); }); ``` **Hint:** Call it with `INV-9` and open the Logs tab. The log says only `billing request failed: Error`. What did the `catch` catch? **Solution:** `this.fail()` throws to end the call, so inside the `try` it was caught and replaced. The fix shrinks the `try` to the one line that can fail to reach billing, and checks the response after it, where `this.fail()` goes straight to the client. If you do need a wide `try`, rethrow what you didn't expect rather than turning everything into one error. ### Challenge: Keep up with a new status This `get_invoice` returns billing's JSON as it is, and relies on `outputSchema` to drop the fields the model shouldn't see. It works for `INV-1`. Call it with `INV-2`, then fix it so that every invoice comes back with exactly the four fields in the schema, and `status` may also be `"overdue"`. Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-2" } } ``` ```ts get-invoice.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status and total.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, outputSchema: z.object({ id: z.string(), status: z.enum(["paid", "open"]), total_cents: z.number(), currency: z.string(), }), }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const res = await this.fetch(`https://billing.example/invoices/${id}`); return await res.json(); // outputSchema drops the rest } } ``` **Solution file (alternative to the starter):** ```ts get-invoice.tool.ts solution import { Tool, ToolContext, z } from "@frontmcp/sdk"; type Invoice = { id: string; status: "paid" | "open" | "overdue"; total_cents: number; currency: string }; @Tool({ name: "get_invoice", description: "Get an invoice from the billing service: its status and total.", inputSchema: { id: z.string().regex(/^INV-\d+$/).describe("Invoice id, like INV-1") }, outputSchema: z.object({ id: z.string(), status: z.enum(["paid", "open", "overdue"]), total_cents: z.number(), currency: z.string(), }), }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const res = await this.fetch(`https://billing.example/invoices/${id}`); const invoice = (await res.json()) as Invoice; return { id: invoice.id, status: invoice.status, total_cents: invoice.total_cents, currency: invoice.currency }; } } ``` ```ts billing.example.ts // Stands in for the billing service at https://billing.example, which the // Playground can't reach from your browser. It answers requests for that host // in-process, and passes everything else to the real fetch. A real server // doesn't need this file. // // INV-1 and INV-2 exist. INV-6 is rate-limited, INV-7 fails, INV-8 never answers. const invoices: Record = { "INV-1": { id: "INV-1", customer_id: "C-881", status: "paid", total_cents: 12000, currency: "EUR", due_date: "2026-09-01", card_token: "tok_live_4242_9f8e", internal_notes: "Refunded once in 2025." }, "INV-2": { id: "INV-2", customer_id: "C-881", status: "overdue", total_cents: 4900, currency: "EUR", due_date: "2026-08-15", card_token: "tok_live_4242_9f8e", internal_notes: "Customer disputes the late fee." }, }; /** Every request the billing service received, oldest first. */ export const received: { path: string; headers: Record }[] = []; async function billing(request: Request): Promise { const path = new URL(request.url).pathname; received.push({ path, headers: Object.fromEntries(request.headers) }); switch (path) { case "/invoices/INV-6": return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }); case "/invoices/INV-7": return Response.json({ error: "db_unavailable", detail: "connect ECONNREFUSED pg-billing-01.internal:5432" }, { status: 503 }); case "/invoices/INV-8": // a connection that stays open and never answers return new Promise((_, reject) => { const open = setInterval(() => {}, 1_000); request.signal.addEventListener("abort", () => (clearInterval(open), reject(request.signal.reason))); }); } const invoice = invoices[path.replace("/invoices/", "")]; return invoice ? Response.json(invoice) : Response.json({ error: "not_found" }, { status: 404 }); } const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost"); return url.hostname === "billing.example" ? billing(new Request(input, init)) : realFetch(input, init); }; ``` **Hidden fixture/test file (runs with the example):** ```ts fields.test.ts hidden import { test, expect } from "@frontmcp/testing"; for (const id of ["INV-1", "INV-2"]) { test(`${id} comes back with only \`id\`, \`status\`, \`total_cents\` and \`currency\``, async ({ mcp }) => { const result = await mcp.tools.call("get_invoice", { id }); expect(Object.keys(result.raw.structuredContent ?? {}).sort()).toEqual(["currency", "id", "status", "total_cents"]); expect(result.text()).not.toContain("tok_live"); }); } test("`status` can be \"overdue\"", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "get_invoice"); expect(tool?.outputSchema?.properties?.status?.enum).toContain("overdue"); }); ``` **Hint:** Read the error `INV-2` gets, then look at its `status` in `billing.example.ts`. FrontMCP checks every result against `outputSchema` before sending it. **Solution:** Billing added an `overdue` status, `INV-2` stopped matching the schema, and FrontMCP refused to send it: the call failed with `INVALID_OUTPUT`, which in production reads "Output validation failed. Please contact support.", nothing the model can act on. Adding the status to the enum fixes this one. Building the result field by field in `execute()` means the model gets the fields you chose, whatever billing adds next, and the schema only has to describe your own result. Services change their responses without asking you. [Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results) covers `outputSchema` in more depth. --- # Running FrontMCP Anywhere > The entry points under @FrontMcp's built-in server. createFetchHandler() serves MCP from Workers and other web-standard runtimes, and connect() and createDirect() call your tools in-process. Source: https://frontmcp.dev/learn/running-frontmcp-anywhere [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 So far, `@FrontMcp` and the `frontmcp` CLI have decided how your server runs: `frontmcp dev` starts an HTTP server, and `frontmcp build` packages the server for a target like Node or Cloudflare Workers. Underneath are a few functions you can call yourself, for when you need to own a part FrontMCP usually owns: the HTTP layer, or the client. Most servers never need them. **You will learn** - What `@FrontMcp` does for you, and which entry points sit under it - How to serve MCP from any runtime that speaks `Request` and `Response` - How to call your tools in-process with `connect()` and `createDirect()` - What changes when you skip the transport: identity, errors and formatting ## What `@FrontMcp` does for you `@FrontMcp({ info, apps })` records your server's configuration and, on Node, starts an HTTP server as soon as the decorated class is defined. The CLI's serverless builds switch that off and wrap the same configuration in the entry point their target needs. When you need something else, these are the pieces to build from: | You want to | Use | You get | | --- | --- | --- | | Serve MCP over HTTP from Node | `@FrontMcp`, with `frontmcp dev` and `frontmcp build` | A running server | | Serve MCP from a runtime that hands you a web `Request`: Cloudflare Workers, Deno, Bun, or a route in another framework | [`FrontMcpInstance.createFetchHandler(config)`](https://frontmcp.dev/reference/sdk/create-fetch-handler) | `(request: Request) => Promise` | | Call your tools from your own code, through an MCP client | [`connect(config, options)`](https://frontmcp.dev/reference/sdk/connect), or `connectClaude()`, `connectOpenAI()`, `connectLangChain()`, `connectVercelAI()` | A `DirectClient` | | Call your tools from your own code, without a client | [`FrontMcpInstance.createDirect(config)`](https://frontmcp.dev/reference/sdk/create), or `create()` for a config without apps | A `DirectMcpServer` | `FrontMcpInstance.runStdio()` and `runUnixSocket()` serve local clients over stdio or a Unix socket. They need Node and aren't covered here. All of them take the configuration you'd give `@FrontMcp`. Keep it in its own module, and decorate a class with it only in the file the CLI runs, because importing a decorated class starts a server: ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp" }, }; ``` ```ts main.ts import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; import { config } from "./config"; @FrontMcp(config) export default class HelpDeskServer {} ``` A worker, a script or an agent imports `config.ts` and never touches `main.ts`. ## Serving MCP from any runtime `FrontMcpInstance.createFetchHandler(config)` returns a function that takes a web `Request` and returns a `Response`, and knows nothing else about where it runs. This is a complete Cloudflare Worker, and the test sends it the same requests Cloudflare would: ```ts worker.ts active import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; const handler = FrontMcpInstance.createFetchHandler(config); export default { async fetch(request: Request): Promise { return (await handler)(request); }, }; ``` ```ts worker.test.ts import { test, expect } from "@frontmcp/testing"; import worker from "./worker"; // What an MCP client sends under 2026-07-28: the method, and for calls the // tool's name, repeated in headers, and the protocol version in two places. function mcp(method: string, params: Record = {}) { return new Request("https://desk.example.com/mcp", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": method, ...(method === "tools/call" ? { "mcp-name": String(params.name) } : {}), }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params: { ...params, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }); } test("lists tools at /mcp", async () => { const body = await (await worker.fetch(mcp("tools/list"))).json(); expect(body.result.tools.map((t: { name: string }) => t.name)).toEqual(["get_ticket"]); }); test("calls a tool", async () => { const body = await (await worker.fetch(mcp("tools/call", { name: "get_ticket", arguments: { id: "T-1" } }))).json(); expect(body.result.structuredContent).toEqual({ id: "T-1", title: "Cannot log in", status: "open" }); }); test("answers health checks on /healthz", async () => { const res = await worker.fetch(new Request("https://desk.example.com/healthz")); expect(await res.json()).toMatchObject({ status: "ok", transport: "web-fetch" }); }); test("answers 404 anywhere else", async () => { const res = await worker.fetch(new Request("https://desk.example.com/", { method: "POST", body: "{}" })); expect(res.status).toBe(404); }); ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp" }, }; ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "open" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND")); return ticket; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` `createFetchHandler()` takes the same configuration as `@FrontMcp`. The handler serves MCP at `http.entryPath`, or at `/` if you don't set one, answers `/healthz` and `/readyz` everywhere, and returns 404 for anything else. It returns a promise of the handler, and builds the server when you call it, so a server that can't start fails there. On an edge isolate like a Worker, which can't build a server while the module loads, it builds on the first request instead: see [`createFetchHandler()`](https://frontmcp.dev/reference/sdk/create-fetch-handler#returns). This site's Playground runs on the same function. It builds a fetch handler from each example and sends it requests from a Web Worker in your browser, and the Wire tab shows those requests. In a project, deploy the Worker like any other; FrontMCP's CLI also has a Cloudflare build target that writes this entry file for you. Any other runtime or framework that gives you a `Request` and takes a `Response` back can call `handler(request)` the same way. Behind `createFetchHandler()`, your tools see the request much as they would behind FrontMCP's own server: a `traceparent` header continues the client's trace, and `this.context.metadata` has the user agent and the `x-frontmcp-*` headers. A deep dive in [Reading the Request](https://frontmcp.dev/learn/reading-the-request) tests it. ## Calling your tools through a client: `connect()` Sometimes your own code is the MCP client: an agent loop that calls a model's API directly, a command-line tool, a job. `connect(config, options)` builds the server in your process and connects a client to it in memory. It goes through the same handshake and requests as a client over HTTP, without a network. The `connectClaude()`, `connectOpenAI()`, `connectLangChain()` and `connectVercelAI()` variants also convert tools and results to the shape each API or library expects: ```ts agent.test.ts active import { test, expect } from "@frontmcp/testing"; import { ToolCallError, connectClaude } from "@frontmcp/sdk"; import { config } from "./config"; test("tools come in the shape Claude's Messages API takes", async () => { const client = await connectClaude(config); const tools = await client.listTools(); await client.close(); expect(tools).toEqual([ { name: "get_ticket", description: "Get one support ticket by its id.", input_schema: expect.objectContaining({ type: "object", required: ["id"] }), }, ]); }); test("results come back as content blocks", async () => { const client = await connectClaude(config); const result = await client.callTool("get_ticket", { id: "T-1" }); await client.close(); expect(result).toEqual([{ type: "text", text: '{"id":"T-1","title":"Cannot log in","status":"open"}' }]); }); test("a failed call rejects with a ToolCallError", async () => { const client = await connectClaude(config); const error = await client.callTool("get_ticket", { id: "T-9" }).catch((err: unknown) => err); await client.close(); expect(error).toBeInstanceOf(ToolCallError); expect((error as ToolCallError).message).toBe("There's no ticket T-9."); expect((error as ToolCallError).result.content).toEqual([{ type: "text", text: "There's no ticket T-9." }]); }); ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], }; ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "open" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND")); return ticket; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` `listTools()` returns tools with `input_schema`, ready to pass to Claude, and `callTool()` returns the result's content blocks, ready for a `tool_result`. Claude's format has no place for MCP's `isError`, so a failed call doesn't return at all: it rejects with a `ToolCallError`, whose `message` is the tool's error text and whose `result` is the full MCP result. An agent that doesn't catch it stops at the first failed call, when the model could have tried another id. The second challenge catches it and sends the failure back as a `tool_result` with `is_error: true`. Plain `connect()` returns the full MCP result instead, `isError` included, for code that wants to convert it itself. `connect()` also takes who the client is and who the user is: ```ts const client = await connect(config, { clientInfo: { name: "desk-agent", version: "1.0.0" }, authToken: userToken, session: { user: { sub: "nour" }, scopes: ["tickets:write"] }, }); ``` `clientInfo` becomes [`this.clientInfo`](https://frontmcp.dev/learn/reading-the-request) in your tools, `session.user` becomes the caller in `this.auth`, and `session.scopes` the caller's scopes, so `this.auth.hasScope("tickets:write")` is `true` (since 1.9.3). These explicit users and scopes are trusted: only pass what your own code has verified. Changed in 1.11.1: before, `authToken` was only passed along; it now goes through the server's configured auth mode. If it identifies a nonanonymous caller, verified claims replace the explicit user and scopes, and `this.context.authInfo.clientId` is the verified subject. Without `auth`, or with an opaque token in public mode, the token is passed through unverified and identifies no caller. Public mode still verifies JWTs. Read the caller from `this.auth`, as this course's tools do; [`connect()`](https://frontmcp.dev/reference/sdk/connect#who-is-calling) has the details. ## Calling your tools without a client: `createDirect()` A script or a job often doesn't need a client at all, just a way to run a tool. `FrontMcpInstance.createDirect(config)` returns a `DirectMcpServer` with `listTools()`, `callTool()`, `listResources()`, `readResource()`, `listPrompts()`, `getPrompt()` and `dispose()`. `create()` does the same from a flat configuration with `tools` and `providers` at the top level and no `@App`, which is what the tests in [Reading the Request](https://frontmcp.dev/learn/reading-the-request) use. Its results are plain MCP results, and each call can say who the user is with `authContext`: `authContext.user` stands in for the claims of a verified token, so its `sub` becomes `this.auth.user.sub` and its `roles` become `this.auth.roles`. Here a nightly job closes tickets as the user `nightly-cleanup`: ```ts nightly.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance, connect } from "@frontmcp/sdk"; import { config } from "./config"; const asJob = { authContext: { user: { sub: "nightly-cleanup" } } }; test("a job can call tools as a named user", async () => { const server = await FrontMcpInstance.createDirect(config); const result = await server.callTool("close_ticket", { id: "T-1" }, asJob); await server.dispose(); expect(result.structuredContent).toEqual({ id: "T-1", status: "closed", closed_by: "nightly-cleanup" }); }); test("a failed call throws, instead of returning isError", async () => { const server = await FrontMcpInstance.createDirect(config); await expect(server.callTool("close_ticket", { id: "T-9" }, asJob)).rejects.toThrow("There's no ticket T-9."); await expect(server.callTool("close_ticket", { id: 9 }, asJob)).rejects.toThrow("Invalid tool input"); await server.dispose(); }); test("🚩 without authContext, the caller is `direct`, not anonymous", async () => { const server = await FrontMcpInstance.createDirect(config); const result = await server.callTool("close_ticket", { id: "T-2" }); await server.dispose(); expect(result.structuredContent).toEqual({ id: "T-2", status: "closed", closed_by: "direct" }); }); test("one server, several users: each call runs as the user it names", async () => { const server = await FrontMcpInstance.createDirect(config); const ana = await server.callTool("close_ticket", { id: "T-1" }, { authContext: { user: { sub: "ana" } } }); const bo = await server.callTool("close_ticket", { id: "T-2" }, { authContext: { user: { sub: "bo" } } }); const job = await server.callTool("close_ticket", { id: "T-1" }, asJob); await server.dispose(); expect(ana.structuredContent).toMatchObject({ closed_by: "ana" }); expect(bo.structuredContent).toMatchObject({ closed_by: "bo" }); expect(job.structuredContent).toMatchObject({ closed_by: "nightly-cleanup" }); }); test("connect() takes the user from `session.user`", async () => { const client = await connect(config, { session: { user: { sub: "nightly-cleanup" } } }); const result = await client.callTool("close_ticket", { id: "T-2" }); await client.close(); expect(result).toMatchObject({ structuredContent: { closed_by: "nightly-cleanup" } }); }); ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], }; ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "open" }, ]; @Tool({ name: "close_ticket", description: "Close a support ticket. Signed-in agents only.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { if (this.auth.isAnonymous) this.fail(new PublicMcpError("Sign in to close tickets.", "SIGN_IN_REQUIRED")); const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND")); ticket.status = "closed"; return { id, status: ticket.status, closed_by: this.auth.user.sub }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket] }) export class HelpDesk {} ``` Two things work differently from a client, and the tests show both: - **Failures are exceptions.** Over MCP, a tool that fails returns a result with `isError: true`. `callTool()` here rejects instead, with the `PublicMcpError` the tool failed with, `code` and all, or an `InvalidInputError` for bad arguments. Wrap calls in `try` when one failure shouldn't stop the job. - **No `authContext` isn't anonymous.** Without it, the caller is a signed-in user called `direct`: `this.auth.user.sub` is `"direct"` and `isAnonymous` is `false`, so a tool's check for anonymous callers lets the call through. Always name the user, even for jobs. One server can serve many users. Each call runs as the user its `authContext` names, and gets a `this.context` of its own, with its own `requestId` and `authInfo`. The fourth test closes tickets as Ana, Bo and the job on one server, and each ticket records the right user. A server you build this way inside a Cloudflare Worker, in a Durable Object or a queue consumer, gets no request from a fetch handler, so it doesn't see the Worker's `env` by itself. Pass it as `workerEnv`, in `createDirect()`'s configuration, on one call, or in `connect()`'s options, and your tools read it as `this.workerEnv` (since 1.9.4). [Passing a Worker's bindings](https://frontmcp.dev/reference/sdk/create#passing-a-workers-bindings) shows it. ## Recap - `@FrontMcp` records your configuration and starts a server on import. Keep the configuration in its own module, so other entry points can use it without starting one. - `FrontMcpInstance.createFetchHandler(config)` turns a server into `(request) => Promise`, for Workers and any other web-standard runtime. It serves `http.entryPath`, `/healthz` and `/readyz`. - `connect()` connects an MCP client in memory. The platform variants convert tools and results for an LLM API, and reject a failed call with a `ToolCallError` that carries the result. - `createDirect()` and `create()` run tools with no client: results are MCP results, and failures are thrown. - In-process callers say who the user is and nothing checks it. Pass only users your code has verified, and always pass one. ## Try some challenges ### Challenge: Serve MCP at /mcp The help desk's MCP clients are set up with `https://desk.example.com/mcp`, and this worker answers every one of their requests with a 404. Open the Tests tab, then fix the worker so that MCP requests to `/mcp` work. ```ts worker.ts active import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; const handler = FrontMcpInstance.createFetchHandler(config); export default { async fetch(request: Request): Promise { return (await handler)(request); }, }; ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], }; ``` **Solution file (alternative to the starter):** ```ts config.ts solution import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], http: { entryPath: "/mcp" }, }; ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "open" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND")); return ticket; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` ```ts worker.test.ts import { test, expect } from "@frontmcp/testing"; import worker from "./worker"; function listTools() { return worker.fetch( new Request("https://desk.example.com/mcp", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/list" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } } }), }), ); } test("`tools/list` at `/mcp` answers 200", async () => { const res = await listTools(); expect({ status: res.status, body: await res.text() }).toMatchObject({ status: 200 }); }); test("it lists `get_ticket`", async () => { const body = await (await listTools()).json(); expect(body.result?.tools).toContainTool("get_ticket"); }); test("health checks still answer at `/healthz`", async () => { const res = await worker.fetch(new Request("https://desk.example.com/healthz")); expect(res.status).toBe(200); }); ``` **Hint:** The handler serves MCP at one path and answers 404 everywhere else. Where is that path when the configuration doesn't name one? **Solution:** Without `http.entryPath`, the handler serves MCP at `/`, so a request to `/mcp` got the same 404 as any other unknown path. `http: { entryPath: "/mcp" }` moves the MCP endpoint there, and `/healthz` and `/readyz` keep answering where they were. The fix belongs in the configuration rather than the worker, so every entry point that uses `config.ts` agrees on the path. ### Challenge: Keep failures visible to Claude `toolResult()` in `agent.ts` runs a tool for an agent that talks to Claude's Messages API, and returns the `tool_result` block to send back. When the tool fails, `connectClaude()`'s `callTool()` rejects, and so does `toolResult()`, so the agent never tells the model. Return a `tool_result` for a failed call too, with `is_error: true` and the tool's content blocks. ```ts agent.ts active import { connectClaude } from "@frontmcp/sdk"; import { config } from "./config"; export async function toolResult(toolUseId: string, name: string, input: Record) { const client = await connectClaude(config); try { const content = await client.callTool(name, input); return { type: "tool_result", tool_use_id: toolUseId, content, is_error: false }; } finally { await client.close(); } } ``` **Solution file (alternative to the starter):** ```ts agent.ts solution import { ToolCallError, connectClaude } from "@frontmcp/sdk"; import { config } from "./config"; export async function toolResult(toolUseId: string, name: string, input: Record) { const client = await connectClaude(config); try { const content = await client.callTool(name, input); return { type: "tool_result", tool_use_id: toolUseId, content, is_error: false }; } catch (err) { if (!(err instanceof ToolCallError)) throw err; return { type: "tool_result", tool_use_id: toolUseId, content: err.result.content, is_error: true }; } finally { await client.close(); } } ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], }; ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "open" }, ]; @Tool({ name: "get_ticket", description: "Get one support ticket by its id.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND")); return ticket; } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDesk {} ``` **Hidden fixture/test file (runs with the example):** ```ts agent.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { toolResult } from "./agent"; test("a failed call has `is_error: true`", async () => { expect(await toolResult("toolu_1", "get_ticket", { id: "T-9" })).toEqual({ type: "tool_result", tool_use_id: "toolu_1", content: [{ type: "text", text: "There's no ticket T-9." }], is_error: true, }); }); test("a good call has `is_error: false` and the same content blocks", async () => { expect(await toolResult("toolu_2", "get_ticket", { id: "T-1" })).toEqual({ type: "tool_result", tool_use_id: "toolu_2", content: [{ type: "text", text: '{"id":"T-1","title":"Cannot log in","status":"open"}' }], is_error: false, }); }); ``` **Hint:** Wrap the call in `try`. What does the error `callTool()` rejects with carry? **Solution:** A failed call rejects with a `ToolCallError`, and its `result` is the MCP result the tool sent, content blocks and all. Those blocks are text blocks Claude accepts, so the `catch` sends them as they are, with `is_error: true`. The model reads "There's no ticket T-9." as a failure and can try another id. Any other error is rethrown: it isn't the tool's answer, so it shouldn't reach the model as one. Plain `connect()` works too: it returns the failure as a result with `isError`, which you'd copy into `is_error`. ### Challenge: Don't let one failure stop the job `closeAll()` in `nightly.ts` closes a list of tickets for the nightly job. One id in tonight's list doesn't exist, and the whole job stops there. Make it close every ticket it can, and report the ones it couldn't with their error `code`. Call the tools as `nightly-cleanup` while you're at it: right now the job runs as `direct`. ```ts nightly.ts active import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; export async function closeAll(ids: string[]) { const server = await FrontMcpInstance.createDirect(config); const closed: unknown[] = []; for (const id of ids) { const result = await server.callTool("close_ticket", { id }); closed.push(result.structuredContent); } await server.dispose(); return { closed, failed: [] as { id: string; code: string }[] }; } ``` **Solution file (alternative to the starter):** ```ts nightly.ts solution import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; export async function closeAll(ids: string[]) { const server = await FrontMcpInstance.createDirect(config); const closed: unknown[] = []; const failed: { id: string; code: string }[] = []; try { for (const id of ids) { try { const result = await server.callTool("close_ticket", { id }, { authContext: { user: { sub: "nightly-cleanup" } } }); closed.push(result.structuredContent); } catch (err) { failed.push({ id, code: (err as { code?: string }).code ?? "UNKNOWN" }); } } } finally { await server.dispose(); } return { closed, failed }; } ``` ```ts config.ts import { HelpDesk } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], }; ``` ```ts help-desk.app.ts import { App, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "open" }, ]; @Tool({ name: "close_ticket", description: "Close a support ticket. Signed-in agents only.", inputSchema: { id: z.string().regex(/^T-\d+$/).describe("Ticket id, like T-1") }, }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { if (this.auth.isAnonymous) this.fail(new PublicMcpError("Sign in to close tickets.", "SIGN_IN_REQUIRED")); const ticket = tickets.find((t) => t.id === id); if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "TICKET_NOT_FOUND")); ticket.status = "closed"; return { id, status: ticket.status, closed_by: this.auth.user.sub }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket] }) export class HelpDesk {} ``` **Hidden fixture/test file (runs with the example):** ```ts nightly.test.ts hidden import { test, expect } from "@frontmcp/testing"; import { closeAll } from "./nightly"; test("tickets after a missing one still get closed", async () => { const report = await closeAll(["T-1", "T-9", "T-2"]); expect(report.closed).toHaveLength(2); }); test("the missing ticket is reported with its code", async () => { const report = await closeAll(["T-1", "T-9", "T-2"]); expect(report.failed).toEqual([{ id: "T-9", code: "TICKET_NOT_FOUND" }]); }); test("tickets are closed by `nightly-cleanup`", async () => { const report = await closeAll(["T-1"]); expect(report.closed).toEqual([{ id: "T-1", status: "closed", closed_by: "nightly-cleanup" }]); }); ``` **Hint:** `callTool()` rejects when a tool fails, and the error it rejects with has the tool's `code`. Pass the user as the third argument: `{ authContext: { user: { sub: "nightly-cleanup" } } }`. **Solution:** Each call gets its own `try`, so a failure is recorded and the loop moves on. The error is the `PublicMcpError` the tool failed with, so its `code` says why. The outer `try` makes sure the server is disposed even if something unexpected escapes. And the `authContext` puts the job's name on every ticket it closes, instead of the `direct` user FrontMCP fills in when you don't name one. --- # FrontMCP API reference > The FrontMCP API reference for TypeScript MCP servers, from decorators and contexts to auth, plugins, testing and deployment, checked against the SDK it describes, with a runnable example for everything that can run in a browser. Source: https://frontmcp.dev/reference [Covers FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) as of November 14, 2026 Reference is the complete documentation for FrontMCP: every decorator, option and API, what it does, and what to do when it doesn't work. Each page is checked against the FrontMCP version this site documents, and most examples run right on the page. To learn FrontMCP from the beginning, start with the [Quick Start](https://frontmcp.dev/learn); to see how it differs from the official MCP SDK and other TypeScript frameworks, read [Compare](https://frontmcp.dev/compare). Each page follows the same structure: - **Reference**: the signature, every option, what it returns, and caveats. - **Usage**: common tasks, each with a runnable example. - **Troubleshooting**: problems you might hit, titled by what you'll see. ## @frontmcp/sdk Every page of the SDK reference, grouped, with which page answers which task, is in the [SDK overview](https://frontmcp.dev/reference/sdk). ### Decorators Decorators declare what your server exposes. | Decorator | Declares | | --- | --- | | [`@FrontMcp`](https://frontmcp.dev/reference/sdk/frontmcp) | The server: its apps and server-wide settings | | [`@App`](https://frontmcp.dev/reference/sdk/app) | A group of tools, resources, prompts and providers | | [`@Tool`](https://frontmcp.dev/reference/sdk/tool) | A function the model can call | | [`@Resource`](https://frontmcp.dev/reference/sdk/resource) | Data at a fixed URI | | [`@ResourceTemplate`](https://frontmcp.dev/reference/sdk/resource-template) | Data at a family of URIs, like `ticket://{id}` | | [`@Prompt`](https://frontmcp.dev/reference/sdk/prompt) | A reusable message template | | [`@Provider`](https://frontmcp.dev/reference/sdk/provider) | A service tools can share, via dependency injection | | [`@Job`](https://frontmcp.dev/reference/sdk/job) | A unit of work that can run in the background, with retries and a run record | | [`@Workflow`](https://frontmcp.dev/reference/sdk/workflow) | Jobs run as steps, in dependency order | | [`@Agent`](https://frontmcp.dev/reference/sdk/agent) | A tool that runs its own model loop, with its own tools and instructions | | [`@Skill`](https://frontmcp.dev/reference/sdk/skill) | Instructions a client's model can find and follow, served as resources | | [`@Plugin`](https://frontmcp.dev/reference/sdk/plugin) | A reusable package of providers, hooks and context extensions | | [`@Channel`](https://frontmcp.dev/reference/sdk/channel) | Events a server pushes to clients | | [`@Event`](https://frontmcp.dev/reference/sdk/event) | An event type clients subscribe to, and how to publish it | | [Hook decorators](https://frontmcp.dev/reference/sdk/hooks) | Code that runs before, after or around a stage of a call | ### Events MCP Events (a draft extension of MCP, SEP-3415): a client subscribes once, and the server tells it each time something happens. | Page | Covers | | --- | --- | | [`@Event`](https://frontmcp.dev/reference/sdk/event) | Declaring an event, who may see it, and publishing an occurrence | | [Event subscriptions and delivery](https://frontmcp.dev/reference/sdk/event-delivery) | Polling, streaming and webhook subscriptions, signed deliveries, errors and dialects | | [Events options](https://frontmcp.dev/reference/sdk/events-options) | Delivery modes, lifetimes, the subscription store and the HTTP publish endpoint | ### Context Inside `execute()`, `this` is the call's context. [Context classes](https://frontmcp.dev/reference/sdk/contexts) lists what each kind of context has; the most used members have their own pages: | Member | Does | | --- | --- | | [`this.auth`](https://frontmcp.dev/reference/sdk/auth) | Who is calling: user, scopes and roles | | [`this.context`](https://frontmcp.dev/reference/sdk/context) | The request: its id, trace, auth info and headers | | [`this.elicit()`](https://frontmcp.dev/reference/sdk/elicit) | Asks the user for input in the middle of a call | | [`this.progress()`](https://frontmcp.dev/reference/sdk/progress) | Reports how far a long call has got | | [`this.notify()`](https://frontmcp.dev/reference/sdk/notify) | Sends a log message to the client | | [`this.get()`](https://frontmcp.dev/reference/sdk/get) | Gets a provider (see [`@Provider`](https://frontmcp.dev/reference/sdk/provider)) | | [`this.fetch()`](https://frontmcp.dev/reference/sdk/fetch) | Makes an outbound HTTP request | | [`this.fail()`](https://frontmcp.dev/reference/sdk/fail) | Ends the call with an error the model can read | | [`this.callTool()`](https://frontmcp.dev/reference/sdk/call-tool) | Calls another tool on the server | | [`this.respond()`](https://frontmcp.dev/reference/sdk/respond) | Ends the call early with a finished result | ### Running a server | API | Does | | --- | --- | | [`FrontMcpInstance`](https://frontmcp.dev/reference/sdk/frontmcp-instance) | Starts the HTTP server a decorated class describes | | [`createFetchHandler()`](https://frontmcp.dev/reference/sdk/create-fetch-handler) | A web-standard `Request → Response` handler, for Workers, Deno, Bun and frameworks | | [`create()` and `createDirect()`](https://frontmcp.dev/reference/sdk/create) | A server in your own process, called without HTTP | | [`connect()` and client adapters](https://frontmcp.dev/reference/sdk/connect) | The server's tools, ready for Claude, OpenAI, LangChain or the Vercel AI SDK | ### Limits, errors and the scope - [Guard options](https://frontmcp.dev/reference/sdk/guard): rate limits, concurrency caps, timeouts and IP filters. - [Error classes](https://frontmcp.dev/reference/sdk/error-classes) and [error codes](https://frontmcp.dev/reference/errors): what to throw, and what a client sees. - [Scope and registries](https://frontmcp.dev/reference/sdk/scope): the server's registries, from inside a call. ## Server and configuration How a server is put together and configured, across decorators: | Page | Covers | | --- | --- | | [Server overview](https://frontmcp.dev/reference/server) | Every page in this section, grouped, and which page answers which task | | [Apps, discovery and splitting](https://frontmcp.dev/reference/server/apps) | Composing a server from apps, what clients discover, and serving apps separately | | [Flows and stages](https://frontmcp.dev/reference/server/flows) | Every flow FrontMCP runs for a request, and the stages hooks attach to | | [Loading apps from npm (ESM)](https://frontmcp.dev/reference/server/esm) | `App.esm()`: apps loaded from a registry at run time | | [Remote servers](https://frontmcp.dev/reference/server/remote) | Another MCP server mounted as an app | | [Configuration files](https://frontmcp.dev/reference/server/config-files) | Config files and every environment variable FrontMCP reads | | [Logging](https://frontmcp.dev/reference/server/logging) | The server's own logs, levels and transports | | [Observability and telemetry](https://frontmcp.dev/reference/server/observability) | Tracing, metrics and health endpoints | | [Environment awareness](https://frontmcp.dev/reference/server/environment) | Capabilities that depend on the runtime and environment | ## Authentication How a server authenticates MCP clients, and decides what each caller may do: | Page | Covers | | --- | --- | | [Authentication overview](https://frontmcp.dev/reference/auth) | Every page in this section, grouped, and which page answers which task | | [Auth modes](https://frontmcp.dev/reference/auth/modes) | Every mode, what it protects, and how to choose | | [Tokens and sessions](https://frontmcp.dev/reference/auth/tokens) | How tokens are verified, sessions, and the secrets behind them | | [Local auth](https://frontmcp.dev/reference/auth/local) | FrontMCP as its own OAuth authorization server | | [Custom login UI](https://frontmcp.dev/reference/auth/login-ui) | The login and consent pages, and replacing them | | [Progressive auth](https://frontmcp.dev/reference/auth/progressive) | Asking for more access later, when a tool needs it | | [Remote and proxied auth](https://frontmcp.dev/reference/auth/remote) | An external identity provider as the authorization server | | [Client ID metadata (CIMD)](https://frontmcp.dev/reference/auth/cimd) | Clients identified by a metadata document instead of registration | | [Authorities](https://frontmcp.dev/reference/auth/authorities) | Roles, permissions and rules on tools, resources, prompts, agents and skills | | [Auth in production](https://frontmcp.dev/reference/auth/production) | The checklist for running an authenticated server | ## Plugins and adapters Official packages that add behaviour to a server, or turn an API into tools: | Page | Covers | | --- | --- | | [Plugins overview](https://frontmcp.dev/reference/plugins) | The official plugins and adapters, their packages, and how to add them to a server | | [Cache](https://frontmcp.dev/reference/plugins/cache) | Reusing a tool's result for identical calls, per caller or shared | | [Remember](https://frontmcp.dev/reference/plugins/remember) | Memory tools can read and write across calls, per session, user or tool | | [Approval](https://frontmcp.dev/reference/plugins/approval) | Requiring the user's approval before a tool runs | | [Feature flags](https://frontmcp.dev/reference/plugins/feature-flags) | Turning tools, resources and prompts on and off with flags | | [CodeCall](https://frontmcp.dev/reference/plugins/codecall) | Letting the model search many tools and call them from a short script | | [Skilled OpenAPI](https://frontmcp.dev/reference/plugins/skilled-openapi) | Serving a REST API as a few skills instead of one tool per endpoint | | [OpenAPI adapter](https://frontmcp.dev/reference/adapters/openapi) | Every operation in an OpenAPI spec as a tool | ## Tool UI and React Widgets a tool shows in the host, and React apps that talk to a server: | Page | Covers | | --- | --- | | [Tool UI](https://frontmcp.dev/reference/ui) | A tool's `ui` option, the `ui://widget` resource, serving modes and the widget's Content Security Policy | | [Widget components](https://frontmcp.dev/reference/ui/components) | Widgets written as React files, `@frontmcp/ui` hooks and components, and `@frontmcp/uipack` | | [Hosts and platforms](https://frontmcp.dev/reference/ui/hosts) | How the client is recognized, the widget's bridge, MCP Apps hosts and the OpenAI Apps SDK | | [@frontmcp/react](https://frontmcp.dev/reference/react) | A server in the same process as a React app: the provider, its client, several servers, stores | | [React hooks](https://frontmcp.dev/reference/react/hooks) | Calling tools, reading resources and prompts, and registering tools from components | | [React components](https://frontmcp.dev/reference/react/components) | Generated forms, result viewers, `mcpComponent`, DOM resources and the router bridge | ## @frontmcp/testing End-to-end tests that start a server and call it like a client: | Page | Covers | | --- | --- | | [`test` and the `mcp` client](https://frontmcp.dev/reference/testing) | Writing tests, the client, and the result wrappers | | [Matchers](https://frontmcp.dev/reference/testing/matchers) | The MCP-specific `expect` matchers | | [Fixtures](https://frontmcp.dev/reference/testing/fixtures) | `test.use()`, and the `mcp`, `server` and `auth` fixtures and their lifetimes | | [Interceptors and HTTP mocking](https://frontmcp.dev/reference/testing/interceptors) | `mcp.mock`, `mcp.intercept`, `MockAPIServer` and `httpMock` | | [Testing authentication](https://frontmcp.dev/reference/testing/auth) | Tokens, clients that call as a user, and `MockOAuthServer` | ## CLI and Nx Creating, running and building servers, alone or in an Nx workspace: | Page | Covers | | --- | --- | | [frontmcp CLI](https://frontmcp.dev/reference/cli) | Every command and option: create, dev, build and its targets, test, inspector and more | | [Nx plugin](https://frontmcp.dev/reference/nx) | What `@frontmcp/nx` adds, installing it, and the workspace layout | | [Nx generators](https://frontmcp.dev/reference/nx/generators) | Every generator, its options, and what it writes | | [Nx executors](https://frontmcp.dev/reference/nx/executors) | Every executor, its options, and the command it runs | | [Monorepo patterns](https://frontmcp.dev/reference/nx/monorepo) | Apps, shared libraries and server shells, and composing apps into one server | ## Deployment Building a server and running it in production: | Page | Covers | | --- | --- | | [Deployment overview](https://frontmcp.dev/reference/deployment) | Every page in this section, grouped, and which page answers which task | | [Production build](https://frontmcp.dev/reference/deployment/production-build) | `frontmcp build`, what each target writes and bundles, and how the result runs | | [Node.js and Docker](https://frontmcp.dev/reference/deployment/node) | The node build on a machine, in Docker, with Redis in Compose, behind nginx, or on a Unix socket | | [Vercel](https://frontmcp.dev/reference/deployment/vercel) | The Vercel target, what the function serves, and Vercel KV | | [AWS Lambda](https://frontmcp.dev/reference/deployment/aws-lambda) | The Lambda handler, what ships beside it, and the events it accepts | | [Cloudflare Workers](https://frontmcp.dev/reference/deployment/cloudflare-workers) | The Worker entry, `wrangler.toml`, secrets and bindings | | [Redis](https://frontmcp.dev/reference/deployment/redis) | The `redis` option, what's kept under which keys, and what happens when Redis is down | | [SQLite](https://frontmcp.dev/reference/deployment/sqlite) | Sessions, tasks and pending questions in a SQLite file on one machine | | [High availability](https://frontmcp.dev/reference/deployment/high-availability) | Several instances behind a load balancer, and what they must share | | [Health checks and metrics](https://frontmcp.dev/reference/deployment/health-and-metrics) | `/healthz`, `/readyz` and `/metrics` on each runtime, and wiring them to probes | | [Security headers and transport](https://frontmcp.dev/reference/deployment/security) | Headers, bind address and host checks, body limits, and exposed endpoints | | [Connecting MCP clients](https://frontmcp.dev/reference/deployment/mcp-clients) | Clients over Streamable HTTP, stdio or a Unix socket, and MCP Bundles | ## Guides - [Rules of FrontMCP](https://frontmcp.dev/reference/rules): the short list of rules that keep servers correct and safe. - [Security](https://frontmcp.dev/reference/security): how to report a vulnerability, the defaults a new server starts with, and what FrontMCP does about each risk in the OWASP MCP Top 10. --- # Maintainers and corrections > FrontMCP's publisher, source, license, article authors and public documentation correction route. Source: https://frontmcp.dev/reference/maintainers [Covers FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) as of November 14, 2026 FrontMCP is published by AgentFront. Its [framework source](https://github.com/agentfront/frontmcp), release history and issue tracker are public. The software uses the Apache 2.0 license. This site documents the framework; hosting, model calls and external services have their own costs and terms. ## David Antoon David Antoon is the named author of the site's [implementation notes and guides](https://frontmcp.dev/blog), and is [frontegg-david](https://github.com/frontegg-david) on GitHub. Each article preserves its original publication date. A visible update date records a substantive revision; a stated example version identifies its scope. Runnable Playground checks and editorial review are described separately on [Versions](https://frontmcp.dev/versions#how-pages-are-checked). ## Report a documentation issue Use the “Report a docs issue” link below a page. It opens the framework's public GitHub issue form with only the page URL and documented release prefilled. Describe the unclear instruction, expected behavior and a minimal sanitized reproduction. Do not include credentials, private source or customer records. For a potential vulnerability, use the [private security reporting channel](https://frontmcp.dev/reference/security) instead of a public issue. Product plans are not release commitments; check the maintained reference and releases for available capabilities. --- # Site usage and privacy > What runs locally in the FrontMCP Playground, which usage events the site records, and what Global Privacy Control changes. Source: https://frontmcp.dev/reference/site-privacy [Covers FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) as of November 14, 2026 Playground code executes in your browser. Code you add can make network calls permitted by its runtime. Downloading runtime files, searching the docs and using external services also uses the network. The site records limited aggregate usage events to understand which examples and actions work. ## Usage events The page sends event names, page paths, example positions, selected fixed labels, startup/call durations and test counts to this site's `/api/events` endpoint. The receiver also obtains an approximate country from the hosting request metadata. New call-completion events distinguish successful results, tool errors, protocol errors and transport failures; an intentionally refused example can still be correct. Each page load also sends its loading and responsiveness timings (largest contentful paint, interaction to next paint, layout shift, first contentful paint and server response time) with the page's path, measured in your browser and sent to the same endpoint. No third-party analytics script runs on the site. The event schema does not collect code, prompts, tokens, tool arguments, tool results or raw search text. It has no visitor or session ID. Counts and event ratios do not identify unique people or establish a person-level conversion funnel. ## Global Privacy Control When your browser enables Global Privacy Control, the page's usage-event sender does not send its batches. That control does not imply zero requests: server-side assistant-referral classification and browser Content Security Policy reports are separate paths. Referral records use the recognized source and page path, not a copy of the whole referrer URL. CSP reports describe blocked resources; they are diagnostic reports rather than Playground source uploads. ## Sharing examples The Playground's Share/Open links carry example files in the URL fragment. Anyone you send that link to can read those files. Keep credentials and private code out of shared examples. Downloadable projects contain the published fixtures, not your local edits. ## Corrections See [maintainers and corrections](https://frontmcp.dev/reference/maintainers) for documentation feedback and [Security](https://frontmcp.dev/reference/security) for private vulnerability reporting. --- # @frontmcp/sdk reference > The decorators that declare what a FrontMCP server exposes, the context members your code calls inside a tool, resource or prompt, and the entry points that run a server over HTTP, in a Worker or in your own process. Source: https://frontmcp.dev/reference/sdk [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@frontmcp/sdk` is the package a FrontMCP server is written with. Its pages fall into three groups. **Decorators** declare what the server exposes, from `@FrontMcp` and `@App` down to `@Tool`, `@Resource` and `@Prompt`. **Context members** are what `this` offers inside `execute()`, like `this.auth`, `this.get()` and `this.fail()`. **Entry points** run the same classes over HTTP, in a Worker or another web-standard runtime, or inside your own process. Events, limits, errors, the scope and the `z` you write schemas with complete the section. This page is for looking things up; [Your First Tool](https://frontmcp.dev/learn/your-first-tool) teaches the same pieces in order. ```ts import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; ``` --- ## Decorators Decorators declare what your server exposes. | Page | Declares | | --- | --- | | [`@FrontMcp`](https://frontmcp.dev/reference/sdk/frontmcp) | An MCP server, the apps it hosts, and the settings that apply to all of them | | [`@App`](https://frontmcp.dev/reference/sdk/app) | Related tools, resources, prompts and providers, grouped into an app the server hosts | | [`@Tool`](https://frontmcp.dev/reference/sdk/tool) | A function an AI model can call, with validated input and optional structured output | | [`@Resource`](https://frontmcp.dev/reference/sdk/resource) | Data at a fixed URI that clients can list and read, like a policy document | | [`@ResourceTemplate`](https://frontmcp.dev/reference/sdk/resource-template) | A family of resources whose URIs follow a pattern, like `ticket://{id}` | | [`@Prompt`](https://frontmcp.dev/reference/sdk/prompt) | A reusable message template that users pick in their client and fill in with arguments | | [`@Duty`](https://frontmcp.dev/reference/sdk/duty) | Recurring provider work, every interval or on a cron schedule, with a lease held by one process of a machine, a workspace or a cluster | | [`@Worker`](https://frontmcp.dev/reference/sdk/worker) | A supervised long-running background process, run in every process or in one under a lease | | [`@HttpRoute`](https://frontmcp.dev/reference/sdk/http-route) | Pages, JSON and SSE views alongside MCP | | [`@Provider`](https://frontmcp.dev/reference/sdk/provider) | A shared service, like a database client or a cache, that tools, resources and prompts get with `this.get()` | | [`@Job`](https://frontmcp.dev/reference/sdk/job) | A unit of work with validated input that clients run by name, while they wait or in the background, with retries | | [`@Workflow`](https://frontmcp.dev/reference/sdk/workflow) | Jobs chained into steps that run in order or in parallel, each step's input built from the results before it | | [`@Agent`](https://frontmcp.dev/reference/sdk/agent) | A tool that runs its own model loop, with its own instructions and tools, so a client's model can hand it a whole task | | [`@Skill`](https://frontmcp.dev/reference/sdk/skill) | A written procedure, with the tools it uses, that clients find and load for their model to follow | | [`@Plugin`](https://frontmcp.dev/reference/sdk/plugin) | Providers, tools, resources, prompts, skills and hooks, packaged so an app or a whole server turns them on with one line | | [`@Adapter`](https://frontmcp.dev/reference/sdk/adapter) | Tools, resources and prompts built from another source when the server starts, like a spec or a list of saved views, and replaced while it runs | | [`@Channel`](https://frontmcp.dev/reference/sdk/channel) | Events pushed into a connected Claude Code session as they happen | | [`@Event`](https://frontmcp.dev/reference/sdk/event) | An event type that clients list and subscribe to, and are told about each time your code publishes it. See [Events](https://frontmcp.dev/reference/sdk#events) | | [Hook decorators](https://frontmcp.dev/reference/sdk/hooks) | `Will`, `Did`, `Finally`, `Around` and `Stage`: code that runs before, after success, after any outcome, around or inside a request stage | ## Events MCP Events let a server tell a client that something happened, without being asked: the client subscribes once, and gets each occurrence by poll, stream or webhook. It's a draft extension of MCP (SEP-3415). New in 1.12. | Page | Covers | | --- | --- | | [`@Event`](https://frontmcp.dev/reference/sdk/event) | Declaring an event with `@Event` or `event()`, who may see it, and publishing an occurrence with `this.events.publish()` from a tool or from background code | | [Event subscriptions and delivery](https://frontmcp.dev/reference/sdk/event-delivery) | What a client sends and receives: `events/poll`, `events/stream` and `events/subscribe`, signed webhook deliveries and their retries, the errors, and the two dialects | | [Events options](https://frontmcp.dev/reference/sdk/events-options) | `@FrontMcp({ events })`: which delivery modes a server performs, lifetimes and limits, the subscription store, and the HTTP publish endpoint | ## Context Inside `execute()`, `this` is the call's context. [Context classes](https://frontmcp.dev/reference/sdk/contexts) lists what `this` is in a tool, resource, prompt, agent, job, channel or skill, and every member each one has. The members used most have pages of their own: | Page | Does | | --- | --- | | [`this.auth`](https://frontmcp.dev/reference/sdk/auth) | Who is calling, with their scopes, roles and claims, and what each auth mode and entry point fills in | | [`this.authProviders`](https://frontmcp.dev/reference/sdk/auth-providers) | Gets another service's credential for the caller, from the credential providers the server registers | | [`this.context`](https://frontmcp.dev/reference/sdk/context) | The request a call belongs to: its id, trace, auth info and HTTP metadata, and a store that lasts for the request | | [`this.elicit()`](https://frontmcp.dev/reference/sdk/elicit) | Asks the user for input in the middle of a tool call, and continues with their answer as typed data | | [`this.progress()`](https://frontmcp.dev/reference/sdk/progress) | Tells the client how far a long call has got, when the client asked for progress | | [`this.notify()`](https://frontmcp.dev/reference/sdk/notify) | Sends log messages to the client while a tool runs, at the levels the client asked for | | [`this.get()`](https://frontmcp.dev/reference/sdk/get) | Gets a provider, like a ticket store or your configuration | | [`this.offload()`](https://frontmcp.dev/reference/sdk/offload) | Runs CPU work in a Node worker-thread pool | | [`this.fetch()`](https://frontmcp.dev/reference/sdk/fetch) | Calls another HTTP service, with the request's tracing headers and a default timeout | | [`this.fail()`](https://frontmcp.dev/reference/sdk/fail) | Ends a tool call with an error the model can read, carrying the code you choose | | [`this.callTool()`](https://frontmcp.dev/reference/sdk/call-tool) | Calls another tool of the same server, as the same caller | | [`this.respond()`](https://frontmcp.dev/reference/sdk/respond) | Ends a call early with a result you built yourself, or answers a call from a hook | ## Running a server Importing a class decorated with `@FrontMcp` starts FrontMCP's HTTP server. These run the same configuration in other ways: | Page | Does | | --- | --- | | [`FrontMcpInstance`](https://frontmcp.dev/reference/sdk/frontmcp-instance) | Builds and runs a server from its `@FrontMcp` configuration: over HTTP, stdio or a Unix socket, as a serverless handler, or in-process | | [`createFetchHandler()`](https://frontmcp.dev/reference/sdk/create-fetch-handler) | Serves MCP from any runtime that speaks web `Request` and `Response`, like Cloudflare Workers, Deno, Bun or a framework's route | | [`create()` and `createDirect()`](https://frontmcp.dev/reference/sdk/create) | A server inside your own process, whose tools, resources, prompts and jobs you call as async functions, as a user you name | | [`server.registerTool()`](https://frontmcp.dev/reference/sdk/register-tool) | Adds a tool to a running `create()` or `createDirect()` server from code outside it, and removes it again | | [`connect()` and client adapters](https://frontmcp.dev/reference/sdk/connect) | An MCP client connected in memory, with the server's tools and results in the shape Claude, OpenAI, LangChain or the Vercel AI SDK expects | ## Limits, errors and the scope | Page | Covers | | --- | --- | | [Guard options](https://frontmcp.dev/reference/sdk/guard) | A tool's `rateLimit`, `concurrency` and `timeout`, `@FrontMcp`'s `throttle`, whose calls each limit counts, and the error each one produces | | [Error classes](https://frontmcp.dev/reference/sdk/error-classes) | The SDK's error classes by area, the code a client receives, whether the message survives production, and whether you throw it or FrontMCP does | | [Error codes](https://frontmcp.dev/reference/errors) | What FrontMCP's JSON-RPC error codes and tool error results mean, and how to fix them | | [Scope and registries](https://frontmcp.dev/reference/sdk/scope) | `this.scope`: the registries you can list and search, what you can add at runtime, and which parts are FrontMCP's own machinery | ## `z`, `eagerZ` and `lazyZ` Every example on this site imports `z` from `@frontmcp/sdk`, not from `zod`. It's Zod 4's `z` with one change: `z.object()`, `z.strictObject()`, `z.looseObject()`, `z.union()`, `z.discriminatedUnion()`, `z.intersection()`, `z.record()` and `z.tuple()` return a stand-in, and the real Zod schema is built the first time the schema is used, by a parse or by reading it, like `.shape`. Methods you chain on a stand-in, like `.optional()` and `.describe()`, return stand-ins too. So loading and starting a server doesn't build the objects in its tools' `inputSchema`: they're built when a client first lists the tools or calls one. The other factories, like `z.string()` and `z.enum()`, are Zod's own. | Export | What it is | | --- | --- | | `z` | Zod 4's `z`, with the factories above deferred. Use it for every schema in a FrontMCP server. | | `eagerZ` | Zod's own `z`, the same object `import { z } from "zod"` gives. Its schemas are built when you call it. | | `lazyZ(build)` | A schema that calls `build()` the first time it's used, and only then. For a schema that's costly to make and may never be used, like one converted from a JSON Schema. | | `isLazy(schema)` | `true` for a stand-in, from `z`'s deferred factories or from `lazyZ()`. | | `forceMaterialize(schema)` | The real Zod schema, with every stand-in inside it built. | | `toJSONSchema(schema)` | Zod's JSON Schema converter, run on `forceMaterialize(schema)`, so it takes any `z` schema. | `@frontmcp/lazy-zod` also exports `hasTransform(schema): boolean`, which detects transforms, preprocessors, pipes and codecs anywhere in a schema, including lazy schemas. The SDK uses it to avoid restoring keys a transform intentionally removes; see [Output policy](https://frontmcp.dev/reference/sdk/tool#output-policy). This helper is an import from `@frontmcp/lazy-zod`, which the Playground does not expose as a package. A stand-in behaves like the schema it stands for: it parses, `instanceof ZodObject` is `true`, and `z.infer` gives the same type. The SDK exports Zod's classes, like `ZodObject` and `ZodError`, and its types, so a FrontMCP server needs no import from `zod`. Two things to know: - **Zod's own `toJSONSchema()`** fails on some `z` schemas. `z.toJSONSchema()`, or the function imported from `zod`, throws `TypeError: Cannot set properties of undefined (setting 'ref')` when an object or a union in the schema is `.optional()` or has a `.default()`, like the optional `customer` below. Convert with `toJSONSchema` from `@frontmcp/sdk`, or build that schema with `eagerZ`. - **Schemas from `zod`** work in a tool's `inputSchema` like the SDK's, as long as they're Zod 4: `frontmcp create` adds `zod` `^4.0.0` to a new project. Schemas from Zod 3, `zod@3` or `zod/v3`, aren't recognized: the tool is listed with no properties, and every call fails with `INVALID_INPUT` and `Unknown error occurred when trying to parse input`. Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Cannot log in", customer: { email: "dana@acme.com" } } } ``` ```ts create-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; export const TicketInput = { title: z.string().min(5).describe("One-line summary of the problem"), customer: z.object({ email: z.string().email() }).optional().describe("Who reported it, if known"), }; @Tool({ name: "create_ticket", description: "Open a new support ticket", inputSchema: TicketInput }) export class CreateTicket extends ToolContext { async execute(input: { title: string; customer?: { email: string } }) { return { id: "T-4", status: "open", ...input }; } } ``` ```ts schemas.test.ts import { test, expect } from "@frontmcp/testing"; import { eagerZ, isLazy, lazyZ, toJSONSchema, z, ZodObject } from "@frontmcp/sdk"; import { TicketInput } from "./create-ticket.tool"; test("`z.object()` is a stand-in that behaves like the schema", () => { const customer = z.object({ email: z.string().email() }); expect(isLazy(customer)).toBe(true); expect(isLazy(z.string())).toBe(false); expect(customer instanceof ZodObject).toBe(true); expect(customer.safeParse({ email: "dana" }).success).toBe(false); }); test("`eagerZ` is Zod's own `z`", () => { expect(isLazy(eagerZ.object({ email: eagerZ.string() }))).toBe(false); }); test("`lazyZ()` builds the schema once, the first time it's used", () => { let builds = 0; const imported = lazyZ(() => { builds++; return eagerZ.object({ id: eagerZ.string() }); }); expect(builds).toBe(0); imported.parse({ id: "T-1" }); imported.parse({ id: "T-2" }); expect(builds).toBe(1); }); test("Zod's own `toJSONSchema()` fails on an optional object; the SDK's doesn't", () => { const schema = z.object(TicketInput); expect(() => z.toJSONSchema(schema)).toThrow("Cannot set properties of undefined (setting 'ref')"); const json = toJSONSchema(schema) as { required: string[] }; expect(json.required).toEqual(["title"]); const eager = eagerZ.object({ customer: eagerZ.object({ email: eagerZ.string() }).optional() }); expect(() => eagerZ.toJSONSchema(eager)).not.toThrow(); }); test("FrontMCP lists the tool's schema either way", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t: { name: string }) => t.name === "create_ticket"); expect(tool?.inputSchema.required).toEqual(["title"]); expect(tool?.inputSchema.properties.customer.properties.email.format).toBe("email"); }); ``` ## Which page for which task | You want to | Read | | --- | --- | | Give the model something to call | [`@Tool`](https://frontmcp.dev/reference/sdk/tool) | | Share a database client or an API client between tools | [`@Provider`](https://frontmcp.dev/reference/sdk/provider) and [`this.get()`](https://frontmcp.dev/reference/sdk/get) | | Refuse a call with a message the model can act on | [`this.fail()`](https://frontmcp.dev/reference/sdk/fail) and [Error classes](https://frontmcp.dev/reference/sdk/error-classes) | | Check who is calling before you act | [`this.auth`](https://frontmcp.dev/reference/sdk/auth) | | Send another service the credential it needs for this caller | [`this.authProviders`](https://frontmcp.dev/reference/sdk/auth-providers) | | Confirm with the user before a tool acts | [`this.elicit()`](https://frontmcp.dev/reference/sdk/elicit) | | Run work that takes too long for one tool call | [`@Job`](https://frontmcp.dev/reference/sdk/job) | | Let a model on your server carry out a whole task | [`@Agent`](https://frontmcp.dev/reference/sdk/agent) | | Run code around every call, like logging or auditing | [Hook decorators](https://frontmcp.dev/reference/sdk/hooks), packaged as a [`@Plugin`](https://frontmcp.dev/reference/sdk/plugin) | | Generate tools from a spec, a catalog or a list kept somewhere else | [`@Adapter`](https://frontmcp.dev/reference/sdk/adapter), or the [OpenAPI adapter](https://frontmcp.dev/reference/adapters/openapi) for an OpenAPI spec | | Serve from Cloudflare Workers, Deno or Bun | [`createFetchHandler()`](https://frontmcp.dev/reference/sdk/create-fetch-handler) | | Call your tools from a script or a test, without HTTP | [`create()` and `createDirect()`](https://frontmcp.dev/reference/sdk/create) | | Give your tools to an agent loop built on Claude, OpenAI, LangChain or the Vercel AI SDK | [`connect()` and client adapters](https://frontmcp.dev/reference/sdk/connect) | | Cap how often a tool runs, or how long it may take | [Guard options](https://frontmcp.dev/reference/sdk/guard) | | Find out what an error code means | [Error codes](https://frontmcp.dev/reference/errors) | | Hand a schema to code that calls Zod's own functions | [`z`, `eagerZ` and `lazyZ`](https://frontmcp.dev/reference/sdk#z-eagerz-and-lazyz) | ## The three groups in one server A decorator for each part of the server, context members inside the tool, and the **Tests** tab running the same app through a second entry point, `createDirect()`, in-process and as a named user: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts help-desk.app.ts active import { App, Provider, PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; @Provider({ name: "TicketStore" }) export class TicketStore { private tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; find(id: string) { return this.tickets.find((t) => t.id === id); } } @Tool({ name: "get_ticket", description: "Get one support ticket by its id", inputSchema: { id: z.string().describe("Ticket id, like T-1") }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { const ticket = this.get(TicketStore).find(id); // a provider if (!ticket) this.fail(new PublicMcpError(`There's no ticket ${id}.`, "NOT_FOUND")); // an error the model reads return { ticket, caller: this.auth.user.sub }; // who is calling } } @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket], providers: [TicketStore] }) export class HelpDeskApp {} ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` ```ts help-desk.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; test("the tool gets the store with `this.get()`", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result).toBeSuccessful(); expect(result.json().ticket).toEqual({ id: "T-1", title: "Cannot log in", status: "open" }); }); test("`this.fail()` sends an error the model can read", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-9" }); expect(result).toBeError("NOT_FOUND"); expect(result).toHaveTextContent("There's no ticket T-9."); }); test("over HTTP with no credentials, `this.auth` is an anonymous caller", async ({ mcp }) => { const result = await mcp.tools.call("get_ticket", { id: "T-1" }); expect(result.json().caller).toMatch(/^anon:/); }); test("`createDirect()` runs the same app in-process, as the user you name", async () => { const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); try { const result = await server.callTool("get_ticket", { id: "T-2" }, { authContext: { user: { sub: "agent-7" } } }); expect(result.structuredContent).toMatchObject({ ticket: { id: "T-2", status: "closed" }, caller: "agent-7" }); } finally { await server.dispose(); } }); ``` ## Related pages - [Server configuration](https://frontmcp.dev/reference/server): apps, configuration files, logging, observability and flows, across decorators. - [Authentication and authorization](https://frontmcp.dev/reference/auth): the `auth` and `authorities` options, and what fills in `this.auth`. - [Plugins and adapters](https://frontmcp.dev/reference/plugins): the official plugins and the OpenAPI adapter. - [`@frontmcp/testing`](https://frontmcp.dev/reference/testing): end-to-end tests that call a server like a client. - Learn: [Describing Capabilities](https://frontmcp.dev/learn/describing-capabilities), [Structuring a Server](https://frontmcp.dev/learn/structuring-a-server) and [Running FrontMCP Anywhere](https://frontmcp.dev/learn/running-frontmcp-anywhere). --- # @FrontMcp > Declare an MCP server, the apps it hosts, and the settings that apply to all of them. Source: https://frontmcp.dev/reference/sdk/frontmcp [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@FrontMcp` declares the server: its name and version, the [apps](https://frontmcp.dev/reference/sdk/app) it hosts, and the settings that apply to all of them, from how it asks users for input to which port it listens on. A project has one, in its entry file, and importing that file starts the server. ```ts @FrontMcp(options) export default class Server {} ``` --- ## Reference ### `@FrontMcp(options)` Apply `@FrontMcp` to an empty class in your server's entry file. ```ts main.ts import "reflect-metadata"; import { FrontMcp, LogLevel } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], http: { port: 3000 }, logging: { level: LogLevel.Info }, }) export default class Server {} ``` [See more examples below.](https://frontmcp.dev/reference/sdk/frontmcp#usage) #### Options Required: | Option | Type | Description | | --- | --- | --- | | `info` | `ServerInfoOptions` | Who the server is. Sent to clients in the `_meta` of its responses. See [`info`](https://frontmcp.dev/reference/sdk/frontmcp#info). | | `apps` | `AppType[]` | The apps to serve: `@App` classes, `app()` results, [`App.remote()` and `App.esm()`](https://frontmcp.dev/reference/sdk/app#apps-from-outside-your-code). | Shared by every app: | Option | Type | Description | | --- | --- | --- | | `providers` | `ProviderType[]` | [Providers](https://frontmcp.dev/reference/sdk/provider) every app can get, as one shared instance. [`@Duty`](https://frontmcp.dev/reference/sdk/duty) and [`@Worker`](https://frontmcp.dev/reference/sdk/worker) classes are providers, and go here or in an app's `providers` (`@Worker` is new in 1.12.0). | | `plugins` | `PluginType[]` | Plugins that apply to every app, such as caching or auditing. See [`@Plugin`](https://frontmcp.dev/reference/sdk/plugin). | | `skills` | `SkillType[]` | Skills available to every app. | | `tools`, `resources` | `ToolType[]`, `ResourceType[]` | Tools and resources served with every app's, once. See [Tools every app shares](https://frontmcp.dev/reference/sdk/frontmcp#tools-every-app-shares). (Changed in 1.9.1: before, they were accepted and never registered.) | | `adapters` | `AdapterType[]` | Adapters, like an OpenAPI adapter, whose tools are served with every app's. See [Registering an adapter](https://frontmcp.dev/reference/plugins#registering-an-adapter). (Changed in 1.9: before, `@FrontMcp` dropped the option.) | How the server behaves toward clients. These all work in the Playground: | Option | Type | Description | | --- | --- | --- | | `instructions` | `string` | Tells the model how to use the server as a whole. Sent with `server/discover`, and in `initialize` to older clients, through every entry point. (Changed in 1.9.3: before, `initialize` through `createFetchHandler()` and `connect()` left them out.) See [giving the model instructions](https://frontmcp.dev/reference/sdk/frontmcp#giving-the-model-instructions). | | `instructionsBudget` | `false \| { instructions?: number; toolDescription?: number }` | Character limits for the `initialize` instructions and each tool's `description`, 1024 each by default. Over a limit, the server logs a warning at startup and `frontmcp build` reports it; nothing is cut. `false` turns the check off. New in 1.11.0. | | `clients` | `Record` | What one client receives, keyed by a glob of its `clientInfo.name`. Off by default. See [Client profiles](https://frontmcp.dev/reference/sdk/frontmcp#client-profiles). New in 1.11.0. | | `devtools` | `{ hookTrace?: boolean }` | `hookTrace` adds the hooks a call ran to its answer's `_meta["frontmcp/trace"]`. On by default only with `NODE_ENV=development`. See [Hook decorators](https://frontmcp.dev/reference/sdk/hooks#seeing-which-hooks-ran). New in 1.11.0. | | `elicitation` | `{ enabled?, redis?, store?, persistent? }` | Lets tools ask the user for input with `this.elicit()`. Off by default. Turning it on also adds a `sendElicitationResult` tool for clients on protocol versions before 2026-07-28 that can't show forms; 2026-07-28 clients never see it. `redis` stores pending questions for servers that run as several processes; it defaults to the top-level `redis`. `store: false` keeps pending questions in memory, and takes no `redis`. `persistent` turns on [persistent questions](https://frontmcp.dev/reference/sdk/elicit#persistent-questions), asked through an inbox. | | `pagination` | `{ tools?: { mode?, pageSize?, autoThreshold? } }` | How `tools/list` is split into pages. By default (`mode: "auto"`) it pages once there are more than `autoThreshold` tools, `pageSize` per page; both default to 40. `mode: true` always pages, `false` never does. The TypeScript type requires all three fields. | | `output` | `OutputPolicy` | Defaults for every tool's result: `schemaMode` (`"definition"`, the default, `"description"`, `"both"` or `"none"`), `schemaDescriptionFormat` (`"summary"` or `"jsonSchema"`) and `allowNonFinite` (default `false`: a `NaN` or `Infinity` in a result is an error). Also `budget`: `false` or `{ maxBytes, lists? }`, off by default, inherited by apps and tools. Also `undeclaredKeys`: `"strip"`, `"warn"`, `"keep"` or `"fail"` (default `"warn"` in development, `"strip"` otherwise). App and tool settings override these defaults, including `allowNonFinite`. See [Output policy](https://frontmcp.dev/reference/sdk/tool#output-policy). | | `throttle` | `GuardConfig` | Server-wide rate limits, concurrency caps and timeouts. `enabled` is required: `enabled: false` also turns off every tool's own `rateLimit` and `concurrency`. A tool's own limits work without `throttle`. See [Guard options](https://frontmcp.dev/reference/sdk/guard) and [setting defaults for every tool](https://frontmcp.dev/reference/sdk/frontmcp#setting-defaults-for-every-tool). | | `fetch` | `{ forwardCallerTokenTo?, forwardCustomHeadersTo?, requestTimeout?, autoInjectTracingHeaders? }` | How [`this.fetch()`](https://frontmcp.dev/reference/sdk/fetch#server-options) behaves: which origins get the caller's token and `x-frontmcp-*` headers (none by default), the timeout (30 seconds), and whether to send tracing headers. | | `authProvidersVault` | `{ providers?, enabled?, defaultCacheTtl?, maxCredentialsPerSession?, namespace?, useSharedStorage? }` | Credential providers for other services: each one's `factory` acquires a credential for the caller, which tools read with [`this.authProviders`](https://frontmcp.dev/reference/sdk/auth-providers) and `this.fetch()` sends with `credentials: { provider }`. Off by default. New in 1.11.1. | How the server is deployed. These configure a real process, so the Playground ignores them: | Option | Type | Description | | --- | --- | --- | | `serve` | `boolean` | Defaults to `true`: importing the decorated class starts the server. See [starting the server](https://frontmcp.dev/reference/sdk/frontmcp#starting-the-server). | | `http` | `HttpOptions` | Port, path, CORS and custom routes. See [`http`](https://frontmcp.dev/reference/sdk/frontmcp#http). | | `transport` | `TransportOptions` | Protocols, sessions and where sessions are stored. See [`transport`](https://frontmcp.dev/reference/sdk/frontmcp#transport). | | `session` | `{ sessionMode?, platformDetection? }` | Deprecated: the pre-1.0 option that `transport` replaced, and not read. A `sessionMode` other than `"stateful"` logs the same warning as [`transport.sessionMode`](https://frontmcp.dev/reference/sdk/frontmcp#transport), and a `platformDetection` logs ``session.platformDetection is ignored and will be removed in the next major, with the rest of `session`: move it to `transport.platformDetection`.`` (Changed in 1.9.4: before, it was dropped without a warning.) | | `auth` | `AuthOptions` | Who may connect. Defaults to public. See [`auth`](https://frontmcp.dev/reference/sdk/frontmcp#auth). | | `registry` | `McpRegistryOptionsInput` | Off by default. Serve a domain proof, server card and AI Catalog. See [`registry`](https://frontmcp.dev/reference/sdk/frontmcp#registry) and [MCP Registry](https://frontmcp.dev/reference/deployment/mcp-registry). | | `authorities` | `AuthoritiesConfig` | Named role and attribute rules, and where to find roles in a token, for the `authorities` option of tools, resources, templates, prompts, agents and skills. A server whose entries declare `authorities` doesn't start without it, and neither does one with a rule that checks nothing: see [Troubleshooting](https://frontmcp.dev/reference/sdk/frontmcp#authorities-configuration-required-or-invalid-authorities-rule). | | `splitByApp` | `boolean` | Serve each app on its own path, `/`, each with its own `auth`. Defaults to `false`. See [Apps, discovery and splitting](https://frontmcp.dev/reference/server/apps). | | `redis` | `RedisOptions` | Shared storage for sessions, tokens and pending questions: `{ host, port?, password?, db?, tls?, keyPrefix?, defaultTtlMs? }`, or `{ provider: "vercel-kv", url?, token? }`. Since 1.12.0 a Redis server here also holds the [leases](https://frontmcp.dev/reference/sdk/duty#scopes-and-leases) of [duties](https://frontmcp.dev/reference/sdk/duty) and [workers](https://frontmcp.dev/reference/sdk/worker), which Vercel KV doesn't: a server with a `scope: "cluster"` one and no Redis server here doesn't start. Events keep their subscriptions in `events.store`, not here. | | `pubsub` | `RedisOptions` | Redis for resource-subscription events, needed when `redis` is Vercel KV. Defaults to `redis`. | | `sqlite` | `{ path?, encryption?, walMode?, ttlCleanupIntervalMs? }` | Local storage for sessions, jobs, pending questions and events on a single machine, instead of Redis. | | `logging` | `{ level?, enableConsole?, prefix?, transports? }` | `level` is a `LogLevel`: `Debug`, `Verbose`, `Info` (the default), `Warn`, `Error` or `Off`. `transports` adds your own log destinations. See [Logging](https://frontmcp.dev/reference/server/logging). | | `health` | `HealthOptions` | Health endpoints, on by default: `/healthz` (also `/health`) and `/readyz`. `probes` adds your own checks, like a database ping. See [Health checks](https://frontmcp.dev/reference/server/observability#health). | | `metrics` | `MetricsOptions` | A `/metrics` endpoint in Prometheus or JSON format. Off by default. `auth: "token"` protects it with a token from `FRONTMCP_METRICS_TOKEN`. See [Metrics](https://frontmcp.dev/reference/server/observability#metrics). | | `observability` | `boolean` or `ObservabilityOptions` | OpenTelemetry tracing and structured logs. Needs `@frontmcp/observability` installed. See [Observability and telemetry](https://frontmcp.dev/reference/server/observability). | | `manifest` | `string \| ServerManifest` | The build manifest that lists [lazy apps](https://frontmcp.dev/reference/sdk/app#lazy-apps) until their first call: a path, or the manifest itself. Defaults to `frontmcp.manifest.json` next to the entry script. New in 1.11.0. | | `offload` | `{ maxWorkers?, idleTimeoutMs?, budgetMs?, env? }` | The Node worker-thread pool of [`this.offload()`](https://frontmcp.dev/reference/sdk/offload#frontmcp-offload-). No worker starts until one is needed. New in 1.11.0. | | `lifecycle` | `{ shutdownHookTimeoutMs?: number; exitWhenOrphaned?: boolean }` | Each provider `onShutdown()` gets 3000 ms by default ([provider lifecycle](https://frontmcp.dev/reference/sdk/provider#provider-lifecycle)). `exitWhenOrphaned` shuts the server down when its parent process exits or, over stdio, stdin ends: on by default for stdio, off for HTTP and Unix sockets. New in 1.11.0. | Other features: | Option | Type | Description | | --- | --- | --- | | `skillsConfig` | `SkillsConfigOptions` | Serve skills over HTTP (`/llm.txt`, `/skills`), and choose how the skill catalog joins `instructions` with `injectInstructions`: `"compact"` (the default), `"append"`, `"prepend"`, `"replace"` or `"off"`. The `resourceAnnotations` option controls the annotations on `SKILL.md` resources (default `"no-priority"`). See [`@Skill`](https://frontmcp.dev/reference/sdk/skill#server-options-skillsconfig). Its `audit` options keep a signed record of what skill scripts run: see [Audit log](https://frontmcp.dev/reference/plugins/skilled-openapi#audit-log). | | `extApps` | `ExtAppsOptions` | What MCP Apps widgets may do: call tools, log, open links, update the model's context. | | `tasks` | `TasksOptions` | Where background tasks are kept, for how long, and where they run. Tasks are on by default; a tool runs as one when it sets `execution.taskSupport`. See [Background tasks](https://frontmcp.dev/reference/server/tasks). | | `jobs` | `{ enabled, allowDynamicRegistration?, store?, defaultTimeoutMs?, admission?, runner? }` | The jobs and workflows system. On when an app declares jobs or workflows. Inherits top-level Redis (except Vercel KV) or SQLite, else memory; `store: false` forces memory. See [`@Job`](https://frontmcp.dev/reference/sdk/job#frontmcp-jobs-). | | `events` | `EventsConfigOptions` | [MCP Events](https://frontmcp.dev/reference/sdk/event): event types that clients list, subscribe to, poll or stream. On once an app declares an event in `@App({ events })`; `enabled: false` turns them off. The options set the delivery modes, the subscription store and limits, and the HTTP publish endpoint: see [`events`](https://frontmcp.dev/reference/sdk/frontmcp#events). New in 1.12.0. | | `channels` | `{ enabled, defaultMeta? }` | Push events to Claude Code sessions through channels. Off by default. Over HTTP, a client asks for them with `experimental: { "claude/channel": {} }` in its capabilities: in `initialize`, before 2026-07-28, or in a 2026-07-28 `subscriptions/listen` request, whose stream then carries the events (since 1.9.2; before, 2026-07-28 clients received none). The stdio session gets them without asking. See [`@Channel`](https://frontmcp.dev/reference/sdk/channel). An [event](https://frontmcp.dev/reference/sdk/event) with the `channel` option is sent to sessions without this option, never on a `subscriptions/listen` stream, and `enabled: false` turns that off too (new in 1.12.0). Changed in 1.12.0: before, the stdio session had to declare the capability too, and a stdio server with channels served MCP 2026-07-28. A server that pushes to Claude Code sessions now declines that revision over stdio, with [`-32022`](https://frontmcp.dev/reference/errors#protocol-errors). | | `loader` | `{ url?, registryUrl?, token?, tokenEnvVar? }` | Where `App.esm()` fetches packages. Defaults to the npm registry and esm.sh. See [the loader](https://frontmcp.dev/reference/server/esm#the-loader). | | `ui` | `{ cdnOverrides?, escapeStringResults?, servingMode? }` | Defaults for the tools' [UI widgets](https://frontmcp.dev/reference/ui): where they load their libraries from, whether a template's plain string is [escaped](https://frontmcp.dev/reference/ui#escaping-string-results), and the [serving mode](https://frontmcp.dev/reference/ui#serving-modes) of every tool that doesn't set one. An app's `@App({ ui: { servingMode } })` overrides it for that app's tools, and a tool's own `ui.servingMode` overrides both: see [Defaults for the server and an app](https://frontmcp.dev/reference/ui#defaults-for-the-server-and-an-app). (`servingMode` is new in 1.9.4.) | #### `info` | Field | Type | Description | | --- | --- | --- | | `name` | `string` | **Required.** The server's name, like `"help-desk"`. | | `version` | `string` | **Required.** The server's version, like `"1.0.0"`. | | `title` | `string` | A readable name for clients to display. | | `websiteUrl` | `string` | A URL for the server's documentation or home page. | | `icons` | `Icon[]` | Icons for clients to show. Each has a `src`, and optionally `mimeType`, `sizes` and `theme`. | `info` has no `description` field. One is silently dropped: use `instructions` to describe the server to the model. #### `http` ```ts main.ts @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], http: { port: 8080, entryPath: "/mcp", cors: { origin: ["https://desk.example.com"], credentials: true }, routes: [{ method: "GET", path: "/exports", handler: (req, res) => res.json({ format: req.query.format ?? "csv" }) }], }, }) export default class Server {} ``` | Field | Default | Description | | --- | --- | --- | | `port` | `PORT`, or `3000` | The TCP port to listen on. | | `entryPath` | `""` | The path of the MCP endpoint. With the default, clients connect to the root: `http://localhost:3000`. | | `cors` | none | CORS for browser clients: `{ origin, credentials?, maxAge? }`. Without it, MCP responses have no CORS headers, so browser pages on other origins can't read them. The [server card](https://frontmcp.dev/reference/deployment/mcp-registry#documents-served) sends its own CORS headers with origin `*`. `origin: true` allows any origin. | | `security` | loopback | `bindAddress`: `"loopback"` (the default, `127.0.0.1`), `"all"`, or an address. The `FRONTMCP_BIND_ADDRESS` environment variable does the same. `dnsRebindingProtection` checks `Host` and, on a loopback listener with derived protection, `Origin` headers. See [network settings](https://frontmcp.dev/reference/deployment/security#httpsecurity). `strict: true` turns on the hardening. | | `routes` | none | Extra HTTP handlers on the same port: `{ method, path, handler, auth? }`. With `auth: true`, a route requires the same credentials as the MCP endpoint. Paths used by FrontMCP, like `/health`, `/.well-known/*` and `/server-card`, are rejected at startup. `createFetchHandler()` serves these routes too. See [Serving HTTP routes next to MCP](https://frontmcp.dev/reference/sdk/frontmcp#serving-http-routes-next-to-mcp). | | `bodyLimit` | `"4mb"` | The largest JSON request body accepted, as a byte count or size string (`number \| string`). Applies to the fetch handler too, including limits above 4 MiB. A larger body gets HTTP `413`. `urlencodedLimit` does the same for form bodies on the Node host. See [body size limits](https://frontmcp.dev/reference/deployment/security#body-size-limits). | | `securityHeaders` | `nosniff` and `X-Frame-Options: DENY` | The security headers on every response: `{ hsts?, contentTypeOptions?, frameOptions?, custom?, csp? }`. `hsts`, `contentTypeOptions` and `frameOptions` take the header's value, or `false` to leave it out; `custom` adds headers as they are; `csp` is `{ enabled?, directives?, reportUri?, reportOnly? }`. Each option wins over its `FRONTMCP_*` variable ([Response headers](https://frontmcp.dev/reference/server/config-files#response-headers)). Since 1.8.7; before, FrontMCP sent neither default header and sent `X-Powered-By: Express`. | | `socketPath` | none | Listen on a Unix socket instead of a port, with owner-only `0600` permissions on POSIX. See [socket safety](https://frontmcp.dev/reference/deployment/node#serving-on-a-unix-socket). | | `forwardHeaders` | none beyond `x-frontmcp-*` | Header names or globs, like `"x-acme-*"`, matched without regard to case: the headers of an HTTP request that they match are kept in `this.context.metadata.customHeaders`, besides the `x-frontmcp-*` ones, and so are those in an in-process call's `metadata` (`create()`, `createDirect()`; changed in 1.11.1). One that matches a credential, hop-by-hop or client-address header (`authorization`, `cookie`, `host`, `x-forwarded-*`, …) stops startup. `this.fetch()` sends a kept header on only to the origins in `fetch.forwardCustomHeadersTo`. See [Reading a header of your own](https://frontmcp.dev/reference/sdk/context#reading-a-header-of-your-own). New in 1.11.0. | | `auth.people` | off | `"loopback-token"` or the [people sign-in options](https://frontmcp.dev/reference/sdk/http-route#people-sign-in), for app HTTP routes and persistent-question inboxes. | | `hostFactory` | Express | Your own HTTP server instead of Express: a `FrontMcpServer`, or a function that returns one. It then applies `cors`, `bodyLimit`, `securityHeaders` and the `Host` check itself. See [Using your own HTTP server](https://frontmcp.dev/reference/sdk/frontmcp#using-your-own-http-server). | #### `registry` `registry` serves discovery documents before a client connects. It defaults to off. The [MCP Registry reference](https://frontmcp.dev/reference/deployment/mcp-registry#frontmcp-registry-) lists each option's type and default and [tests the routes](https://frontmcp.dev/reference/deployment/mcp-registry#serving-the-proof-and-discovery-documents). ```ts registry: { name: "com.example/help-desk", description: "Search support tickets", // publicKey defaults to MCP_REGISTRY_PUBLIC_KEY, read on each proof request. } ``` The proof is always at `/.well-known/mcp-registry-auth`; the card follows `http.entryPath` at `/server-card`; the catalog is at `/.well-known/ai-catalog.json`. With `splitByApp`, or only standalone apps, only the proof is served. Set `FRONTMCP_PUBLIC_URL` behind a proxy so the card names the public endpoint. #### `transport` | Field | Default | Description | | --- | --- | --- | | `protocol` | `"legacy"` | Which HTTP transports clients may use, for protocol versions before 2026-07-28: `"legacy"` (Streamable HTTP and the old SSE transport), `"modern"` (Streamable HTTP with sessions), `"stateless-api"` (no sessions), `"full"` (everything), or an object of `sse`, `streamable`, `json`, `stateless`, `legacy` and `strictSession` flags. | | `defaultProtocolVersion` | `"legacy"` on the Node server and stdio, `"2026-07-28"` behind `createFetchHandler()` | How to serve a bare JSON-RPC request that names no protocol version. On stdio, applies until `initialize` makes the connection a session. See [Protocol versions](https://frontmcp.dev/reference/server/protocol-versions#transportdefaultprotocolversion). | | `persistence` | on when `redis` or `sqlite` is set | Store sessions so they survive restarts: `{ redis?, sqlite?, defaultTtlMs?, sessionCheckTimeoutMs? }`. `sessionCheckTimeoutMs` (500 by default, new in 1.9.4) is how long a request waits for the store to confirm its session before it's served from memory: see [High availability](https://frontmcp.dev/reference/deployment/high-availability). Without it, FrontMCP uses the top-level `redis`, or else `sqlite`, if one is set, and memory otherwise. `false` keeps sessions in memory. | | `distributedMode` | `false` | `true` or `"auto"` for servers that run as many instances behind a load balancer or as serverless functions. | | `providerCaching` | `true` | When `false`, `CONTEXT` providers are rebuilt on every request, even within a session: those registered on `@FrontMcp` and, since 1.9.2, on apps. | | `eventStore` | off | Let SSE clients resume missed messages after reconnecting: `{ enabled, provider?, maxEvents?, ttlMs?, redis? }`. | | `sessionMode` | `"stateful"` | Deprecated, not read, and removed in the next major: with `"stateless"`, older clients still get a session id and must send it. Sessions follow `protocol`: `"stateless-api"` serves without them. A value other than `"stateful"` logs a warning at startup: ``transport.sessionMode ('stateless') is ignored and will be removed in the next major: sessions follow `transport.protocol`. To serve without sessions, set `transport.protocol: 'stateless-api'` and remove `sessionMode`.`` (Since 1.9; the message changed in 1.9.4.) | | `platformDetection` | built-in | Rules for recognizing the client's platform from its client info. | Clients that speak MCP 2026-07-28 don't use sessions, so most of these only matter for older clients. A session id is encrypted with `MCP_SESSION_SECRET`. Since 1.8.6, a request whose id was minted under another secret gets `404` `invalid session id` (before 1.8.6, `session not initialized`), and the client starts over with `initialize`, so changing the secret ends every open session once. This was checked on a Node server, since the Playground has no sessions. #### Client profiles `clients` changes what one client receives, without changing tool code. Each key is a glob of the `clientInfo.name` the client sends (`*` any characters, `?` one), matched without regard to case, and the first key that matches wins. A client's name comes from the request's `_meta`, or from `initialize` for a client with a session. New in 1.11.0. ```ts clients: { "codex*": { structured: "text", annotations: "no-numbers" }, "claude-code": { structured: "only", instructions: "compact" }, } ``` | Field | Type | Default | Description | | --- | --- | --- | --- | | `structured` | `"both" \| "only" \| "text"` | `"both"` | How a `tools/call` answer carries its data. `"both"`: the JSON in the text and in `structuredContent`. `"only"`: `structuredContent`, with a one-line summary as the text, for a tool whose `outputSchema` `tools/list` lists; other tools answer as with `"both"`. `"text"`: the text only, and `tools/list` leaves `outputSchema` out for that client. | | `annotations` | `"full" \| "no-numbers"` | `skillsConfig.resourceAnnotations` | `"no-numbers"` leaves `priority` out of every resource's annotations in `resources/list`; `"full"` gives each skill's `SKILL.md` its `priority`. | | `instructions` | `"full" \| "compact"` | `skillsConfig.injectInstructions` | The skills part of the instructions: the catalog, or one line with the number of skills. | [Shaping answers for one client](https://frontmcp.dev/reference/sdk/frontmcp#shaping-answers-for-one-client) runs these. For custom transports, `composeCallerInstructions(scope, options?)` takes `options.clientName` to apply that client's `instructions`, and `McpHandlerOptions.composeInstructions(caller?, clientName?)` receives the name as its second argument. #### `auth` `auth` sets who may connect, and apps inherit it. An app's own `auth` doesn't change who may call its tools on the shared endpoint: see [Auth for one app](https://frontmcp.dev/reference/auth/modes#auth-for-one-app). [Auth modes](https://frontmcp.dev/reference/auth/modes) covers every mode and its options. | `mode` | Who may connect | | --- | --- | | `"public"` | Anyone. **The default.** Callers get anonymous identities. | | `"static"` | Callers that send one of the shared secrets in `tokens`, as `Authorization: Bearer …` by default. | | `"transparent"` | Callers with a valid token from your identity provider, `provider`. FrontMCP checks tokens but doesn't issue them. | | `"local"` | Callers who sign in through FrontMCP's own OAuth server. See [Local auth](https://frontmcp.dev/reference/auth/local). | | `"remote"` | Callers who sign in through an external OAuth provider, `provider`, with FrontMCP handling the flow. | In `local` and `remote` mode, only registered clients can sign in, since `requireRegisteredClients` defaults to `true`, and a client is granted only the scopes listed in `allowedScopes`. See [Local auth](https://frontmcp.dev/reference/auth/local). ```ts main.ts @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static", tokens: [process.env.DESK_API_KEY!] }, }) export default class Server {} ``` The Playground's client can't send credentials, so this runs in a project, not in the Playground. [Authenticating Clients](https://frontmcp.dev/learn/authenticating-clients) walks through each mode. #### `events` New in 1.12.0. Events need no option: an app that lists an [`@Event`](https://frontmcp.dev/reference/sdk/event) in `events` turns them on, and the server then performs every delivery mode it can. `events` changes that. Every field is optional, and [Events options](https://frontmcp.dev/reference/sdk/events-options) describes each one in full: | Option | Type | Default | Description | | --- | --- | --- | --- | | `enabled` | `boolean` | on when an app declares an event | `false` turns events off: `events/list` answers `-32601`, and publishing rejects with `EventsNotEnabledError`. | | `compat` | `"auto" \| "sep-3415" \| "sketch"` | `"auto"` | The dialect of [error codes](https://frontmcp.dev/reference/errors#events-errors) and webhook deliveries: SEP-3415, or the earlier design that ChatGPT implements. `"auto"` picks per caller. | | `poll` | `{ enabled?, nextPollMs?, maxEvents? }` | on, `30000`, `100` | `events/poll`: the wait between polls the server recommends, and the most occurrences one poll returns. | | `push` | `{ enabled?, heartbeatMs? }` | on, `25000` | `events/stream`. Not performed in a serverless deployment. | | `webhook` | `{ enabled?, allowedCallbacks?, verification?, delivery?, rotationGraceMs?, unsafeAllowLocalCallbacks? }` | on | `events/subscribe`, signed deliveries and their retries. Performed only when `auth` signs callers in: not in `public` mode. | | `buffer` | `{ maxAgeMs?, maxEvents? }` | `600000`, `10000` | How long, and how many, published occurrences of each event stay readable by poll and stream, in the memory of the process that published them. | | `subscriptions` | `{ defaultTtlMs?, maxTtlMs?, minTtlMs?, allowNoExpiry?, maxPerPrincipal?, reauthorizeEveryMs?, suspendedTtlMs? }` | 1 hour, 24 hours, 1 minute, `false`, `100`, 5 minutes, 7 days | Subscription lifetimes, how many one caller may hold, and how often a subscription's owner is checked again. | | `store` | `{ redis?, sqlite?, keyPrefix? }` | memory | Where webhook subscriptions and pending deliveries are kept: `redis` or `sqlite: { path }`, not both. A kept store needs [`MCP_EVENTS_SECRET`](https://frontmcp.dev/reference/server/environment#environment-variables). | | `publishEndpoint` | `{ enabled?, path?, secret?, authorities? }` | off, `/events/publish` | An HTTP endpoint another service publishes on. With `secret` (32 characters or more), requests are signed; without it, callers present the MCP endpoint's bearer credentials, and `authorities` restricts them. A `public` server needs `secret`. | | `bridge` | `boolean` | `true` | Also emits each published occurrence on the server's event bus, for workflows with `trigger: "event"` and `app-event` channels. | A value that can't work stops the server when it starts: `allowNoExpiry` without a kept store, `store` with both `redis` and `sqlite`, lifetimes that aren't in order, or a publish endpoint that can't tell who publishes. [The Events reference](https://frontmcp.dev/reference/sdk/event) describes each option's effect; [turning on events](https://frontmcp.dev/reference/sdk/frontmcp#turning-on-events) runs a few. #### Starting the server With the default `serve: true`, importing the class starts an HTTP server. With the environment variable `FRONTMCP_STDIO=1` (or `true`), it connects over stdio instead and opens no port, for clients that launch the server as a subprocess. To decide when the server starts, set `serve: false` and start it yourself: ```ts main.ts import "reflect-metadata"; import { FrontMcp, FrontMcpInstance } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; const options = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }; @FrontMcp({ ...options, serve: false }) export default class Server {} await connectToDatabase(); await FrontMcpInstance.bootstrap(options); ``` [`FrontMcpInstance`](https://frontmcp.dev/reference/sdk/frontmcp-instance) also has `runStdio(options)`, `createHandler(options)` for serverless platforms, and [`createFetchHandler(options)`](https://frontmcp.dev/reference/sdk/create-fetch-handler), which is what the Playground uses. To call a server in your own process, see [`create()` and `createDirect()`](https://frontmcp.dev/reference/sdk/create) and [`connect()`](https://frontmcp.dev/reference/sdk/connect). #### Caveats - Declare **one** `@FrontMcp` per server. The class body is ignored. - Options FrontMCP doesn't know are **dropped without an error**, including `info.description` and a top-level `prompts`. Check the spelling of anything that seems to have no effect. - The MCP endpoint is at the **root path** unless you set `http.entryPath`. - The Playground runs your options through `FrontMcpInstance.createFetchHandler()`, in your browser, with a minimal `AsyncContext` so that calls overlap as they do on Node (FrontMCP's browser build serves [one request at a time](https://frontmcp.dev/reference/sdk/create-fetch-handler#in-a-browser) without one). It opens no port, and listener options such as `http.port` and `http.socketPath` have no effect there. Custom `http.routes` are served. `auth` does apply, but the Playground's client never sends credentials: a mode that requires them (such as `static`) refuses every request, and one that allows anonymous callers treats the Playground as anonymous. See [Authenticating Clients](https://frontmcp.dev/learn/authenticating-clients). --- ## Usage ### Declaring a server `info` and `apps` are all a server needs. Clients receive `info` with every response: open the **Wire** tab and look at `_meta` in any response. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "help-desk", title: "Help Desk", version: "1.4.0", websiteUrl: "https://desk.example.com" }, apps: [HelpDeskApp], }) export default class Server {} ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-2", title: "Invoice total is wrong" }, ]; @Tool({ name: "search_tickets", description: "Search support tickets by title", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets] }) export class HelpDeskApp {} ``` ```ts info.test.ts import { test, expect } from "@frontmcp/testing"; test("clients see the server's info", async ({ mcp }) => { const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "server/discover" }); expect(response.result).toMatchObject({ _meta: { "io.modelcontextprotocol/serverInfo": { name: "help-desk", title: "Help Desk", version: "1.4.0", websiteUrl: "https://desk.example.com", }, }, }); }); ``` ### Tools every app shares `tools` and `resources` on `@FrontMcp` belong to no app: every app serves them, and they're listed once, with their own names. Use them for what isn't any app's, like a health check: Initial call configuration: ```js { tool: "ping", arguments: {} } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { BillingApp, HelpDeskApp } from "./apps"; import { Ping, ServerStatus } from "./shared"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp, BillingApp], tools: [Ping], resources: [ServerStatus], }) export default class Server {} ``` ```ts shared.ts import { Resource, ResourceContext, Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "ping", description: "Check that the server is up", inputSchema: {} }) export class Ping extends ToolContext { async execute() { return { ok: true }; } } @Resource({ name: "status", uri: "desk://status", mimeType: "application/json", description: "Whether every service is up" }) export class ServerStatus extends ResourceContext { async execute() { return { services: { tickets: "up", billing: "up" } }; } } ``` ```ts apps.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets", inputSchema: { query: z.string() } }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [{ id: "T-1", title: "Cannot log in" }].filter((t) => t.title.toLowerCase().includes(query)) }; } } @Tool({ name: "get_invoice", description: "Get an invoice", inputSchema: { id: z.string() } }) export class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, amount: "49 EUR" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets] }) export class HelpDeskApp {} @App({ id: "billing", name: "Billing", tools: [GetInvoice] }) export class BillingApp {} ``` ```ts shared.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcp, FrontMcpInstance, Tool, ToolContext } from "@frontmcp/sdk"; import { SearchTickets } from "./apps"; test("the server's tool and resource are listed once, next to the apps'", async ({ mcp }) => { expect((await mcp.tools.list()).map((t) => t.name).sort()).toEqual(["get_invoice", "ping", "search_tickets"]); expect((await mcp.resources.list()).map((r) => r.uri)).toEqual(["desk://status"]); expect((await mcp.tools.call("ping", {})).json()).toEqual({ ok: true }); }); test("a name an app's tool has too gets a prefix on both", async () => { @Tool({ name: "search_tickets", description: "Search every app's tickets", inputSchema: {} }) class SearchEverything extends ToolContext { async execute() { return { from: "server" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets] }) class HelpDesk {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], tools: [SearchEverything] }); try { expect((await server.listTools()).tools.map((t) => t.name).sort()).toEqual(["help-desk:search_tickets", "server:search_tickets"]); expect((await server.callTool("server:search_tickets", {})).structuredContent).toEqual({ from: "server" }); } finally { await server.dispose(); } }); ``` `@FrontMcp` has no `prompts`: put prompts in an app. Changed in 1.9.1: before, FrontMCP accepted `tools` and `resources` here but never registered them, so clients couldn't see or call them. ### Giving the model instructions Tool descriptions explain each tool. `instructions` explains the server: which tool to start with, how the tools fit together, what not to do. Clients read it from `server/discover` and usually add it to the model's context, so keep it short. ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], instructions: "Support ticket tools. Find tickets with search_tickets before acting on them. " + "Never close a ticket the customer hasn't confirmed is solved.", }) export default class Server {} ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by title", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [], query }; } } @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets, CloseTicket] }) export class HelpDeskApp {} ``` ```ts instructions.test.ts import { test, expect } from "@frontmcp/testing"; test("server/discover carries the instructions", async ({ mcp }) => { const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "server/discover" }); expect(response.result).toMatchObject({ instructions: expect.stringContaining("Find tickets with search_tickets") }); }); ``` ### Asking the user for input `this.elicit()` pauses a tool to ask the user a question, and it only works when the server turns elicitation on. The Call tab shows the form a client would show; answer it to finish the call. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], elicitation: { enabled: true }, }) export default class Server {} ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a ticket once the user confirms", inputSchema: { id: z.string() } }) class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const answer = await this.elicit(`Close ticket ${id}?`, z.object({ confirm: z.boolean() })); if (answer.status !== "accept" || !answer.content?.confirm) return { id, status: "open" }; return { id, status: "closed" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket] }) export class HelpDeskApp {} ``` ```ts elicit.test.ts import { test, expect } from "@frontmcp/testing"; test("the tool closes the ticket once the user confirms", async ({ mcp }) => { mcp.onElicitation(() => ({ action: "accept", content: { confirm: true } })); const result = await mcp.tools.call("close_ticket", { id: "T-1" }); expect(result.json()).toEqual({ id: "T-1", status: "closed" }); }); ``` Without `elicitation: { enabled: true }`, the same call fails. See [the troubleshooting entry](https://frontmcp.dev/reference/sdk/frontmcp#elicitation-is-disabled-in-server-configuration). ### Paging long tool lists Once a server has more than 40 tools, `tools/list` returns them 40 at a time, with a `nextCursor` for the next page. Change both numbers with `pagination`. Here the threshold is four tools, and there are five, so they come two per page: ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], pagination: { tools: { mode: "auto", autoThreshold: 4, pageSize: 2 } }, }) export default class Server {} ``` ```ts help-desk.app.ts import { App, tool } from "@frontmcp/sdk"; const names = ["search_tickets", "get_ticket", "create_ticket", "assign_ticket", "close_ticket"]; const tools = names.map((name) => tool({ name, description: name.replace("_", " "), inputSchema: {} })(async () => ({ ok: true })), ); @App({ id: "help-desk", name: "Help Desk", tools }) export class HelpDeskApp {} ``` ```ts pages.test.ts import { test, expect } from "@frontmcp/testing"; type Page = { tools: { name: string }[]; nextCursor?: string }; test("each page has two tools and a cursor to the next", async ({ mcp }) => { const page = async (cursor?: string) => (await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "tools/list", params: cursor ? { cursor } : {} })).result as Page; const first = await page(); expect(first.tools).toHaveLength(2); const second = await page(first.nextCursor); expect(second.tools).toHaveLength(2); const third = await page(second.nextCursor); expect(third.tools).toHaveLength(1); expect(third.nextCursor).toBeUndefined(); }); ``` A client reads every tool by following `nextCursor` until there isn't one. `mcp.tools.list()` does that for you since 1.8.6; before, it returned only the first page. A `DirectClient` from [`connect()`](https://frontmcp.dev/reference/sdk/connect) or `server.connect()` does it too: its list methods follow every page, `listResources()`, `listResourceTemplates()` and `listPrompts()` since 1.8.7. So does [`listTools()` on the server itself](https://frontmcp.dev/reference/sdk/create#listing-more-than-one-page-of-tools), since 1.9; before, it returned only the first page. This test sends the requests itself, to show each page. ### Setting defaults for every tool Some options set a default for every tool on the server. An app's own setting overrides the server's, and a tool's overrides both. ### Server-wide defaults ### Example: Output `output` controls how tool results are checked and described. With `allowNonFinite: true`, a `NaN` in a result becomes `null` instead of failing the call. Change it to `false` to see the error. Initial call configuration: ```js { tool: "average_reply_hours", arguments: {} } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "average_reply_hours", description: "Average hours to first reply this week", inputSchema: {} }) class AverageReplyHours extends ToolContext { async execute() { const replies: number[] = []; return { hours: replies.reduce((a, b) => a + b, 0) / replies.length }; // 0 / 0 is NaN } } @App({ id: "reports", name: "Reports", tools: [AverageReplyHours] }) class ReportsApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [ReportsApp], output: { allowNonFinite: true }, }) export default class Server {} ``` ### Example: Rate limit `throttle` sets limits for every tool. Here each tool may run twice a minute; the third call fails with a message that says when to retry. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by title", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [], query }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], throttle: { enabled: true, defaultRateLimit: { maxRequests: 2, windowMs: 60_000 } }, }) export default class Server {} ``` ```ts limits.test.ts import { test, expect } from "@frontmcp/testing"; test("the third call in a minute is refused", async ({ mcp }) => { await mcp.tools.call("search_tickets", { query: "a" }); await mcp.tools.call("search_tickets", { query: "b" }); const third = await mcp.tools.call("search_tickets", { query: "c" }); expect(third).toBeError(); expect(third.raw._meta?.code).toBe("RATE_LIMIT_EXCEEDED"); expect(third.text()).toContain("Rate limit exceeded"); }); ``` `throttle` also takes `global` (one limit shared by all requests), `defaultConcurrency` and `globalConcurrency` (`{ maxConcurrent }`), `defaultTimeout` (`{ executeMs }`), `ipFilter`, and `storage` to share counters between processes through Redis. A tool's own `rateLimit`, `concurrency` and `timeout` override the defaults. `ui.servingMode` sets a default the same way, for the [serving mode](https://frontmcp.dev/reference/ui#serving-modes) of every tool with a widget that doesn't set its own: `@FrontMcp({ ui: { servingMode: "static" } })`, overridden by `@App({ ui: { servingMode } })` for an app's tools, and by a tool's own `ui.servingMode`. New in 1.9.4. [Defaults for the server and an app](https://frontmcp.dev/reference/ui#defaults-for-the-server-and-an-app) shows it. ### Shaping answers for one client Some clients read only the text of an answer, and some read only `structuredContent`. `clients` sends each what it reads. Here Codex gets the text alone, Claude Code gets the data with a one-line summary, and every other client, the Playground's included, gets both: Initial call configuration: ```js { tool: "count_tickets", arguments: {} } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "count_tickets", description: "Count open and closed tickets", inputSchema: {}, outputSchema: { open: z.number(), closed: z.number() }, }) class CountTickets extends ToolContext { async execute() { return { open: 3, closed: 40 }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CountTickets] }) class HelpDeskApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], clients: { "codex*": { structured: "text" }, "claude-code": { structured: "only" }, }, }) export default class Server {} ``` ```ts clients.test.ts import { test, expect } from "@frontmcp/testing"; async function requestAs(mcp: any, client: string, method: string, params: object = {}) { const body = await mcp.raw.request({ method, params: { ...params, _meta: { "io.modelcontextprotocol/clientInfo": { name: client, version: "1.0.0" } } }, }); return body.result; } const callAs = (mcp: any, client: string) => requestAs(mcp, client, "tools/call", { name: "count_tickets", arguments: {} }); test("a client no profile matches gets the text and the data", async ({ mcp }) => { const result = await callAs(mcp, "my-mcp-client"); expect(result.structuredContent).toEqual({ open: 3, closed: 40 }); expect(JSON.parse(result.content[0].text)).toEqual({ open: 3, closed: 40 }); }); test("`codex*` matches Codex, which gets the text alone", async ({ mcp }) => { const result = await callAs(mcp, "Codex-MCP-Client"); expect(result.structuredContent).toBeUndefined(); expect(JSON.parse(result.content[0].text)).toEqual({ open: 3, closed: 40 }); }); test("Codex isn't listed the output schema", async ({ mcp }) => { const [asCodex] = (await requestAs(mcp, "codex-mcp-client", "tools/list")).tools; const [asOther] = (await requestAs(mcp, "my-mcp-client", "tools/list")).tools; expect(asCodex.outputSchema).toBeUndefined(); expect(asOther.outputSchema).toMatchObject({ type: "object" }); }); test("Claude Code gets the data, and a summary as the text", async ({ mcp }) => { const result = await callAs(mcp, "claude-code"); expect(result.structuredContent).toEqual({ open: 3, closed: 40 }); expect(result.content[0].text).toBe("The answer is in structuredContent: open: 3, closed: 40."); }); ``` A tool whose `outputSchema` isn't listed answers a `"only"` client as it does any other: without the schema, the client couldn't read the data alone. ### Turning on events New in 1.12.0. The server below sets three [`events`](https://frontmcp.dev/reference/sdk/frontmcp#events) options, and its app declares one event. That's enough for clients to list it, poll it and hold a stream on it; with `auth` in a mode that signs callers in, they could subscribe by webhook too. The tests start the same configuration with other `events` options: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, event, z } from "@frontmcp/sdk"; export const ticketClosed = event({ name: "ticket.closed", description: "A ticket was closed", payloadSchema: { id: z.string() }, }); @Tool({ name: "close_ticket", description: "Close a ticket", inputSchema: { id: z.string() } }) class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const { eventId } = await this.events.publish(ticketClosed, { id }); return { id, status: "closed", eventId }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], events: [ticketClosed] }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], events: { poll: { nextPollMs: 5_000, maxEvents: 20 }, buffer: { maxAgeMs: 60_000 } }, }; @FrontMcp(config) export default class Server {} ``` ```ts events-options.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; async function listEvents(events: object) { const handler = await FrontMcpInstance.createFetchHandler({ ...config, events }); const meta = { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": { name: "test", version: "1.0.0" }, "io.modelcontextprotocol/clientCapabilities": {} }; const response = await handler( new Request("http://localhost/", { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2026-07-28", "Mcp-Method": "events/list" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "events/list", params: { _meta: meta } }), }), ); return response.json(); } test("declaring an event turns events on, by poll and push on a public server", async ({ mcp }) => { const listed = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "events/list", params: {} }); expect(listed.result.events).toMatchObject([{ name: "ticket.closed", delivery: ["poll", "push"] }]); }); test("push.enabled: false leaves poll", async () => { const listed = await listEvents({ push: { enabled: false } }); expect(listed.result.events[0].delivery).toEqual(["poll"]); }); test("enabled: false turns events off", async () => { const listed = await listEvents({ enabled: false }); expect(listed.error).toMatchObject({ code: -32601, message: "Method not found: events/list" }); }); test("an option that can't work stops the server", async () => { await expect(listEvents({ subscriptions: { allowNoExpiry: true } })).rejects.toThrow("events.subscriptions.allowNoExpiry needs events.store.redis or events.store.sqlite"); await expect(listEvents({ publishEndpoint: { enabled: true } })).rejects.toMatchObject({ code: "EVENT_PUBLISH_ENDPOINT" }); }); ``` `poll.nextPollMs` is what each `events/poll` answer recommends as the wait before the next one, and `buffer.maxAgeMs` how long a published occurrence can still be read. [`@Event`](https://frontmcp.dev/reference/sdk/event) covers declaring, publishing and delivering events. ### Serving HTTP routes next to MCP Not everything a help desk serves is MCP. A spreadsheet wants a CSV export, and the billing system calls a webhook when an invoice is paid. `http.routes` adds plain HTTP endpoints on the MCP endpoint's port, so they don't need a second server: ```ts main.ts import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; import { markPaid, ticketsCsv } from "./store"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "static", tokens: [process.env.DESK_API_KEY!] }, http: { routes: [ { method: "GET", path: "/exports/:status", auth: true, // the same credentials as the MCP endpoint handler: (req, res) => { res.setHeader("Content-Type", "text/csv"); res.send(ticketsCsv(req.params?.status ?? "open")); }, }, { method: "POST", path: "/webhooks/billing", handler: (req, res) => { markPaid(req.body.invoice); res.status(202).json({ received: req.body.invoice }); }, }, ], }, }) export default class Server {} ``` A handler is Express-style, `(req, res, next)`. `req.params` holds the path's `:status`, `req.query` the query string, `req.headers` the headers, and `req.body` a JSON or form body, already parsed. `req.bodyBytes` is the body as it arrived, a `Uint8Array`, for a signature or a digest over the exact bytes ([below](https://frontmcp.dev/reference/sdk/frontmcp#checking-a-webhooks-signature); new in 1.11.1). `res` has `status()`, `json()`, `send()` and `setHeader()`. This server answers: | Request | Answer | | --- | --- | | `GET /exports/open` with no `Authorization` header | `401` `{"error":"Unauthorized"}`, with `WWW-Authenticate: Bearer realm="mcp"` | | `GET /exports/open` with a key that isn't in `tokens` | `401`, with `WWW-Authenticate: Bearer realm="mcp", error="invalid_token", error_description="The access token is invalid"` | | `GET /exports/open` with `Authorization: Bearer` and the key | `200`, the CSV, as `text/csv; charset=utf-8` | | `POST /webhooks/billing` with no credentials | `202` `{"received":"INV-7"}`. A route without `auth: true` is open to anyone, whatever the server's `auth`, so check that the request comes from billing in the handler. | `auth: true` runs the check the MCP endpoint runs, before the handler: - Without valid credentials, the route answers `401` with the challenge the MCP endpoint sends. With an identity provider (`transparent` mode), it points at the resource metadata: `Bearer resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource"`. - A valid token that lacks one of `auth.requiredScopes` gets `403` `{"error":"Forbidden"}`, with `error="insufficient_scope"` and the scopes it needs in the challenge. - Otherwise the handler runs, and `req.authSession` says who called: `user` holds the token's claims (`sub`, `scope`, and for a JWT the rest of them), and `token` the token itself. A static key's `user.sub` is `static:` and a hash of the key. - A server that lets anonymous callers in lets them into these routes too. In `public` mode, the default, and with `allowAnonymous`, a request without a token runs the handler as a new anonymous caller each time, whose `req.authSession.user.sub` starts with `anon:`. If a route needs a real caller, refuse those in the handler. `throttle.ipFilter` applies to every route, before `auth`: a refused address gets `403` `{"error":"forbidden","message":"Client IP rejected by ipFilter"}`. **The content type.** FrontMCP's Express server sets `Content-Type: application/json; charset=utf-8` on every response before a handler runs. That suits `res.json()`, but a CSV string sent with `res.send()` goes out labelled as JSON. Set the type first, as the export does. **Reserved paths.** A route can't take a path FrontMCP serves itself: - the MCP endpoint and the `/sse` and `/message` paths next to it: `/`, `/sse` and `/message` by default, or `/mcp`, `/mcp/sse` and `/mcp/message` with `entryPath: "/mcp"`; - `/server-card`, whether or not `registry` is set. Changed in 1.10.0: before, a custom route could use this path; - `/health` and `/metrics`; - anything under `/oauth/` or `/.well-known/`. Such a route stops the server from starting: see [the troubleshooting entry](https://frontmcp.dev/reference/sdk/frontmcp#custom-httproute--collides-with-the-reserved-frontmcp-path). Health probe paths (`/healthz` and `/readyz`, or the paths set by `health.healthzPath` and `health.readyzPath`) are reserved while health is enabled. Changed in 1.9.5: before, a custom route could replace a health probe. **Where routes are served.** FrontMCP's Node server serves them, whether you start it by importing the class or with `bootstrap()`, and so does [`createHandler()`](https://frontmcp.dev/reference/sdk/frontmcp-instance#frontmcpinstancecreatehandlerconfig). [`createFetchHandler()`](https://frontmcp.dev/reference/sdk/create-fetch-handler) serves them too, including channel webhooks, behind the same IP filtering and session verification. Changed in 1.9.5: before, fetch-handler routes answered `404`. **Large files.** A tool's result, like a resource's contents, travels inside one JSON-RPC response. For an export of many megabytes, serve the file from a route and have the tool return a `resource_link` to it: the result carries only the link, and the file goes out on a request of its own when someone follows it. With `auth: true` on the route, that request needs the same credentials as the MCP endpoint. Initial call configuration: ```js { tool: "export_tickets", arguments: { status: "open" } } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z, type ServerRequest, type ServerResponse } from "@frontmcp/sdk"; import { ticketsCsv } from "./store"; const PUBLIC_URL = "https://desk.example.com"; // where clients reach this server @Tool({ name: "export_tickets", description: "Export the tickets with a status as a CSV file, and return a link to it", inputSchema: { status: z.enum(["open", "closed"]) }, outputSchema: "resource_link", }) class ExportTickets extends ToolContext { async execute({ status }: { status: "open" | "closed" }) { return { type: "resource_link" as const, uri: `${PUBLIC_URL}/exports/${status}`, name: `${status}-tickets.csv`, mimeType: "text/csv" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ExportTickets] }) class HelpDeskApp {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], http: { routes: [ { method: "GET" as const, path: "/exports/:status", handler: (req: ServerRequest, res: ServerResponse) => { res.setHeader("Content-Type", "text/csv"); res.send(ticketsCsv(req.params?.status ?? "open")); }, }, ], }, }; @FrontMcp(config) export default class Server {} ``` ```ts store.ts const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Export times out", status: "open" }, ]; // A real export would stream thousands of rows from the database export function ticketsCsv(status: string) { const rows = tickets.filter((t) => t.status === status).map((t) => `${t.id},${t.title}`); return ["id,title", ...rows].join("\n") + "\n"; } ``` ```ts export.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; test("the result is a link to the file, not the file", async ({ mcp }) => { const result = await mcp.tools.call("export_tickets", { status: "open" }); expect(result).toBeSuccessful(); expect(result.raw.content).toEqual([ { type: "resource_link", uri: "https://desk.example.com/exports/open", name: "open-tickets.csv", mimeType: "text/csv" }, ]); }); test("createFetchHandler() serves the export route", async () => { const handler = await FrontMcpInstance.createFetchHandler(config); const response = await handler(new Request("https://desk.example.com/exports/open")); expect(response.status).toBe(200); expect(await response.text()).toContain("id,title"); }); ``` On a Node server, following the link returns the two open tickets as `text/csv`. #### Checking a webhook's signature A service that calls a webhook usually signs the body, and the signature is over the bytes it sent. `JSON.stringify(req.body)` can differ from them, in spacing or key order, so check `req.bodyBytes`: ```ts billing-webhook.ts active import type { HttpRouteConfig } from "@frontmcp/sdk"; const SECRET = new TextEncoder().encode("whsec_test_7f3a"); // in a project, read it from the environment export async function signatureOf(body: Uint8Array): Promise { const key = await crypto.subtle.importKey("raw", SECRET, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new Uint8Array(body))); return Array.from(mac, (byte) => byte.toString(16).padStart(2, "0")).join(""); } export const billingWebhook: HttpRouteConfig = { method: "POST", path: "/webhooks/billing", handler: async (req, res) => { const signed = req.bodyBytes !== undefined && req.headers["x-signature"] === (await signatureOf(req.bodyBytes)); if (!signed) { res.status(401).json({ error: "bad signature" }); return; } res.status(202).json({ received: req.body.invoice }); }, }; ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { billingWebhook } from "./billing-webhook"; @App({ id: "billing", name: "Billing" }) class Billing {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [Billing], http: { routes: [billingWebhook] } }; @FrontMcp(config) export default class Server {} ``` ```ts webhook.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { signatureOf } from "./billing-webhook"; import { config } from "./main"; const body = '{ "invoice": "INV-7" }'; async function post(text: string, signature: string, contentType = "application/json") { const handler = await FrontMcpInstance.createFetchHandler(config); return handler( new Request("http://localhost/webhooks/billing", { method: "POST", headers: { "content-type": contentType, "x-signature": signature }, body: text }), ); } test("a body signed as it was sent is accepted", async () => { const response = await post(body, await signatureOf(new TextEncoder().encode(body))); expect(response.status).toBe(202); expect(await response.json()).toEqual({ received: "INV-7" }); }); test("the parsed body, serialized again, isn't what was signed", async () => { const reserialized = new TextEncoder().encode(JSON.stringify({ invoice: "INV-7" })); expect((await post(body, await signatureOf(reserialized))).status).toBe(401); }); test("createFetchHandler() keeps the bytes of a body that isn't JSON too", async () => { const signature = await signatureOf(new TextEncoder().encode(body)); expect((await post(body, signature, "text/plain")).status).toBe(202); }); ``` FrontMCP's Node server fills in `bodyBytes` for JSON and form bodies, and `createFetchHandler()` for any body. ### Using your own HTTP server `HostServerAdapter` is exported as a value and `Scope` as a type from `@frontmcp/sdk`. Custom hosts implement `FrontMcpServer`. Changed in 1.9.5: `enhancedHandler()` is removed from that contract; hosts no longer need to implement it. FrontMCP's Node server is built on Express. `http.hostFactory` replaces Express with a server of your own: a `FrontMcpServer` subclass, or a function that returns one. FrontMCP still decides what to serve, the MCP endpoint, discovery documents, OAuth, health checks and your routes, and registers each with your server. Your server decides how requests reach them. To add MCP to a Node server you already run, you don't need one: [`createHandler()`](https://frontmcp.dev/reference/sdk/frontmcp-instance#frontmcpinstancecreatehandlerconfig) returns FrontMCP's Express app as a `(req, res)` handler, to call with the requests MCP should answer. FrontMCP calls these methods, in this order: | Method | Called | | --- | --- | | `registerMiddleware(path, handler)` | Once for each of FrontMCP's endpoints, while the server starts: the MCP endpoint with `"/"`, discovery documents with `""`, and OAuth with paths like `"/oauth/token"` and `"/oauth/provider/:providerId/callback"`. Run `handler` for every request at or under `path`, in the order they were registered. A handler that doesn't serve the request calls `next()`. | | `registerRoute(method, path, handler)` | For each of `http.routes`, then for FrontMCP's health checks, `/healthz`, `/health` and `/readyz`. Run `handler` for that method and path. `:name` parts of the path go in `req.params`. | | `prepare()` | Once everything is registered. | | `start(portOrSocketPath, bindAddress)` | When the server starts: with `http.socketPath` if it's set, else `http.port`, and the bind address `http.security` resolves to, `"127.0.0.1"` by default. | | `getHandler()` | By `createHandler()`, instead of `start()`. `createHandler()` returns what it returns. | | `stop()` | On `SIGTERM` or `SIGINT`. The base class's does nothing. | The handlers expect Express's request and response, so a host gives them what they use. On the request: `path`, `query`, `params`, `headers`, and `body`, parsed from JSON or a form. On the response: `status()`, which returns the response, `json()`, `send()` and `redirect()`, besides Node's own `setHeader()`, `writeHead()`, `write()` and `end()`, which streamed answers use. This host does it with `node:http` alone: ```ts node-host.ts import http from "node:http"; import { FrontMcpServer, type HttpMethod, type ServerRequest, type ServerRequestHandler, type ServerResponse } from "@frontmcp/sdk"; type Layer = { method?: HttpMethod; path: string; prefix: boolean; handler: ServerRequestHandler }; export class NodeHost extends FrontMcpServer { private layers: Layer[] = []; private server?: http.Server; registerMiddleware(path: string, handler: ServerRequestHandler) { this.layers.push({ path, prefix: true, handler }); } registerRoute(method: HttpMethod, path: string, handler: ServerRequestHandler) { this.layers.push({ method, path, prefix: false, handler }); } prepare() {} getHandler() { return (req: http.IncomingMessage, res: http.ServerResponse) => this.handle(req, res).catch(() => { if (!res.headersSent) res.writeHead(500).end(); }); } async start(portOrSocketPath?: number | string, bindAddress?: string) { this.server = http.createServer(this.getHandler()); await new Promise((resolve) => { if (typeof portOrSocketPath === "string") this.server!.listen(portOrSocketPath, resolve); else this.server!.listen(portOrSocketPath, bindAddress, resolve); }); } override async stop() { await new Promise((resolve) => this.server?.close(resolve)); } private async handle(req: http.IncomingMessage, res: http.ServerResponse) { const url = new URL(req.url ?? "/", "http://localhost"); let body: unknown; try { body = await readBody(req); } catch { return void res.writeHead(400).end(); // not JSON } // What FrontMCP's handlers read and call, as on Express const request = Object.assign(req, { path: url.pathname, query: Object.fromEntries(url.searchParams), body }); const response = Object.assign(res, { status: (code: number) => { res.statusCode = code; return res; }, json: (payload: unknown) => { if (!res.hasHeader("content-type")) res.setHeader("content-type", "application/json; charset=utf-8"); res.end(JSON.stringify(payload)); }, send: (payload: unknown) => res.end(typeof payload === "string" || payload instanceof Uint8Array ? payload : JSON.stringify(payload)), redirect: (status: number | string, location?: string) => { res.writeHead(typeof status === "number" ? status : 302, { location: typeof status === "number" ? location : status }).end(); }, }); // Offer the request to each handler in the order FrontMCP registered them, until one answers const layers = this.layers.filter((layer) => !layer.method || layer.method === req.method); const next = async (i: number): Promise => { if (i === layers.length) return void res.writeHead(404).end(); const params = matchPath(layers[i], url.pathname); if (!params) return next(i + 1); Object.assign(request, { params }); await layers[i].handler(request as unknown as ServerRequest, response as unknown as ServerResponse, () => next(i + 1)); }; await next(0); } } // "/exports/:status" matches "/exports/open" with { status: "open" }; a middleware's path also matches what's below it function matchPath(layer: Layer, pathname: string): Record | undefined { const want = layer.path.split("/").filter(Boolean); const got = pathname.split("/").filter(Boolean); if (layer.prefix ? got.length < want.length : got.length !== want.length) return undefined; const params: Record = {}; for (const [i, part] of want.entries()) { if (part.startsWith(":")) params[part.slice(1)] = decodeURIComponent(got[i]); else if (part !== got[i]) return undefined; } return params; } async function readBody(req: http.IncomingMessage) { const type = req.headers["content-type"] ?? ""; const form = type.includes("application/x-www-form-urlencoded"); if (!form && !type.includes("application/json")) return undefined; const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk as Buffer); const text = Buffer.concat(chunks).toString("utf8"); if (!text) return undefined; return form ? Object.fromEntries(new URLSearchParams(text)) : JSON.parse(text); } ``` ```ts main.ts import "reflect-metadata"; import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; import { NodeHost } from "./node-host"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], http: { port: 3000, hostFactory: () => new NodeHost() }, }) export default class Server {} ``` On a Node server, this host served `server/discover` and `tools/call` to a 2026-07-28 client, an `initialize` session and a streamed `tools/call` to a 2025-06-18 client, `/healthz`, `/readyz`, the resource metadata document, and an `http.routes` route with `auth: true`. The Playground runs no HTTP server, so it never calls a host. Some of what the Express server does, a host of your own has to do itself: `cors`, `bodyLimit`, `securityHeaders` with its `nosniff` and `X-Frame-Options` defaults, the `Host` check of `security.dnsRebindingProtection`, and the JSON `Content-Type` default. With this host, a request from an origin listed in `cors` gets no CORS headers. The function form of `hostFactory` is called once, with the `http` options except `hostFactory`, defaults filled in (`port`, `entryPath`, `bodyLimit`), so your server can read them. An instance, `hostFactory: new NodeHost()`, works the same way, without them. `FrontMcpServer`, `HttpMethod`, `ServerRequestHandler`, `ServerRequest` and `ServerResponse` come from `@frontmcp/sdk`. FrontMCP's Express host class isn't exported, so a host extends `FrontMcpServer` directly. --- ## Troubleshooting ### `@FrontMcp invalid metadata for "apps"` The full message goes on: `apps items must be annotated with @App() | @FrontMcpApp() or be a valid remote app configuration.` An entry in `apps` is a class without `@App`. Often it's a tool or a provider listed directly on the server: ```ts // 🚩 A tool is not an app @FrontMcp({ info, apps: [SearchTickets] }) // ✅ Put the tool in an app, and the app on the server @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets] }) class HelpDeskApp {} @FrontMcp({ info, apps: [HelpDeskApp] }) ``` ### `Invalid option: expected one of 0|1|2|3|4|100` The error's `path` is `logging.level`. The level is a `LogLevel` enum value, not a string: ```ts // 🚩 A string logging: { level: "info" } // ✅ The enum import { LogLevel } from "@frontmcp/sdk"; logging: { level: LogLevel.Info } ``` ### `Elicitation is disabled in server configuration` A tool called `this.elicit()`, but the server doesn't have elicitation turned on, so the call failed with this message: Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a ticket once the user confirms", inputSchema: { id: z.string() } }) class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const answer = await this.elicit(`Close ticket ${id}?`, z.object({ confirm: z.boolean() })); return { id, status: answer.content?.confirm ? "closed" : "open" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket] }) class HelpDeskApp {} // 🚩 No `elicitation: { enabled: true }` @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class Server {} ``` Add `elicitation: { enabled: true }` to `@FrontMcp`. If the server runs as several processes, also give it a `redis`, so an answer can reach whichever process asked. ### `Authorities configuration required`, or `Invalid authorities rule` The server didn't start, for one of three reasons: - An entry declares `authorities`, a tool, resource, template, prompt, agent, a tool inside an agent, or a skill, and `@FrontMcp` has no `authorities` option to check it with. - A rule checks nothing: `{}`, an empty list, an unknown field like `role:`, or a profile name inside `anyOf`. The message names the entry. Such a rule used to let every caller in; since FrontMCP 1.8.3 the server refuses it instead. - A rule names a profile the `authorities` option doesn't define, like a typo: `Invalid authorities rule: Tool "close_ticket": authorities names an unknown profile "lead"`. Changed in 1.8.4: before, such a server started and then refused every caller. ```ts startup.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { ArchiveApp, HelpDeskApp } from "./apps"; import { authorities } from "./main"; const info = { name: "help-desk", version: "1.0.0" }; test("an entry with authorities, and no authorities option", async () => { await expect(FrontMcpInstance.createDirect({ info, apps: [HelpDeskApp] })).rejects.toThrow('Authorities configuration required: Tool "close_ticket"'); }); test("a rule that checks nothing", async () => { await expect(FrontMcpInstance.createDirect({ info, apps: [HelpDeskApp, ArchiveApp], authorities })).rejects.toThrow( 'Invalid authorities rule: Tool "reopen_ticket": authorities checks nothing', ); }); test("a profile name the option doesn't define", async () => { const typo = { profiles: { leads: { roles: { any: ["lead"] } } } }; await expect(FrontMcpInstance.createDirect({ info, apps: [HelpDeskApp], authorities: typo })).rejects.toThrow( 'Invalid authorities rule: Tool "close_ticket": authorities names an unknown profile "lead"', ); }); test("with the option, and a rule that checks a role, the server starts", async ({ mcp }) => { expect(await mcp.tools.call("close_ticket", { id: "T-1" })).toBeError("AUTHORITY_DENIED"); }); ``` ```ts apps.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a ticket", inputSchema: { id: z.string() }, authorities: "lead" }) class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, closed: true }; } } // 🚩 checks nothing @Tool({ name: "reopen_ticket", description: "Reopen a ticket", inputSchema: { id: z.string() }, authorities: {} }) class ReopenTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, reopened: true }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket] }) export class HelpDeskApp {} @App({ id: "archive", name: "Archive", tools: [ReopenTicket] }) export class ArchiveApp {} ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./apps"; export const authorities = { profiles: { lead: { roles: { any: ["lead"] } } } }; // ✅ The option is set, and the app's rule checks a role @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], authorities }) export default class Server {} ``` Add the `authorities` option, and fix the rule. To leave an entry open to everyone, remove its `authorities`. ### `Custom http.route … collides with the reserved FrontMCP path` The server didn't start, because a route in `http.routes` takes a path FrontMCP serves itself. The full message names both paths and the rule: `Custom http.route "GET /health" collides with the reserved FrontMCP path "/health". Reserved prefixes are the MCP entry path (and its /sse, /message and /server-card siblings), /oauth/*, /.well-known/*, /health, /metrics, and the health probe paths (/healthz, /readyz unless health.healthzPath / health.readyzPath move them). Choose a different path.` Changed in 1.10.0: before, a custom route could use `/server-card`. It is now reserved, even without `registry` configured. ```ts startup.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance, type ServerRequestHandler } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; const info = { name: "help-desk", version: "1.0.0" }; const ok: ServerRequestHandler = (_req, res) => res.json({ ok: true }); const serve = (path: string, entryPath = "") => FrontMcpInstance.createFetchHandler({ info, apps: [HelpDeskApp], http: { entryPath, routes: [{ method: "GET", path, handler: ok }] } }); test("a route on /health", async () => { await expect(serve("/health")).rejects.toThrow('Custom http.route "GET /health" collides with the reserved FrontMCP path "/health".'); }); test("a route under /.well-known", async () => { await expect(serve("/.well-known/desk.json")).rejects.toThrow('collides with the reserved FrontMCP path "/.well-known"'); }); test("the server card's path is reserved without registry configured", async () => { await expect(serve("/mcp/server-card", "/mcp")).rejects.toThrow('collides with the reserved FrontMCP path "/mcp/server-card"'); }); test("with entryPath /mcp, /mcp/sse is taken and / is free", async () => { await expect(serve("/mcp/sse", "/mcp")).rejects.toThrow('collides with the reserved FrontMCP path "/mcp/sse"'); await expect(serve("/", "/mcp")).resolves.toBeDefined(); }); test("/healthz is reserved while health is enabled", async () => { await expect(serve("/healthz")).rejects.toThrow('collides with the reserved FrontMCP path "/healthz"'); }); ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], // ✅ A path of its own, not /health http: { routes: [{ method: "GET", path: "/status/queue", handler: (_req, res) => res.json({ waiting: 4 }) }] }, }) export default class Server {} ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search_tickets", description: "Search support tickets by title", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [], query }; } } @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets] }) export class HelpDeskApp {} ``` Move the route to a path of its own. To add a check to FrontMCP's health endpoints, use `health.probes` instead: see [Health checks](https://frontmcp.dev/reference/server/observability#health). ### My client gets `404` or `Cannot POST /mcp` The client is using a different path from the server. The MCP endpoint is at the root, `http://localhost:3000`, unless `http.entryPath` says otherwise. Either point the client at the root, or set `http: { entryPath: "/mcp" }`. If apps are `standalone` or the server uses `splitByApp`, each app has its own path under the entry path, like `/mcp/billing`. ### A route answers `404` `{"error":"Not Found","entryPaths":["/"]}` No MCP flow or custom route matched the request. Check the method and path in `http.routes`, and whether the handler calls `next()` without answering. Changed in 1.9.5: `createFetchHandler()` serves custom routes and channel webhooks; before, it returned this `404` for them: see [Serving HTTP routes next to MCP](https://frontmcp.dev/reference/sdk/frontmcp#serving-http-routes-next-to-mcp). ### A web page can't read the server's responses Browsers block cross-origin reads unless the server sends CORS headers, and since FrontMCP 1.7 MCP responses have none by default. The [server card](https://frontmcp.dev/reference/deployment/mcp-registry#documents-served) sends its own CORS headers with origin `*`. The request still reaches the server; the browser hides a response without CORS headers. List the origins that need access: ```ts http: { cors: { origin: ["https://desk.example.com"] } } ``` FrontMCP then also exposes the `Mcp-Session-Id` header, which clients using sessions need. CORS only affects browsers. It isn't access control; use [`auth`](https://frontmcp.dev/reference/sdk/frontmcp#auth) for that. ### Clients on other machines can't connect The server listens on `127.0.0.1` by default, so only the same machine can reach it. Set `http: { security: { bindAddress: "all" } }`, or the `FRONTMCP_BIND_ADDRESS=all` environment variable (handy in a Dockerfile), and put [`auth`](https://frontmcp.dev/reference/sdk/frontmcp#auth) in front of anything you expose. --- # @App > Group related tools, resources, prompts and providers into an app that a FrontMCP server hosts. Source: https://frontmcp.dev/reference/sdk/app [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@App` groups related capabilities, the tools, resources and prompts for one area like tickets or billing, together with the providers they use. A [`@FrontMcp`](https://frontmcp.dev/reference/sdk/frontmcp) server hosts one or more apps on the same endpoint. Each app keeps its providers to itself, and can have its own auth and defaults. ```ts @App(options) class MyApp {} ``` --- ## Reference ### `@App(options)` Apply `@App` to an empty class, and list the class in `@FrontMcp({ apps })`. ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket, SearchTickets } from "./tools"; import { TicketResource } from "./ticket.resource"; import { TriageTicket } from "./triage.prompt"; import { TicketStore } from "./ticket-store"; @App({ id: "help-desk", name: "Help Desk", description: "Search, triage and close support tickets", tools: [SearchTickets, CloseTicket], resources: [TicketResource], prompts: [TriageTicket], providers: [TicketStore], }) export class HelpDeskApp {} ``` [See more examples below.](https://frontmcp.dev/reference/sdk/app#usage) #### Options Required: | Option | Type | Description | | --- | --- | --- | | `name` | `string` | A readable name for logs and tooling, like `"Help Desk"`. | Optional: | Option | Type | Description | | --- | --- | --- | | `id` | `string` | A stable identifier. It prefixes names that clash with another app's, and is the URL path of a [standalone](https://frontmcp.dev/reference/sdk/app#standalone-apps) app. Defaults to `name` with spaces replaced by `-`, so set it: short, lowercase, like `help-desk`. | | `description` | `string` | What the app is for. For your own documentation and tooling; FrontMCP doesn't send it to clients. | | `tools` | `ToolType[]` | [`@Tool`](https://frontmcp.dev/reference/sdk/tool) classes or `tool()` functions. | | `resources` | `ResourceType[]` | [`@Resource`](https://frontmcp.dev/reference/sdk/resource) and [`@ResourceTemplate`](https://frontmcp.dev/reference/sdk/resource-template) classes. | | `prompts` | `PromptType[]` | [`@Prompt`](https://frontmcp.dev/reference/sdk/prompt) classes or `prompt()` functions. | | `providers` | `ProviderType[]` | [Providers](https://frontmcp.dev/reference/sdk/provider) for this app's tools, resources and prompts. Other apps can't see them. Background work goes here too: [`@Duty`](https://frontmcp.dev/reference/sdk/duty) classes, and since 1.12.0 [`@Worker`](https://frontmcp.dev/reference/sdk/worker) classes, are providers. | | `routes` | `HttpRouteType[]` | Optional; defaults to none. [HTTP routes](https://frontmcp.dev/reference/sdk/http-route) using this app's providers. | | `plugins` | `PluginType[]` | Plugins that hook into this app's requests, such as caching or auditing, and can add tools and providers of their own. See [`@Plugin`](https://frontmcp.dev/reference/sdk/plugin). | | `adapters` | `AdapterType[]` | Adapters that generate tools from another source, such as an [OpenAPI spec](https://frontmcp.dev/reference/adapters/openapi). | | `authProviders` | `AuthProviderType[]` | Credentials this app's tools can ask for with `authProviders` on `@Tool`, such as a GitHub token. | | `auth` | `AuthOptionsInput` | This app's auth, overriding the server's `auth`, for an app with its own endpoint (`standalone` or `splitByApp`). On the shared endpoint only the server's `auth` checks callers, so where the app's would go unchecked the server refuses to start: a server with no `auth`, or in `public`, `static` or `transparent` mode (a `static` app that accepts all of a `static` server's tokens is allowed). In `local` and `remote` mode it starts, and app grants are checked per call only with `incrementalAuth`. The same modes as [`@FrontMcp`](https://frontmcp.dev/reference/sdk/frontmcp#auth). See [Auth for one app](https://frontmcp.dev/reference/auth/modes#auth-for-one-app). (Changed in 1.9.2: before, the shared endpoint ignored it, and the app's tools were as open as the server's.) | | `output` | `OutputPolicy` | Defaults for this app's tool results: `schemaMode`, `schemaDescriptionFormat`, `undeclaredKeys` (default `"warn"` in development, `"strip"` otherwise) and `budget` ([below](https://frontmcp.dev/reference/sdk/app#budgeting-answers)). Overrides the server's settings; a tool's own settings override both. `allowNonFinite` also overrides the server's value; a tool's setting wins over both. See [Output policy](https://frontmcp.dev/reference/sdk/tool#output-policy) and [overriding server defaults](https://frontmcp.dev/reference/sdk/app#overriding-server-defaults-for-one-app). | | `ui` | `{ servingMode? }` | The [serving mode](https://frontmcp.dev/reference/ui#serving-modes) of this app's tools that don't set one. Overrides the server's `ui.servingMode`; a tool's own `ui.servingMode` overrides both. A value that isn't a serving mode throws a `ZodError` when the class is decorated. See [Defaults for the server and an app](https://frontmcp.dev/reference/ui#defaults-for-the-server-and-an-app). New in 1.9.4. | | `standalone` | `boolean \| "includeInParent"` | Serve the app on its own path. Defaults to `false`. See [standalone apps](https://frontmcp.dev/reference/sdk/app#standalone-apps). | | `agents` | `AgentType[]` | Agents: tools backed by their own model and tools. Each is exposed as a tool. | | `skills` | `SkillType[]` | Skills: step-by-step guides for using several tools together, exposed as resources. | | `jobs` | `JobType[]` | Jobs: named units of work with typed input and output, for the server's jobs system. | | `workflows` | `WorkflowType[]` | Workflows that run jobs in steps. | | `channels` | `ChannelType[]` | Channels that push events to Claude Code sessions. See [`@Channel`](https://frontmcp.dev/reference/sdk/channel). | | `events` | `EventType[]` | [`@Event`](https://frontmcp.dev/reference/sdk/event) classes and `event()` results: the event types clients list with `events/list`, subscribe to, poll or stream. Declaring one turns events on for the server; [`@FrontMcp({ events })`](https://frontmcp.dev/reference/sdk/frontmcp#events) holds their options. Each event runs with this app's providers. A name must be unique on its endpoint: two events with one name stop the server with `EVENT_NAME_CONFLICT`. New in 1.12.0. | Changed in 1.10.16: before, tools contributed by an app's plugins and adapters could miss the app's output policy. They now inherit its schema advertisement and undeclared-key settings too. #### Standalone apps By default every app is served on the server's one MCP endpoint. `standalone` gives an app its own endpoint, under its `id`: | `standalone` | On the main endpoint | On `/` | | --- | --- | --- | | `false` (default) | Yes | No | | `true` | No | Yes | | `"includeInParent"` | Yes | Yes | ```ts main.ts @App({ id: "billing", name: "Billing", tools: [GetInvoice], standalone: true }) class BillingApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp, BillingApp], http: { port: 3000, entryPath: "/mcp" }, }) export default class Server {} // http://localhost:3000/mcp → Help Desk tools only // http://localhost:3000/mcp/billing → Billing tools only ``` The path is relative to `http.entryPath`: with the default entry path, `/`, the billing app is at `/billing`. The Playground has one endpoint and no paths, so standalone apps can't be shown in it. To give **every** app its own path, use `splitByApp: true` on [`@FrontMcp`](https://frontmcp.dev/reference/sdk/frontmcp). #### Apps from outside your code `App.remote()` connects to another MCP server and serves its tools, resources and prompts as an app. `App.esm()` loads an app from an npm package and runs it in your process. [Remote servers](https://frontmcp.dev/reference/server/remote) and [Loading apps from npm](https://frontmcp.dev/reference/server/esm) document every option, with examples that run against stand-in servers in the Playground. ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [ HelpDeskApp, App.remote("https://status.example.com/mcp", { namespace: "status", transportOptions: { timeout: 10_000 }, remoteAuth: { mode: "static", credentials: { type: "bearer", value: process.env.STATUS_TOKEN! } }, }), App.esm("@acme/crm-mcp@^2.0.0", { namespace: "crm" }), ], }) export default class Server {} ``` | Option | Applies to | Description | | --- | --- | --- | | `namespace` | both | Prefix for the app's tool, resource and prompt names. For `App.esm()` it defaults to the package name. | | `name`, `description` | both | Override the name derived from the URL or package, and describe the app. The app's id is the `name` you set, else the `namespace`, else the derived name; two apps with one id stop the server from starting, with `DuplicateAppIdError`. (Changed in 1.9.3: before, the `namespace` didn't count, and the server started.) | | `standalone` | both | As for `@App`. | | `filter` | both | Which tools, resources and prompts to serve, like `{ exclude: { tools: ["delete_*"] } }`. ESM apps also filter `skills`, `agents`, `jobs` and `workflows` by their original names. (Changed in 1.9.2: before, it was ignored.) | | `transportOptions` | `remote` | `timeout` (default 30000 ms, for connecting, tools, resources and prompts), `fallbackToSSE` (`true`), `headers` for every request, and `retryAttempts` and `retryDelayMs`: a tool call that fails on the network, times out, or gets HTTP `408`, `425`, `429` or a `5xx` other than `501` and `505` is tried again, 3 times in all by default, or `retryAttempts` + 1. See [retries](https://frontmcp.dev/reference/server/remote#retrying-calls-that-fail-on-the-way). (Changed in 1.9.2: before, `retryAttempts` and `retryDelayMs` were ignored. Changed in 1.9.3: before, only network failures were retried.) | | `remoteAuth` | `remote` | Credentials for the remote server: `{ mode: "static", credentials: { type: "bearer", value } }` sends them on every request. [Remote servers](https://frontmcp.dev/reference/server/remote#authenticating-to-the-remote-server) has the other modes: `forward`, `mapped` (since 1.9.3) and `oauth`. (Changed in 1.9.2: before, it sent nothing.) | | `refreshInterval`, `cacheTTL` | `remote` | How often to re-read the remote server's capabilities (default never), and how long to cache them (default 60000 ms). | | `autoUpdate`, `cacheTTL`, `loader`, `importMap` | `esm` | Poll for new versions that match the range; how long to cache a loaded package; a [loader](https://frontmcp.dev/reference/server/esm#the-loader) whose fields override the server's for this app, inheriting the rest; and an import map, which rewrites the package's imports of the packages it names. Either app token field replaces both server token fields. (Changed in 1.11.3: before, an app loader replaced all server settings. Changed in 1.9.2: before, `importMap` was ignored.) | Without its own `loader`, `App.esm()` fetches packages with the server's [`loader`](https://frontmcp.dev/reference/server/esm#the-loader) settings. #### `app(options)` The function form takes the same options and returns an app class, for code that builds apps from data rather than declaring them. See [building an app without a decorator](https://frontmcp.dev/reference/sdk/app#building-an-app-without-a-decorator). #### Caveats - The class body is ignored. Keep it empty. - Every entry in `tools`, `resources`, `prompts` and `providers` must be decorated (or made with the function form). The server fails to start otherwise. - An app's providers are **private to it**. To share one between apps, register it on `@FrontMcp({ providers })`. - When two apps expose a tool with the same name, FrontMCP renames **both** to `:`. See [when two apps use the same name](https://frontmcp.dev/reference/sdk/app#when-two-apps-use-the-same-name). ### Budgeting answers `output.budget: { maxBytes, lists? }` limits the answers of the app's tools and the reads of its resources. It defaults to off. A tool overrides its app, and an app overrides the server; `false` disables an inherited budget. Resources take the app's budget, else the server's, and UI widget resources are never cut. `maxBytes` is a whole number of at least 1024; `lists` is `"keep-newest"` (default) or `"keep-oldest"`. See the [tested tool example](https://frontmcp.dev/reference/sdk/tool#fitting-an-answer-to-a-budget). New in 1.11.0. --- ## Usage ### Grouping capabilities into an app Put everything one area needs in one app: its tools, its resources, its prompts, and the providers they share. Open the **Capabilities** tab to see what the app exposes. Initial call configuration: ```js { tool: "search_tickets", arguments: { query: "log" } } ``` ```ts help-desk.app.ts active import { App } from "@frontmcp/sdk"; import { SearchTickets } from "./search-tickets.tool"; import { TicketResource } from "./ticket.resource"; import { TriageTicket } from "./triage.prompt"; import { TicketStore } from "./ticket-store"; @App({ id: "help-desk", name: "Help Desk", tools: [SearchTickets], resources: [TicketResource], prompts: [TriageTicket], providers: [TicketStore], }) export class HelpDeskApp {} ``` ```ts search-tickets.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Tool({ name: "search_tickets", description: "Search support tickets by words in their title", inputSchema: { query: z.string() }, }) export class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: this.get(TicketStore).search(query) }; } } ``` ```ts ticket.resource.ts import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @ResourceTemplate({ name: "ticket", uriTemplate: "ticket://{id}", mimeType: "application/json", description: "One ticket by id" }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(this.get(TicketStore).find(id)) }] }; } } ``` ```ts triage.prompt.ts import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "triage_ticket", description: "Suggest a priority and a next step for a ticket", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class TriageTicket extends PromptContext { async execute({ id }: Record): Promise { return { messages: [{ role: "user", content: { type: "text", text: `Read ticket://${id}, then suggest a priority and a next step.` } }] }; } } ``` ```ts ticket-store.ts import { Provider } from "@frontmcp/sdk"; @Provider({ name: "TicketStore" }) export class TicketStore { private tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", title: "Login link expired", status: "open" }, ]; search(query: string) { return this.tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())); } find(id: string) { return this.tickets.find((t) => t.id === id); } } ``` ### Hosting several apps on one server List each app in `@FrontMcp({ apps })`. Clients see one server, with every app's tools in one `tools/list`. Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-7" } } ``` ```ts main.ts active import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; import { BillingApp } from "./billing.app"; @FrontMcp({ info: { name: "support", version: "1.0.0" }, apps: [HelpDeskApp, BillingApp], }) export default class Server {} ``` ```ts help-desk.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "close_ticket", description: "Close a support ticket", inputSchema: { id: z.string() } }) class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, status: "closed" }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket] }) export class HelpDeskApp {} ``` ```ts billing.app.ts import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_invoice", description: "Get an invoice by id", inputSchema: { id: z.string() } }) class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, total: 120, currency: "EUR", paid: false }; } } @App({ id: "billing", name: "Billing", tools: [GetInvoice] }) export class BillingApp {} ``` ```ts apps.test.ts import { test, expect } from "@frontmcp/testing"; test("one tools/list has both apps' tools", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).toEqual(expect.arrayContaining(["close_ticket", "get_invoice"])); expect(names).toHaveLength(2); }); ``` ### When two apps use the same name Tool names must be unique on a server. When two apps each have a `search` tool, FrontMCP keeps both and renames them to `:`. The model sees the prefixed names. A call to the plain name still works, and reaches the first app in `apps` without saying so. Initial call configuration: ```js { tool: "billing:search", arguments: { query: "INV" } } ``` ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "search", description: "Search support tickets", inputSchema: { query: z.string() } }) class SearchTickets extends ToolContext { async execute({ query }: { query: string }) { return { tickets: [`T-1 (matched "${query}")`] }; } } @Tool({ name: "search", description: "Search invoices", inputSchema: { query: z.string() } }) class SearchInvoices extends ToolContext { async execute({ query }: { query: string }) { return { invoices: [`INV-7 (matched "${query}")`] }; } } @App({ id: "desk", name: "Help Desk", tools: [SearchTickets] }) class DeskApp {} @App({ id: "billing", name: "Billing", tools: [SearchInvoices] }) class BillingApp {} @FrontMcp({ info: { name: "support", version: "1.0.0" }, apps: [DeskApp, BillingApp] }) export default class Server {} ``` ```ts names.test.ts import { test, expect } from "@frontmcp/testing"; test("both tools are renamed with their app's id", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).toEqual(["billing:search", "desk:search"]); }); test("the plain name reaches the first app", async ({ mcp }) => { expect((await mcp.tools.call("search", { query: "log" })).json()).toHaveProperty("tickets"); }); ``` The renaming only happens on a clash, so adding an app can rename tools that clients already use. Give tools names that are unique across the server, like `search_tickets` and `search_invoices`, and the question never comes up. ### Keeping providers private to an app A provider registered on an app is visible to that app only. One registered on `@FrontMcp` is shared by every app, as a single instance. Here both apps count into the same `Metrics`, but only the help desk can see `TicketStore`. Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-7" } } ``` ```ts main.ts active import { App, FrontMcp, Provider, Tool, ToolContext, z } from "@frontmcp/sdk"; @Provider({ name: "Metrics" }) class Metrics { calls = 0; } @Provider({ name: "TicketStore" }) class TicketStore { count = 3; } @Tool({ name: "count_tickets", description: "Count open tickets", inputSchema: {} }) class CountTickets extends ToolContext { async execute() { const calls = ++this.get(Metrics).calls; return { open: this.get(TicketStore).count, calls }; } } @Tool({ name: "get_invoice", description: "Get an invoice by id", inputSchema: { id: z.string() } }) class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { const calls = ++this.get(Metrics).calls; return { id, calls, canSeeTickets: this.tryGet(TicketStore) !== undefined }; } } @App({ id: "desk", name: "Help Desk", tools: [CountTickets], providers: [TicketStore] }) class DeskApp {} @App({ id: "billing", name: "Billing", tools: [GetInvoice] }) class BillingApp {} @FrontMcp({ info: { name: "support", version: "1.0.0" }, apps: [DeskApp, BillingApp], providers: [Metrics] }) export default class Server {} ``` ```ts providers.test.ts import { test, expect } from "@frontmcp/testing"; test("apps share server providers, not each other's", async ({ mcp }) => { await mcp.tools.call("count_tickets", {}); const invoice = await mcp.tools.call("get_invoice", { id: "INV-7" }); expect(invoice.json()).toEqual({ id: "INV-7", calls: 2, canSeeTickets: false }); }); ``` ### Overriding server defaults for one app Some settings cascade from the server to its apps to each tool, and the most specific one wins. `output` is one: here the server hides output schemas, and the help desk app puts them in its tools' descriptions instead. ```ts main.ts active import { App, FrontMcp, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "ticket_stats", description: "Count open and closed tickets", inputSchema: {}, outputSchema: z.object({ open: z.number(), closed: z.number() }), }) class TicketStats extends ToolContext { async execute() { return { open: 12, closed: 40 }; } } @Tool({ name: "invoice_stats", description: "Count paid and unpaid invoices", inputSchema: {}, outputSchema: z.object({ paid: z.number(), unpaid: z.number() }), }) class InvoiceStats extends ToolContext { async execute() { return { paid: 30, unpaid: 4 }; } } @App({ id: "desk", name: "Help Desk", tools: [TicketStats], output: { schemaMode: "description" } }) class DeskApp {} @App({ id: "billing", name: "Billing", tools: [InvoiceStats] }) class BillingApp {} @FrontMcp({ info: { name: "support", version: "1.0.0" }, apps: [DeskApp, BillingApp], output: { schemaMode: "none" } }) export default class Server {} ``` ```ts output.test.ts import { test, expect } from "@frontmcp/testing"; test("the app's setting beats the server's", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "ticket_stats"); expect(tool?.outputSchema).toBeUndefined(); expect(tool?.description).toContain("**Returns:**"); }); test("other apps keep the server's setting", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "invoice_stats"); expect(tool?.outputSchema).toBeUndefined(); expect(tool?.description).toBe("Count paid and unpaid invoices"); }); ``` `schemaMode` can be `"definition"` (the default: send it as `outputSchema`), `"description"`, `"both"` or `"none"`. `ui.servingMode` cascades the same way (since 1.9.4): see [Defaults for the server and an app](https://frontmcp.dev/reference/ui#defaults-for-the-server-and-an-app). ### Building an app without a decorator `app()` builds an app from a plain object. It's useful when the list of tools comes from data, such as a config file or a loop. Initial call configuration: ```js { tool: "count_open", arguments: {} } ``` ```ts help-desk.ts import { app, tool } from "@frontmcp/sdk"; const counts = { open: 12, closed: 40, pending: 3 }; const tools = Object.entries(counts).map(([status, count]) => tool({ name: `count_${status}`, description: `How many tickets are ${status}`, inputSchema: {} })(async () => ({ count })), ); export const helpDesk = app({ id: "help-desk", name: "Help Desk", tools }); ``` ### Lazy apps An app can declare `{ id?, name, description?, lazy: () => Promise, enabled? }` instead of importing its class at startup. Until the first call imports it, the [build manifest](https://frontmcp.dev/reference/deployment/production-build#the-build-manifest) answers the lists for its tools, resources, resource templates and prompts. Concurrent first calls share that import. New in 1.11.0. | Lazy app field | Type | Default | Description | | --- | --- | --- | --- | | `name` | `string` | required | The app's name. Without `id`, the id is derived from it, as for `@App`. | | `id` | `string` | derived from `name` | Must equal the id of the `@App` the import loads; otherwise the import fails with `LAZY_APP_CONFIGURATION_ERROR`. | | `description` | `string` | none | What the app provides. | | `lazy` | `() => Promise` | required | Imports the app: resolves to its `@App` class, or to a module whose default export, or only `@App` export, is one. | | `enabled` | `EnabledOption` | on | The same switch as an entry's. While it is off, the app's entries are refused with `FEATURE_OFF` and the app is never imported. | ```ts apps: [{ id: "reports", name: "Reports", lazy: () => import("./reports.app.js") }], manifest: "./frontmcp.manifest.json", ``` Ship the manifest next to the server's entry, or pass `manifest` on `@FrontMcp`. Without one, a server outside production logs that its lazy apps load at startup, and imports them then; with `NODE_ENV=production`, startup fails with `LAZY_APP_CONFIGURATION_ERROR`. An import that fails answers each call `LAZY_APP_LOAD_FAILED`, with a remedy; one that can be retried is imported again on the next call. When the loaded app's lists differ from the manifest's, the server announces the lists that changed. A lazy app is listed before its code runs, so nothing in it may need that code to be listed, and it may set up nothing that only startup sets up. The app is refused with `LAZY_APP_CONFIGURATION_ERROR`, at startup when the manifest shows it or when it's imported, and its calls answer `LAZY_APP_LOAD_FAILED` until the server restarts, when: - the app declares `jobs`, `workflows`, `channels`, `events` (since 1.12.0), `skills` or `agents`, its own `auth`, `standalone` or `ui` defaults; - it has `@Duty` providers or `@Worker` providers (since 1.12.0), which start with the server, a plugin with `scope: "server"`, a hook with `appliesTo: "all-apps"`, or a hook on a flow other than `tools/call`, `resources/read`, `prompts/get` and `completion/complete`, which runs for every app; - one of its tools, resources, templates or prompts declares `authorities`, a `ui` widget or an `enabled` source of its own, or `featureFlag` or `codecall`, which those plugins read before the call. Put a `featureFlagSource()` on the lazy app's `enabled` instead. The reasons are named in the error: `it declares events`, or `it has workers ("inbox-watcher"), which start with the server`. An app that needs events or background work is imported normally; the rest of the server's apps can still be lazy. A hook on one of the [events flows](https://frontmcp.dev/reference/server/flows#the-events-flows) keeps an app from being lazy too, like any hook on a flow that runs for every app. > **Note** > > The Playground compiles project files into one module. It cannot demonstrate deployment of separate lazy app modules next to a build manifest. --- ## Troubleshooting ### `tools items must be annotated with @Tool() | @FrontMcpTool(), be a package specifier string, or come from Tool.esm() | Tool.remote().` The server fails to start with `@App invalid metadata for "tools"`, and the index of the bad entry. That entry is a class without `@Tool`. (Changed in 1.9.1: the message used to end at `or be a package specifier string.`, before `Tool.esm()` and `Tool.remote()` entries were accepted.) Check that the decorator is there and that you imported the class, not something else with the same name. The same kind of message appears for `resources`, `prompts` and `providers`. ### A tool was renamed to `desk:search` Another app on the same server has a tool with the same name, so FrontMCP prefixed both with their app's `id`. Rename one of the tools. See [when two apps use the same name](https://frontmcp.dev/reference/sdk/app#when-two-apps-use-the-same-name). ### `Provider "TicketStore" is not available: not found in local or parent registries` The tool's app can't see the provider. Often it's registered on a **different** app: Initial call configuration: ```js { tool: "get_invoice", arguments: { id: "INV-7" } } ``` ```ts main.ts active import { App, FrontMcp, Provider, Tool, ToolContext, z } from "@frontmcp/sdk"; @Provider({ name: "TicketStore" }) class TicketStore { forInvoice(id: string) { return ["T-2"]; } } @Tool({ name: "get_invoice", description: "Get an invoice and its tickets", inputSchema: { id: z.string() } }) class GetInvoice extends ToolContext { async execute({ id }: { id: string }) { return { id, tickets: this.get(TicketStore).forInvoice(id) }; } } // 🚩 TicketStore belongs to the help desk app, so billing can't see it @App({ id: "desk", name: "Help Desk", providers: [TicketStore] }) class DeskApp {} @App({ id: "billing", name: "Billing", tools: [GetInvoice] }) class BillingApp {} @FrontMcp({ info: { name: "support", version: "1.0.0" }, apps: [DeskApp, BillingApp] }) export default class Server {} ``` Move the provider to `@FrontMcp({ providers })` to share it, or register it in the app that uses it. ### A standalone app's tools are missing With `standalone: true`, an app is only served at `/`, not on the main endpoint. Point the client at the app's own URL, or use `standalone: "includeInParent"` to serve it in both places. --- # @HttpRoute > Serve pages, JSON and live SSE views from an app's providers, with route hooks and people sign-in. Source: https://frontmcp.dev/reference/sdk/http-route [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A server can offer a page or a JSON endpoint alongside MCP. `@HttpRoute` puts that route in an app, where it uses the same providers as its tools. Requests run through the `http:route` flow for IP filtering, rate limits, same-origin checks and people sign-in. New in 1.11.0. ```ts @HttpRoute({ method, path, auth?, sse? }) class BoardPage extends HttpRouteContext { async handle() { return { open: 2 }; } } ``` --- ## Reference ### `@HttpRoute(options)` Register the class in `@App({ routes: [BoardPage] })`. | Option | Type | Default | Description | | --- | --- | --- | --- | | `method` | `"GET" \| "POST" \| "PUT" \| "PATCH" \| "DELETE"` | required | Request method. An `sse` route must use `"GET"`. | | `path` | `string \| (() => string)` | required | Literal path segments and `:name` parameters, such as `/board/:id`. No wildcards or groups (`*`, `()`, `{}`), query, fragment or whitespace. A function resolves at startup. | | `auth` | `"people" \| "subject" \| "public"` | `"people"` when people auth is configured, else `"public"` | Who may call the route: a person signed in through [people sign-in](https://frontmcp.dev/reference/sdk/http-route#people-sign-in), a person signed in for one MCP caller (the [question inbox](https://frontmcp.dev/reference/sdk/elicit#persistent-questions)), or anyone. Each kind of session opens only its own kind of route. `"people"` and `"subject"` need `http.auth.people`. | | `sse` | `{ store, topics, coalesceMs?, heartbeatMs? }` | none | Serve `text/event-stream`: `handle()`'s view is sent at once, and again after each burst of publishes on `topics`. `store` is anything with `subscribe(topic, listener)`, such as a [`resourceStore()`](https://frontmcp.dev/reference/sdk/resource#resourcestoreoptions), whose keys publish their name as a topic. `topics` names at least one. Defaults: coalesce 50 ms, heartbeat 15000 ms. | `HttpRouteContext` exposes `request` (method, path, headers, query and parsed body, and `bodyBytes`, the body as it arrived, for a signature over the exact bytes: on the Node server for a JSON or form body, under `createFetchHandler()` for any body; new in 1.11.1), path `params`, optional `person` (`person.subject` on a `"subject"` route), and `get()` for the app's providers. #### What `handle()` returns | `handle()` returns | Response | | --- | --- | | An object or array | `200`, as JSON | | A string | `200`, as `text/plain` | | Nothing | `204` | | An `httpRespond` output | As built: `httpRespond.json(body, { status })`, `httpRespond.html(markup, status?, headers?)`, `httpRespond.redirect(url)` (`302`), and the others | On an `sse` route, the return value is the view: one `data:` event, with an object as JSON. Returning nothing sends no event. #### Caveats - **Reserved paths.** The MCP endpoint's paths (with its `/sse`, `/message` and `/server-card`), `/oauth/*`, `/.well-known/*`, `/health`, `/metrics` and the health probe paths stop the server with `ReservedRouteCollisionError`, as they do for [`http.routes`](https://frontmcp.dev/reference/sdk/frontmcp#custom-httproute--collides-with-the-reserved-frontmcp-path). One exception: a `GET` route may use the MCP endpoint's own path. A page load there reaches the route, and a request for an event stream, or one with an `Mcp-Session-Id`, stays the endpoint's. An `sse` route can't use that path. - **Built-in routes.** With `http.auth.people` set, the sign-in routes under `/_frontmcp/people/`, and the question inbox's, are routes of the server too: a route with the same method and path stops the server with `InvalidHttpRouteError`. - **Same origin.** `POST`, `PUT`, `PATCH` and `DELETE` are refused with `403` when the request comes from another site's page: an `Origin` that isn't the server's own, or a `Sec-Fetch-Site` other than `same-origin` or `none`. A request with neither header, from a client that isn't a browser, is allowed. The explicit origins in `http.cors` and in `http.security.dnsRebindingProtection.allowedOrigins` are allowed too. - **Redirects** go to an absolute URL or to a path, such as `httpRespond.redirect("/board")`, relative to the request. Characters a URL doesn't carry as they are, like `é`, `"` or `<`, are percent-encoded in the `Location` header: `/tickets/café` is sent as `/tickets/caf%C3%A9`. A location that starts with `//`, like `//elsewhere.example/board`, is sent as it is, and a browser takes it to that other site: don't build one from a request's input. Changed in 1.11.1: before, a path answered `200` with the redirect object as JSON. - **A response that doesn't fit its kind** answers `500`. An `httpRespond` output, or any object with a response `kind` and a `status`, that fails its kind's checks, like a redirect to a location with a space, is logged as [`INVALID_HTTP_ROUTE_RESPONSE`](https://frontmcp.dev/reference/sdk/http-route#http-route--returned-an-invalid--response). An object with no `status` is data, sent as JSON. Changed in 1.11.1: before, the bad output was sent as JSON with `200`. - **SSE.** Only the latest view waits for a slow reader. On Node, the next event waits for the socket to drain, and the stream stops when the client leaves. - **Hooks.** `HttpRouteHook` hooks the stages `checkIpFilter`, `findRoute`, `acquireQuota`, `checkSameOrigin`, `authenticatePerson` and `handle`. ### People sign-in `http.auth.people: "loopback-token"` turns on sign-in for people, under `/_frontmcp/people/`, and routes default to `auth: "people"`. When the server starts, it prints a sign-in token on stderr, once. 1. A local process trades the token for a one-time code: `POST /_frontmcp/people/code` with `Authorization: Bearer `. The answer has `code`, `expiresAt` and `loginPath`. 2. A browser opens `loginPath`, `/_frontmcp/people/login?code=…`, and submits its form. That spends the code for an `HttpOnly`, `SameSite=Strict` session cookie, which opens `"people"` routes. A tool can hand a person a code too. `this.get(LoopbackTokenAuth).createCode()` returns `{ code, expiresAt }`, a code for `"people"` routes. `createCode({ subject })` makes one that opens only that MCP caller's `"subject"` routes, such as its [question inbox](https://frontmcp.dev/reference/sdk/elicit#persistent-questions), and no `"people"` route. The object form takes `mode: "loopback-token"` and these settings: | Option | Type | Default | Description | | --- | --- | --- | --- | | `codeTtlMs` | `number` | `60000` | One-time code lifetime, at most 600000 ms. | | `sessionTtlMs` | `number` | `43200000` | Signed-in browser session lifetime. | | `maxFailedAttempts` | `number` | `5` | Failed attempts before lockout. | | `lockoutMs` | `number` | `60000` | Lockout and failed-attempt retention. | | `cookiePath` | `string` | `"/"` | Session cookie path. | > **Note** > > People sign-in has no Playground: it starts from the token the server prints on stderr when it starts. Run the server on Node to try it. --- ## Usage ### Serving JSON without opening a port ```ts main.ts active import { App, HttpRoute, HttpRouteContext } from "@frontmcp/sdk"; @HttpRoute({ method: "GET", path: "/board/:id", auth: "public" }) class Board extends HttpRouteContext { async handle() { return { id: this.params.id, open: 2 }; } } @App({ name: "Desk", routes: [Board] }) export class Desk {} ``` ```ts route.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { Desk } from "./main"; test("a fetch handler serves an app route", async () => { const handler = await FrontMcpInstance.createFetchHandler({ info: { name: "desk", version: "1.0.0" }, apps: [Desk] }); const response = await handler(new Request("http://localhost/board/support")); expect(response.status).toBe(200); expect(await response.json()).toEqual({ id: "support", open: 2 }); }); ``` ### Accepting changes from the server's own pages A `POST` route answers with `httpRespond` for a status of its own. A page of another site can't call it, and a redirect goes to an absolute URL or a path. ```ts tickets.ts active import { App, HttpRoute, HttpRouteContext, httpRespond } from "@frontmcp/sdk"; @HttpRoute({ method: "POST", path: "/tickets", auth: "public" }) class CreateTicket extends HttpRouteContext { async handle() { const { title } = this.request.body as { title: string }; return httpRespond.json({ id: "T-3", title }, { status: 201 }); } } @HttpRoute({ method: "GET", path: "/help", auth: "public" }) class Help extends HttpRouteContext { handle() { return httpRespond.redirect("https://frontmcp.dev/reference/sdk/http-route"); } } @App({ name: "Desk", routes: [CreateTicket, Help] }) export class Desk {} ``` ```ts tickets.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance, HttpRoute, HttpRouteContext, httpRespond } from "@frontmcp/sdk"; import { Desk } from "./tickets"; const info = { name: "desk", version: "1.0.0" }; const createTicket = async (headers: Record) => { const handler = await FrontMcpInstance.createFetchHandler({ info, apps: [Desk] }); return handler( new Request("http://localhost/tickets", { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify({ title: "Printer jam" }), }), ); }; test("the server's own page creates a ticket", async () => { const response = await createTicket({ origin: "http://localhost" }); expect(response.status).toBe(201); expect(await response.json()).toEqual({ id: "T-3", title: "Printer jam" }); }); test("another site's page is refused", async () => { const fromOrigin = await createTicket({ origin: "https://elsewhere.example" }); expect(fromOrigin.status).toBe(403); expect(await fromOrigin.json()).toEqual({ error: "Cross-origin requests may not change anything here." }); expect((await createTicket({ "sec-fetch-site": "cross-site" })).status).toBe(403); }); test("a client that isn't a browser sends neither header, and is allowed", async () => { expect((await createTicket({})).status).toBe(201); }); test("a redirect to an absolute URL is a 302", async () => { const handler = await FrontMcpInstance.createFetchHandler({ info, apps: [Desk] }); const response = await handler(new Request("http://localhost/help", { redirect: "manual" })); expect(response.status).toBe(302); expect(response.headers.get("location")).toBe("https://frontmcp.dev/reference/sdk/http-route"); }); test("a redirect to a path is a 302 too, and a location with a space is a 500", async () => { @HttpRoute({ method: "GET", path: "/home", auth: "public" }) class Home extends HttpRouteContext { handle() { return httpRespond.redirect("/board"); } } @HttpRoute({ method: "GET", path: "/broken", auth: "public" }) class Broken extends HttpRouteContext { handle() { return httpRespond.redirect("/board two"); } } @App({ name: "Home", routes: [Home, Broken] }) class HomeApp {} const handler = await FrontMcpInstance.createFetchHandler({ info, apps: [HomeApp] }); const home = await handler(new Request("http://localhost/home", { redirect: "manual" })); expect(home.status).toBe(302); expect(home.headers.get("location")).toBe("/board"); const broken = await handler(new Request("http://localhost/broken", { redirect: "manual" })); expect(broken.status).toBe(500); expect(await broken.text()).toBe("Internal Server Error"); }); test("a location is percent-encoded, and one that starts with // is sent as it is", async () => { @HttpRoute({ method: "GET", path: "/cafe", auth: "public" }) class Cafe extends HttpRouteContext { handle() { return httpRespond.redirect("/tickets/café"); } } @HttpRoute({ method: "GET", path: "/away", auth: "public" }) class Away extends HttpRouteContext { handle() { return httpRespond.redirect("//elsewhere.example/board"); } } @App({ name: "Redirects", routes: [Cafe, Away] }) class RedirectsApp {} const handler = await FrontMcpInstance.createFetchHandler({ info, apps: [RedirectsApp] }); const cafe = await handler(new Request("http://localhost/cafe", { redirect: "manual" })); expect(cafe.headers.get("location")).toBe("/tickets/caf%C3%A9"); const away = await handler(new Request("http://localhost/away", { redirect: "manual" })); expect(away.status).toBe(302); expect(away.headers.get("location")).toBe("//elsewhere.example/board"); }); test("createFetchHandler() keeps the bytes of a body of any type", async () => { @HttpRoute({ method: "POST", path: "/notes", auth: "public" }) class AddNote extends HttpRouteContext { handle() { return { contentType: this.request.headers["content-type"], bytes: this.request.bodyBytes?.length ?? null }; } } @App({ name: "Notes", routes: [AddNote] }) class NotesApp {} const handler = await FrontMcpInstance.createFetchHandler({ info, apps: [NotesApp] }); const response = await handler(new Request("http://localhost/notes", { method: "POST", headers: { "content-type": "text/plain" }, body: "Printer jam" })); expect(await response.json()).toEqual({ contentType: "text/plain", bytes: 11 }); }); ``` ### Streaming a live view An `sse` route sends `handle()`'s view when the page connects, and again whenever its topics are published. A key of a [`resourceStore()`](https://frontmcp.dev/reference/sdk/resource#serving-a-stored-value) publishes its name on every write, so a tool's write reaches the page. ```ts board.ts active import { App, HttpRoute, HttpRouteContext, resourceStore, Tool, ToolContext } from "@frontmcp/sdk"; export const store = resourceStore(); export const board = store.key("board", { initial: { open: 2 } }); @HttpRoute({ method: "GET", path: "/board/events", auth: "public", sse: { store, topics: ["board"] } }) class BoardEvents extends HttpRouteContext { async handle() { return (await board.get()).value; } } @Tool({ name: "close_ticket", description: "Close one open ticket", inputSchema: {} }) class CloseTicket extends ToolContext { async execute() { return (await board.update((current) => ({ open: current.open - 1 }))).value; } } @App({ name: "Desk", tools: [CloseTicket], routes: [BoardEvents] }) export class Desk {} ``` ```ts board.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { board, Desk } from "./board"; test("the page gets the board now, and again after a tool's write", async ({ mcp }) => { const handler = await FrontMcpInstance.createFetchHandler({ info: { name: "desk", version: "1.0.0" }, apps: [Desk] }); const response = await handler(new Request("http://localhost/board/events")); expect(response.status).toBe(200); expect(response.headers.get("content-type")).toBe("text/event-stream"); const events = response.body!.getReader(); const decoder = new TextDecoder(); const nextEvent = async () => decoder.decode((await events.read()).value); try { const { open } = (await board.get()).value; expect(await nextEvent()).toBe(`data: ${JSON.stringify({ open })}\n\n`); await mcp.tools.call("close_ticket", {}); expect(await nextEvent()).toBe(`data: ${JSON.stringify({ open: open - 1 })}\n\n`); } finally { await events.cancel(); } }); ``` ## Troubleshooting ### `INVALID_HTTP_ROUTE` The server didn't start. `InvalidHttpRouteError` (`HTTP route : `) names a route with the same method and path as another, a `path` function that returned an unusable path, an `sse` route on the MCP endpoint's path, a class in `routes` that isn't an `@HttpRoute`, or a `"people"` or `"subject"` route on a server without `http.auth.people`. Give each route its own method and path, keep SSE off the MCP endpoint's path, and set `http.auth.people` or `auth: "public"`. A reserved path fails with `ReservedRouteCollisionError` instead ([below](https://frontmcp.dev/reference/sdk/http-route#custom-httproute--collides-with-the-reserved-frontmcp-path)), and a bad literal `path` fails when the class is declared, with `INVALID_DECORATOR_METADATA` ([below](https://frontmcp.dev/reference/sdk/http-route#httproute-invalid-metadata-for-path)). ```ts startup.test.ts active import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance, HttpRoute, HttpRouteContext, type HttpRouteType } from "@frontmcp/sdk"; const info = { name: "desk", version: "1.0.0" }; const start = (routes: HttpRouteType[]) => { @App({ name: "Desk", routes }) class Desk {} return FrontMcpInstance.createFetchHandler({ info, apps: [Desk] }); }; @HttpRoute({ method: "GET", path: "/board", auth: "public" }) class Board extends HttpRouteContext { handle() { return { open: 2 }; } } @HttpRoute({ method: "GET", path: "/board/", auth: "public" }) class BoardAgain extends HttpRouteContext { handle() { return { open: 2 }; } } @HttpRoute({ method: "GET", path: "/team", auth: "people" }) class Team extends HttpRouteContext { handle() { return { people: 3 }; } } @HttpRoute({ method: "GET", path: "/health", auth: "public" }) class Health extends HttpRouteContext { handle() { return { ok: true }; } } test("two routes with one method and path", async () => { await expect(start([Board, BoardAgain])).rejects.toThrow("HTTP route GET /board/: another route already serves this method and path"); }); test("a people route without http.auth.people", async () => { await expect(start([Team])).rejects.toThrow("HTTP route GET /team: it needs a signed-in person, but http.auth.people is not set"); }); test("a reserved path is a ReservedRouteCollisionError", async () => { await expect(start([Health])).rejects.toThrow('Custom http.route "GET /health" collides with the reserved FrontMCP path "/health".'); }); test("a bad literal path fails at the decorator", () => { expect(() => HttpRoute({ method: "GET", path: "/files/*", auth: "public" })(Board)).toThrow( '@HttpRoute invalid metadata for "path"', ); }); ``` ```ts main.ts import { App, HttpRoute, HttpRouteContext } from "@frontmcp/sdk"; // ✅ Its own method and path, a public route, no wildcard @HttpRoute({ method: "GET", path: "/board/:id", auth: "public" }) class Board extends HttpRouteContext { handle() { return { id: this.params.id, open: 2 }; } } @App({ name: "Desk", routes: [Board] }) export class Desk {} ``` ### `HTTP route … returned an invalid "…" response` The route answered `500` `Internal Server Error`, and the server logged `INVALID_HTTP_ROUTE_RESPONSE`, `HTTP route GET /broken returned an invalid "redirect" response: location: …`: `handle()` returned an `httpRespond` output, or an object with a response `kind` and a `status`, that its kind doesn't accept. The log names each field that failed. A redirect's location, for one, can't hold whitespace or control characters. Fix the value; to send an object as data, leave out its `status`. ### `Custom http.route … collides with the reserved FrontMCP path` The server didn't start, because a route takes a path FrontMCP serves itself. `ReservedRouteCollisionError` names both paths and lists the reserved ones: see [Caveats](https://frontmcp.dev/reference/sdk/http-route#caveats) and [`http.routes`](https://frontmcp.dev/reference/sdk/frontmcp#custom-httproute--collides-with-the-reserved-frontmcp-path). Choose another path. ### `@HttpRoute invalid metadata for "path"` The class failed where it's declared, with `INVALID_DECORATOR_METADATA`: its `path` has a wildcard, a group, a query, a fragment or whitespace, or doesn't start with `/`. Use literal segments and `:name` parameters. The same check on the other options names them: an `sse` route that isn't `GET`, or an empty `topics`. ### `PERSON_NOT_SIGNED_IN` `401`: `Please sign in: open the one-time sign-in link the server gives you (POST /_frontmcp/people/code with its token).` Sign in with a code for the route's kind of `auth`: see [People sign-in](https://frontmcp.dev/reference/sdk/http-route#people-sign-in). A session made from a `createCode({ subject })` code doesn't open a `"people"` route, and a `"people"` session doesn't open a `"subject"` route. ### `Cross-origin requests may not change anything here.` `403`, code `CROSS_ORIGIN_REQUEST`: a `POST`, `PUT`, `PATCH` or `DELETE` came from another site's page. Send it from the server's own pages, or list the page's origin in `http.cors`. See [Accepting changes from the server's own pages](https://frontmcp.dev/reference/sdk/http-route#accepting-changes-from-the-servers-own-pages). --- # @Tool > Declare a function an AI model can call, with validated input and optional structured output. Source: https://frontmcp.dev/reference/sdk/tool [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@Tool` declares an MCP [tool](https://frontmcp.dev/learn/your-first-tool): a function an AI model can decide to call. FrontMCP checks every call against the tool's input schema before your code runs. ```ts @Tool(options) class MyTool extends ToolContext { async execute(input) { /* ... */ } } ``` --- ## Reference ### `@Tool(options)` Apply `@Tool` to a class that extends `ToolContext`, and list the class in an app's `tools` array. ```ts get-weather.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_weather", description: "Get current weather for a city", inputSchema: { city: z.string().describe("City name"), units: z.enum(["celsius", "fahrenheit"]).default("celsius"), }, }) class GetWeatherTool extends ToolContext { async execute(input: { city: string; units: "celsius" | "fahrenheit" }) { const weather = await fetchWeather(input.city, input.units); return { temperature: weather.temp, conditions: weather.conditions }; } } ``` [See more examples below.](https://frontmcp.dev/reference/sdk/tool#usage) #### Options Required: | Option | Type | Description | | --- | --- | --- | | `name` | `string` | What the model calls. Unique within the server. Prefer `verb_noun` in snake_case. | | `inputSchema` | object of Zod types | One Zod type per argument, like `{ city: z.string() }`. Becomes the JSON Schema clients see in `tools/list`. | Optional: | Option | Type | Description | | --- | --- | --- | | `aliases` | `string[]` | Optional; defaults to none. Old names that remain callable but never listed. Aliases win over dotted `owner.name` lookup. Conflicts stop startup with `ToolAliasConflictError`. | | `enabled` | `EnabledOption` | Optional; defaults to on. A boolean or `{ get(context?), subscribe(listener), remedy? }`. Off entries are omitted from lists and refused with `FEATURE_OFF`. Changes announce `list_changed`. See [live availability](https://frontmcp.dev/reference/sdk/tool#changing-availability-while-the-server-runs). | | `description` | `string` | What the tool does, what it returns, and when to use it. Always set it; it's the model's only documentation. | | `title` | `string` | A display name for people, like `"Search tickets"`. Sent in `tools/list` only when set. | | `outputSchema` | Zod schema, or one of `"string"`, `"number"`, `"boolean"`, `"date"`, `"image"`, `"audio"`, `"resource"`, `"resource_link"` | The shape of the result. Object schemas and unions of object schemas are advertised in `tools/list`; string, number, boolean and date literals advertise a wrapper schema. Results are checked against the declared schema: undeclared keys follow `output.undeclaredKeys`, and a result that doesn't match fails with `INVALID_OUTPUT` (see [Shaping Tool Results](https://frontmcp.dev/learn/shaping-tool-results#declaring-the-shape-with-outputschema)). | | `output` | `OutputPolicy` | How results are validated and their schema is advertised. Overrides app and server defaults. See [Output policy](https://frontmcp.dev/reference/sdk/tool#output-policy). | | `annotations` | `ToolAnnotations` | Hints for clients: `title`, `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`. See [describing side effects](https://frontmcp.dev/reference/sdk/tool#describing-side-effects-with-annotations). | | `examples` | `ToolExample[]` | Sample calls: `description`, `input` and optionally `output`. | | `tags` | `string[]` | Labels for grouping and filtering. | | `visibility` | `"public" \| "hidden" \| "internal"` | `hidden` leaves the tool out of `tools/list` but it can still be called by name. `internal` keeps it for in-process callers only. | | `rateLimit` | `RateLimitConfig` | Per-tool rate limit: `maxRequests`, `windowMs`, `partitionBy`. See [Guard options](https://frontmcp.dev/reference/sdk/guard). | | `concurrency` | `ConcurrencyConfig` | Cap on simultaneous executions: `maxConcurrent`, optional queue. See [Guard options](https://frontmcp.dev/reference/sdk/guard). | | `timeout` | `TimeoutConfig` | Execution timeout: `executeMs`. See [Guard options](https://frontmcp.dev/reference/sdk/guard). | | `authProviders` | `ToolAuthProviderRef[]` | Credentials the tool needs, such as `{ name: "github", scopes: ["repo"] }`. Required by default. Before `execute()`, FrontMCP looks each one up in the server's [credential providers](https://frontmcp.dev/reference/sdk/auth-providers#a-tools-authproviders), then in the caller's [credential vault](https://frontmcp.dev/reference/auth/progressive#credentials-authproviders-and-thiscredentials), and refuses the call without it. A server with neither doesn't check them. | | `availableWhen` | `EntryAvailability` | Only offer the tool on certain platforms, runtimes or deployments, or to some callers: `surface` lists who may call it, like `["mcp"]` for clients only, or `["agent"]` for [agents](https://frontmcp.dev/reference/sdk/agent#giving-an-agent-tools) only. Since 1.8.4, `surface` holds for agents and [jobs](https://frontmcp.dev/reference/sdk/call-tool#where-it-works) too. See [Environment awareness](https://frontmcp.dev/reference/server/environment). | | `execution` | `{ taskSupport }` | Whether the tool can run as a background task: `"required"`, `"optional"` or `"forbidden"`. See [Background tasks](https://frontmcp.dev/reference/server/tasks). | | `ui` | `ToolUIConfig` | A widget to render the result in clients that support it. With `ui`, `outputSchema` still drops the fields it doesn't declare ([Fields the schema doesn't declare](https://frontmcp.dev/reference/ui#fields-the-schema-doesnt-declare)). | Plugins add options of their own, which only take effect where the plugin is installed: `cache` ([Cache](https://frontmcp.dev/reference/plugins/cache#cache-in-tool)), `approval` ([Approval](https://frontmcp.dev/reference/plugins/approval#the-approval-tool-option)), `featureFlag` ([Feature flags](https://frontmcp.dev/reference/plugins/feature-flags#the-featureflag-option)) and `codecall` ([CodeCall](https://frontmcp.dev/reference/plugins/codecall#the-codecall-field-on-tool)). A server whose tool sets `approval` or `featureFlag`, with no plugin that enforces it, doesn't start: see [`Unenforced metadata`](https://frontmcp.dev/reference/sdk/plugin#unenforced-metadata-tool--declares-). #### Output policy Set `output` on `@FrontMcp`, `@App` or `@Tool`. `schemaMode`, `schemaDescriptionFormat` and `undeclaredKeys` resolve from tool, then app, then server, then their defaults. `allowNonFinite` follows the same tool > app > server order. Changed in 1.11.3: before, only the server's value was used. Changed in 1.10.16: before, tools contributed by an app's plugins and adapters could miss the app's output policy. They now inherit its schema advertisement and undeclared-key settings too. | Option | Type | Default | Description | | --- | --- | --- | --- | | `budget` | `false \| { maxBytes: number; lists?: "keep-newest" \| "keep-oldest" }` | off | Limit each copy of answer data; tool overrides app, then server. `maxBytes` is a whole number of at least 1024. See [fitting an answer](https://frontmcp.dev/reference/sdk/tool#fitting-an-answer-to-a-budget). | | `schemaMode` | `"definition" \| "description" \| "both" \| "none"` | `"definition"` | Advertise the schema in `outputSchema`, append it to the description, do both, or omit it. Validation still runs. | | `schemaDescriptionFormat` | `"summary" \| "jsonSchema"` | `"summary"` | A readable field list or a fenced JSON Schema. Object unions are summarized member by member. | | `allowNonFinite` | `boolean` | `false` | Allow `NaN` and infinities to serialize as `null` instead of failing, with tool > app > server precedence. | | `undeclaredKeys` | `"strip" \| "warn" \| "keep" \| "fail"` | `"warn"` in development; `"strip"` otherwise | What happens to keys dropped by parsing the Zod output schema. See [Choosing what happens to undeclared keys](https://frontmcp.dev/reference/sdk/tool#choosing-what-happens-to-undeclared-keys). | | `undeclaredKeys` | Result | | --- | --- | | `"strip"` | Drop keys the schema doesn't declare. | | `"warn"` | Drop them and log each key path once per tool, up to 100 paths. Array paths look like `lines[].margin`. | | `"keep"` | Restore them in text and `structuredContent`. The listed schema omits `additionalProperties: false` at every level so clients accept those keys. | | `"fail"` | Refuse the answer with `InvalidOutputError`, code `INVALID_OUTPUT`. The internal message names the keys; the production message stays generic. | Changed in 1.10.16: before, undeclared keys were silently stripped in development too. The default now warns when `NODE_ENV=development`; set `"strip"` for silent stripping. A call that renders a UI still sends declared keys only, even under `"keep"`. A schema containing a transform, preprocess, pipe or codec always uses its parsed answer: the undeclared-key policy doesn't apply. A schema's own unknown-key rules win: `z.strictObject()` refuses extra keys even under `"keep"`, and `z.looseObject()` keeps them even under `"strip"` or `"fail"`. Raw JSON Schema outputs aren't parsed by Zod and pass through as before. #### Advertisement in `tools/list` Object schemas and unions whose members all resolve to objects are listed, including nested unions and `$ref` members registered with `.meta({ id })`. `z.union()` and `z.discriminatedUnion()` need no cast. The union gets top-level `type: "object"` and keeps `anyOf` or `oneOf`. With elicitation enabled, `$defs` stays at the root of the fallback wrapper so its references resolve. Changed in 1.10.16: before, bare unions were omitted and readonly union tuples failed to compile. Schemas that cannot be listed, such as arrays, nullable objects, mixed unions and schemas without a JSON Schema representation, now log one startup warning naming the tool and reason. `schemaMode: "none"` suppresses it. Primitive Zod outputs, media and multi-content arrays remain unlisted and quiet. String, number, boolean and date literals advertise their wrapped structured-content schemas. A recursive union reference is left out too. #### Output parsing helpers `ToolEntry.getOutputJsonSchema()` returns the cached object-compatible JSON Schema or `null`; `getUnlistedOutputSchemaReason()` returns the reason a declared schema cannot be listed, or `undefined` when it is listed or intentionally unlisted. `getRawOutputSchema()` also applies the elicitation fallback wrapper. A `ToolEntry`'s `parseOutput(value, options?)` and `safeParseOutput(value, options?)` accept `OutputParseOptions`: `undeclaredKeys` (default `"strip"`) and `onUndeclaredKeys?: (keyPaths: string[]) => void` for `"warn"`. Omitting options preserves stripping, as on the UI and cache paths. The SDK exports `UNDECLARED_KEYS_POLICIES`, its `UndeclaredKeysPolicy` type, `resolveUndeclaredKeysPolicy(tool?, app?, server?)` for the cascade above, and `withUndeclaredKeysAllowed(schema)` for a copy of a JSON Schema without `additionalProperties: false`. [`@frontmcp/utils`'s `findDroppedKeys(original, parsed)`](https://frontmcp.dev/reference/sdk/tool#choosing-what-happens-to-undeclared-keys) returns dropped key paths; [`hasTransform(schema)`](https://frontmcp.dev/reference/sdk#z-eagerz-and-lazyz) from `@frontmcp/lazy-zod` detects schemas where comparing those paths is inappropriate. #### `execute(input)` FrontMCP calls `execute()` once the arguments pass validation. Inside it, `this` is a `ToolContext`: [Context classes](https://frontmcp.dev/reference/sdk/contexts) lists everything on it. - `input`: the validated arguments. Its TypeScript type must match `inputSchema`. - **Returns** anything. Objects arrive as the result's `structuredContent`. Plain values, like strings and numbers, arrive as `{ "value": ... }`, unless `outputSchema` is `"string"`, `"number"` or `"boolean"`: then the text block is the value itself. The same data is also sent as text in `content`, for clients that don't read structured output. Inside `execute()`, `this` is the `ToolContext`: `this.get()` for providers, `this.fetch()` for outbound HTTP, `this.notify()` and `this.progress()` for status, `this.elicit()` to ask the user for input, and `this.fail()` to return an error. #### Caveats - The class **must extend `ToolContext`**. - The type of `execute()`'s parameter **must match `inputSchema`** exactly, and with an `outputSchema`, its return type must match that. `@Tool` checks all three when TypeScript compiles, and reports a mismatch on the decorator line (see [Troubleshooting](https://frontmcp.dev/reference/sdk/tool#typescript-says-unable-to-resolve-signature-of-class-decorator)). - Arguments that aren't in `inputSchema` are **dropped** before `execute()` runs. - If `execute()` throws a plain `Error`, clients see the message and stack in development, and a generic "Internal FrontMCP error" with an error ID in production. Use [`PublicMcpError`](https://frontmcp.dev/reference/sdk/tool#returning-an-error-the-model-can-read) for messages the model should read. - The class can declare [hooks](https://frontmcp.dev/reference/sdk/hooks#where-hooks-can-be-declared) that run for this tool's calls only: instance methods from `Did("createToolCallContext")` on, and, since 1.9.4, `static` methods on any stage, like `parseInput`. An instance method on an earlier stage stops the server from starting. ### `fileSignal(path, key, options?)` Returns an `EnabledSource` for [`enabled`](https://frontmcp.dev/reference/sdk/tool#changing-availability-while-the-server-runs) that reads the boolean under `key` in the JSON file at `path`, on Node. It watches the file's folder and reads the file again every `pollIntervalMs`. A missing file, or a key without a boolean, gives `defaultValue`; content that isn't JSON, as a write in progress leaves it, keeps the last value read. An empty `path` or `key`, or a `pollIntervalMs` that isn't a positive number, throws `InvalidFileSignalError` (`INVALID_FILE_SIGNAL`) where the entry is declared. New in 1.11.0. | Option | Type | Default | Description | | --- | --- | --- | --- | | `defaultValue` | `boolean` | `false` | Used while the file is missing or its key has no boolean. | | `pollIntervalMs` | `number` | `2000` | Positive finite milliseconds between reads, alongside file watching. | | `remedy` | `ErrorRemedy` | `Turn on the "" feature, then try again.` | Next step sent with the `FEATURE_OFF` refusal. | | `logger` | `{ warn(message: string): void }` | `console` | Reports each file problem once. | ### Answer budget helpers `fitToolAnswer(result, budget)` and `fitResourceAnswer(result, budget)` from `@frontmcp/sdk` return a shortened result, or `undefined` when no change is needed. `budget` is `{ maxBytes: number; lists?: "keep-newest" | "keep-oldest" }`, with `"keep-newest"` as the default. They add a text note and `_meta[BUDGET_META_KEY]` (`"frontmcp/budget"`) describing omissions. Tool images, audio and resource blocks, and resource HTML and blobs, are left whole. These helpers don't check an output schema; the server's tool flow does, as [Fitting an answer to a budget](https://frontmcp.dev/reference/sdk/tool#fitting-an-answer-to-a-budget) describes. New in 1.11.0. --- ## Usage ### Validating input Put every constraint in the schema. The model sees it in `tools/list`, and FrontMCP rejects calls that break it before `execute()` runs, with an `isError` result that lists each problem. Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Can't reset my password", priority: "high" } } ``` ```ts create-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "create_ticket", description: "Open a new support ticket", inputSchema: { title: z.string().min(5).max(120).describe("One-line summary of the problem"), priority: z.enum(["low", "normal", "high"]).default("normal"), email: z.string().email().optional().describe("Where to send updates"), }, }) export class CreateTicket extends ToolContext { async execute(input: { title: string; priority: "low" | "normal" | "high"; email?: string }) { return { id: "T-4", ...input }; } } ``` ### Returning results Return a plain value, an object, or an object that matches an `outputSchema`. Clients get objects as `structuredContent`, and plain values wrapped as `{ "value": ... }`. Both also arrive as text. To send a plain value as it is, declare it with a primitive `outputSchema`. ### Return values ### Example: Plain value A number, string or boolean is wrapped as `{ "value": ... }`. Initial call configuration: ```js { tool: "count_open", arguments: {} } ``` ```ts count-open.tool.ts import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "count_open", description: "How many tickets are open", inputSchema: {} }) export class CountOpen extends ToolContext { async execute() { return 12; } } ``` ### Example: Object An object arrives as `structuredContent` as it is. Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts get-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one ticket by id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id, title: "Cannot log in", status: "open" }; } } ``` ### Example: Plain text With `outputSchema: "string"`, the text block is the string itself, and `structuredContent` is `{ "content": ... }`. Initial call configuration: ```js { tool: "ticket_status", arguments: { id: "T-1" } } ``` ```ts ticket-status.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "ticket_status", description: "Get the status of a ticket, as a sentence", inputSchema: { id: z.string() }, outputSchema: "string", }) export class TicketStatus extends ToolContext { async execute({ id }: { id: string }) { return `Ticket ${id} is open.`; } } ``` ```ts ticket-status.test.ts import { test, expect } from "@frontmcp/testing"; test("the text is the sentence itself", async ({ mcp }) => { const result = await mcp.tools.call("ticket_status", { id: "T-1" }); expect(result.text()).toBe("Ticket T-1 is open."); expect(result.raw.structuredContent).toEqual({ content: "Ticket T-1 is open." }); }); ``` ### Example: Declared output With `outputSchema`, clients see the result's shape in `tools/list` before they call, and a result that doesn't match fails with `INVALID_OUTPUT`. Initial call configuration: ```js { tool: "ticket_stats", arguments: {} } ``` ```ts ticket-stats.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "ticket_stats", description: "Count open and closed tickets", inputSchema: {}, outputSchema: z.object({ open: z.number(), closed: z.number() }), annotations: { readOnlyHint: true }, }) export class TicketStats extends ToolContext { async execute() { return { open: 12, closed: 40 }; } } ``` ### Listing a union result Use a discriminator when each result kind has different fields. The listed schema describes both outcomes: Initial call configuration: ```js { tool: "lookup_ticket", arguments: { id: "T-1" } } ``` ```ts lookup.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "lookup_ticket", inputSchema: { id: z.string() }, outputSchema: z.discriminatedUnion("kind", [ z.object({ kind: z.literal("found"), title: z.string() }).meta({ id: "FoundTicket" }), z.object({ kind: z.literal("missing"), id: z.string() }).meta({ id: "MissingTicket" }), ]), output: { schemaMode: "both" }, }) export class LookupTicket extends ToolContext { async execute({ id }: { id: string }) { return id === "T-1" ? { kind: "found" as const, title: "Cannot log in" } : { kind: "missing" as const, id }; } } ``` ```ts union.test.ts import { test, expect } from "@frontmcp/testing"; test("tools/list advertises both object members and summarizes each", async ({ mcp }) => { const tool = (await mcp.tools.list()).find((t) => t.name === "lookup_ticket")!; expect(tool.outputSchema).toMatchObject({ type: "object" }); expect((tool.outputSchema as any).oneOf).toHaveLength(2); expect((tool.outputSchema as any).$defs).toHaveProperty("FoundTicket"); expect(tool.description).toContain("**Returns** one of:"); }); test("both result kinds match the declared union", async ({ mcp }) => { expect((await mcp.tools.call("lookup_ticket", { id: "T-1" })).json()).toEqual({ kind: "found", title: "Cannot log in" }); expect((await mcp.tools.call("lookup_ticket", { id: "T-9" })).json()).toEqual({ kind: "missing", id: "T-9" }); }); ``` `z.union()` chooses its first matching member. Put the widest matching member first, or use a discriminated union as above, so fields declared only by a later member aren't dropped. ### Choosing what happens to undeclared keys Here the app keeps extra keys for a plugin's tool, while individual tools override the app with `"strip"`, `"warn"` and `"fail"`: Initial call configuration: ```js { tool: "keep_ticket", arguments: {} } ``` ```ts main.ts active import { App, DynamicPlugin, Plugin, Tool, ToolContext, z } from "@frontmcp/sdk"; const schema = { id: z.string() }; const answer = () => ({ id: "T-1", category: "billing" }); @Tool({ name: "keep_ticket", inputSchema: {}, outputSchema: schema }) class KeepTicket extends ToolContext { async execute() { return answer(); } } @Tool({ name: "strip_ticket", inputSchema: {}, outputSchema: schema, output: { undeclaredKeys: "strip" } }) class StripTicket extends ToolContext { async execute() { return answer(); } } @Tool({ name: "warn_ticket", inputSchema: {}, outputSchema: schema, output: { undeclaredKeys: "warn" } }) class WarnTicket extends ToolContext { async execute() { return answer(); } } @Tool({ name: "fail_ticket", inputSchema: {}, outputSchema: schema, output: { undeclaredKeys: "fail" } }) class FailTicket extends ToolContext { async execute() { return answer(); } } @Plugin({ name: "ticket-export", tools: [KeepTicket] }) class TicketExport extends DynamicPlugin {} @App({ name: "Help Desk", plugins: [TicketExport], tools: [StripTicket, WarnTicket, FailTicket], output: { undeclaredKeys: "keep" }, }) export class HelpDeskApp {} ``` ```ts keys.test.ts import { test, expect } from "@frontmcp/testing"; test("a plugin tool inherits keep from its app, in text and structured output", async ({ mcp }) => { const result = await mcp.tools.call("keep_ticket", {}); expect(result.json()).toEqual({ id: "T-1", category: "billing" }); expect(result.raw.structuredContent).toEqual(result.json()); const tool = (await mcp.tools.list()).find((t) => t.name === "keep_ticket")!; expect(tool.outputSchema).not.toHaveProperty("additionalProperties"); }); test("strip and warn send declared keys only", async ({ mcp }) => { for (const name of ["strip_ticket", "warn_ticket"]) { expect((await mcp.tools.call(name, {})).json()).toEqual({ id: "T-1" }); } }); test("fail refuses the answer and names the dropped key in development", async ({ mcp }) => { const result = await mcp.tools.call("fail_ticket", {}); expect(result).toBeError("INVALID_OUTPUT"); expect(result.text()).toContain("category"); }); ``` `"keep"` fails with `INVALID_OUTPUT` if a key cannot be restored because parsing replaced its containing object with a primitive. To catch missing declarations in tests before a server strips them, use [`toPassOutputSchemaWhole()`](https://frontmcp.dev/reference/testing/matchers#checking-an-answer-before-parsing). ### Returning an error the model can read Call `this.fail()` with a `PublicMcpError`. The call ends, and the client gets an `isError` result with your message, in development and in production. Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-404" } } ``` ```ts get-ticket.tool.ts import { PublicMcpError, Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", description: "Get one support ticket by id", inputSchema: { id: z.string() }, }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { if (id !== "T-1") this.fail(new PublicMcpError(`There's no ticket ${id}.`)); return { id, title: "Cannot log in" }; } } ``` ### Describing side effects with annotations Annotations tell clients how a tool behaves, so they can decide how carefully to confirm a call with the user. They're hints: clients may rely on them, but FrontMCP doesn't enforce them. | Annotation | Meaning when `true` | | --- | --- | | `readOnlyHint` | The tool doesn't change anything. | | `destructiveHint` | The tool may delete or overwrite things. Only meaningful when it isn't read-only. | | `idempotentHint` | Calling it again with the same arguments has no further effect. | | `openWorldHint` | The tool reaches outside systems, like the web, rather than a closed set of data. | ```ts delete-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "delete_ticket", description: "Permanently delete a ticket", inputSchema: { id: z.string() }, annotations: { title: "Delete ticket", destructiveHint: true, idempotentHint: true }, }) export class DeleteTicket extends ToolContext { async execute({ id }: { id: string }) { return { deleted: id }; } } ``` ### Using a provider Get shared services with `this.get()`. Register the provider in the same app's `providers` array. Initial call configuration: ```js { tool: "whoami", arguments: {} } ``` ```ts whoami.tool.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; import { Directory } from "./directory"; @Tool({ name: "whoami", description: "Which support team is on duty", inputSchema: {} }) export class WhoAmI extends ToolContext { async execute() { return this.get(Directory).onDuty(); } } ``` ```ts directory.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "Directory", scope: ProviderScope.GLOBAL }) export class Directory { onDuty() { return { team: "EMEA support", lead: "Nour" }; } } ``` ### Writing a tool as a function For a small tool that doesn't need context, the function form is shorter. It takes the same options. Initial call configuration: ```js { tool: "shout", arguments: { text: "hello" } } ``` ```ts shout.tool.ts import { tool, z } from "@frontmcp/sdk"; export const shout = tool({ name: "shout", description: "Uppercase some text", inputSchema: { text: z.string() }, })(async ({ text }) => text.toUpperCase()); ``` ### Keeping an old tool name callable List the current name once, and keep an old integration working through `aliases`. Aliases also use the tool's authorization and availability checks. New in 1.11.0. Initial call configuration: ```js { tool: "find_ticket", arguments: { id: "T-1" } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "get_ticket", aliases: ["find_ticket"], inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return { id }; } } ``` ```ts alias.test.ts import { test, expect } from "@frontmcp/testing"; test("the alias calls the tool but is not listed", async ({ mcp }) => { expect((await mcp.tools.list()).map((tool) => tool.name)).toEqual(["get_ticket"]); expect((await mcp.tools.call("find_ticket", { id: "T-1" })).json()).toEqual({ id: "T-1" }); }); ``` ### Changing availability while the server runs `enabled` turns a tool on and off while the server runs. It is independent of `availableWhen`: both must allow the call. An off tool is left out of `tools/list`, and a call to it is refused with `FEATURE_OFF` and a remedy. New in 1.11.0. Initial call configuration: ```js { tool: "export_tickets", arguments: {} } ``` ```ts tools.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "export_tickets", inputSchema: {}, enabled: false }) export class ExportTickets extends ToolContext { async execute() { return { rows: 12 }; } } ``` ```ts enabled.test.ts import { test, expect } from "@frontmcp/testing"; test("an off tool is omitted and its call is refused", async ({ mcp }) => { expect(await mcp.tools.list()).toEqual([]); expect(await mcp.tools.call("export_tickets", {})).toBeError("FEATURE_OFF"); }); ``` For a switch that changes while sessions are live, pass an `EnabledSource`: `get(context?)` answers for each request, and `subscribe(listener)` calls `listener` when the answer may have changed and returns the function that stops it. A source that throws counts as off, and its optional `remedy` goes with the `FEATURE_OFF` refusal. [`fileSignal()`](https://frontmcp.dev/reference/sdk/tool#filesignalpath-key-options) is a source backed by a JSON file on Node. When a source changes, FrontMCP sends each connected client one `notifications/tools/list_changed` for the burst. `tools/list` results carry `_meta["frontmcp/surface"]`, a hash of the names the list shows. When the tool list has changed since a client with a session, such as a [`connect()`](https://frontmcp.dev/reference/sdk/connect) client, last read it, that client's call to a tool missing from the new list gets `STALE_TOOL_LIST` once, with another `notifications/tools/list_changed`; calling an off tool again gets `FEATURE_OFF`. A 2026-07-28 request has no session, so it gets `FEATURE_OFF` at once, as the Playground's client does. ```ts reviews.ts active import { App, Tool, ToolContext, type EnabledSource } from "@frontmcp/sdk"; let reviewsOn = true; const listeners = new Set<() => void>(); export const reviews: EnabledSource = { get: () => reviewsOn, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, remedy: { say: "Turn on Reviews in Settings" }, }; export function setReviews(on: boolean) { reviewsOn = on; for (const listener of [...listeners]) listener(); } @Tool({ name: "list_reviews", description: "List ticket reviews", inputSchema: {}, enabled: reviews }) class ListReviews extends ToolContext { async execute() { return { reviews: ["R-1"] }; } } @App({ name: "Help Desk", tools: [ListReviews] }) export class HelpDesk {} export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] }; ``` ```ts reviews.test.ts import { test, expect } from "@frontmcp/testing"; import { connect } from "@frontmcp/sdk"; import { config, setReviews } from "./reviews"; const settle = () => new Promise((resolve) => setTimeout(resolve, 200)); test("a session hears the change, then gets STALE_TOOL_LIST once", async () => { setReviews(true); const client = await connect(config); const heard: string[] = []; client.onNotification((notification: { method: string }) => { heard.push(notification.method); }); try { expect(((await client.listTools()) as { name: string }[]).map((tool) => tool.name)).toEqual(["list_reviews"]); setReviews(false); await settle(); expect(heard).toEqual(["notifications/tools/list_changed"]); expect(await client.callTool("list_reviews", {})).toMatchObject({ isError: true, _meta: { code: "STALE_TOOL_LIST" } }); expect(await client.callTool("list_reviews", {})).toMatchObject({ isError: true, _meta: { code: "FEATURE_OFF", remedy: { say: "Turn on Reviews in Settings" } }, }); expect(await client.listTools()).toEqual([]); } finally { setReviews(true); await client.close(); } }); test("a 2026-07-28 request gets FEATURE_OFF with the source's remedy", async ({ mcp }) => { setReviews(false); try { expect(await mcp.tools.list()).toEqual([]); const result = await mcp.tools.call("list_reviews", {}); expect(result).toBeError("FEATURE_OFF"); expect(result.text()).toBe('Tool "list_reviews" is turned off\nTo fix: Turn on Reviews in Settings'); } finally { setReviews(true); } expect((await mcp.tools.list()).map((tool) => tool.name)).toEqual(["list_reviews"]); }); ``` > **Note** > > `fileSignal()` reads a file, so it has no Playground: the Playground runs in your browser, with no file system. On Node, `@Tool({ enabled: fileSignal("./features.json", "reviews") })` turns the tool on when `features.json` holds `{ "reviews": true }`. ### Fitting an answer to a budget `output.budget` applies at tool, app or server level, in that order. It defaults to off; `false` disables an inherited budget. `maxBytes` is a whole number of at least 1024 bytes. `lists` keeps the last items (`"keep-newest"`, the default), or the first (`"keep-oldest"`). Each copy of the data, text and structured content, gets the budget separately. FrontMCP leaves out whole items or string endings and records omissions in `_meta["frontmcp/budget"]` and a text note. When `tools/list` advertises the tool's `outputSchema` (`schemaMode` `"definition"` or `"both"`, with an object schema) and the caller's [client profile](https://frontmcp.dev/reference/sdk/frontmcp#client-profiles) doesn't limit it to text, a cut that would break the schema is not made: the answer goes whole, and the server warns once for that tool. Otherwise the shortened answer is sent. The budget applies to calls from clients, not to in-process calls such as [`this.callTool()`](https://frontmcp.dev/reference/sdk/call-tool). New in 1.11.0. Initial call configuration: ```js { tool: "ticket_history", arguments: {} } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "ticket_history", inputSchema: {}, outputSchema: { events: z.array(z.string()) }, output: { budget: { maxBytes: 1024, lists: "keep-newest" } }, }) export class TicketHistory extends ToolContext { async execute() { return { events: Array.from({ length: 100 }, (_, i) => `${i}: ${"note ".repeat(20)}`) }; } } ``` ```ts budget.test.ts import { test, expect } from "@frontmcp/testing"; test("the answer keeps fewer events and describes the omissions", async ({ mcp }) => { const result = await mcp.tools.call("ticket_history", {}); expect(result).toBeSuccessful(); expect(result.raw._meta?.["frontmcp/budget"]).toBeDefined(); expect((result.raw.structuredContent as any).events.length).toBeLessThan(100); }); ``` ### Checking literal outputs Literal `outputSchema` types validate the value, and `"string"`, `"number"`, `"boolean"` and `"date"` advertise an object schema wrapping the value in `content`. Dates are sent as ISO 8601. Media literals require valid MCP blocks; a bad block fails with `INVALID_OUTPUT` instead of disappearing. Changed in 1.11.3: before, literal outputs were not checked or advertised, and dates used the server's local date string. ```ts outputs.ts active import { Tool, ToolContext } from "@frontmcp/sdk"; @Tool({ name: "bad_count", inputSchema: {}, outputSchema: "number" }) export class BadCount extends ToolContext { async execute(): Promise { return "five"; } } @Tool({ name: "report_date", inputSchema: {}, outputSchema: "date" }) export class ReportDate extends ToolContext { async execute() { return new Date("2026-11-09T12:30:00.000Z"); } } @Tool({ name: "nonfinite_count", inputSchema: {}, output: { allowNonFinite: true } }) export class NonfiniteCount extends ToolContext { async execute() { return { value: Infinity }; } } ``` ```ts outputs.test.ts import { test, expect } from "@frontmcp/testing"; test("a number literal refuses text", async ({ mcp }) => { expect(await mcp.tools.call("bad_count", {})).toBeError("INVALID_OUTPUT"); }); test("a date is ISO 8601 and has a listed output schema", async ({ mcp }) => { const result = await mcp.tools.call("report_date", {}); expect(result.text()).toBe("2026-11-09T12:30:00.000Z"); expect((await mcp.tools.list()).find((t) => t.name === "report_date").outputSchema).toBeDefined(); }); test("the tool's allowNonFinite setting applies", async ({ mcp }) => { expect((await mcp.tools.call("nonfinite_count", {})).json()).toEqual({ value: null }); }); ``` --- ## Troubleshooting ### `Tool alias conflict` The server didn't start: `ToolAliasConflictError` (`TOOL_ALIAS_CONFLICT`) names each alias that two tools declare, or that is also a tool's name. Give each alias to one tool, and never use a tool's name as one. ### `Tool "…" is not in the current tool list; this session's tool list is out of date` `STALE_TOOL_LIST` means the tool list changed since this session last read it, and the tool it called isn't in the new one. The server sends `notifications/tools/list_changed` with it. Call `tools/list` again, then call a tool from the new list. Calling the same tool again gets `FEATURE_OFF` with its remedy while it stays off. See [Changing availability while the server runs](https://frontmcp.dev/reference/sdk/tool#changing-availability-while-the-server-runs). ### `Tool "…": tools/list leaves out its outputSchema because …` The schema cannot be advertised as an object or a union of objects. Use an object wrapper for an array or primitive result, or inspect the named conversion failure. A transform has no JSON Schema representation. Set `output.schemaMode: "none"` only when you intend to hide the schema. ### `Tool "…" answered with keys its outputSchema does not declare, so they were stripped: …` The undeclared-key policy is `"warn"`, the development default. Declare the named fields, or return only the fields you intend to expose. Set `"keep"` to send them or `"fail"` to refuse such answers. UI rendering and transform schemas keep their parsing rules; see [Output policy](https://frontmcp.dev/reference/sdk/tool#output-policy). ### My tool doesn't show up in `tools/list` Check, in order: 1. The class is in its app's `tools` array, and the app is in `@FrontMcp({ apps })`. 2. `tsconfig.json` sets `experimentalDecorators` and `emitDecoratorMetadata` to `true`. 3. `import "reflect-metadata"` is the first line of your entry file. 4. The tool doesn't set `visibility: "hidden"` or `"internal"`, and its `availableWhen` matches the environment. ### TypeScript says `Unable to resolve signature of class decorator` `@Tool` checks the class against its options, and error `TS1238` on the decorator line means a check failed. The rest of the message says which one: - `'execute() parameter error': "Parameter type does not match the input schema."`: `execute()`'s parameter type disagrees with `inputSchema`. `"Parameter type is too wide"` means it allows more than the schema, like `limit?: number` for a field with `.default()`. - `'execute() return type error'`: with an `outputSchema`, `execute()` returns something that doesn't match it, or `any`. A complete `CallToolResult`, with `content`, is accepted too: FrontMCP sends it as it is, without checking it against `outputSchema`. (Changed in 1.11.1: before, a `CallToolResult` failed this check.) - `'Tool class error': "Class must extend ToolContext"`: the class doesn't extend `ToolContext`. The message also shows `expected_input_type` or `expected_output_type`, the type to use: ```ts // 🚩 inputSchema says string, execute says number @Tool({ name: "get_ticket", inputSchema: { id: z.string() } }) class GetTicket extends ToolContext { async execute(input: { id: number }) { /* ... */ } } // ✅ The types match @Tool({ name: "get_ticket", inputSchema: { id: z.string() } }) class GetTicket extends ToolContext { async execute(input: { id: string }) { /* ... */ } } ``` ### The client sees "Internal FrontMCP error" instead of my message In production, FrontMCP hides the message of any error that isn't a `PublicMcpError`, like a plain `Error` thrown from `execute()`, so internals don't leak. The client gets an error ID, and FrontMCP logs the same ID with the original message and stack. If the model should see the message, fail with `this.fail(new PublicMcpError("..."))` instead. ### Calls fail with `INVALID_OUTPUT` The result didn't match `outputSchema`, so nothing from it was sent. In development the text names the first field that didn't match; in production it's only "Output validation failed. Please contact support." A `NaN` or `Infinity` in a number field fails the same way, with or without an `outputSchema`, because JSON can't carry it. Initial call configuration: ```js { tool: "ticket_stats", arguments: {} } ``` ```ts ticket-stats.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; @Tool({ name: "ticket_stats", description: "Count open and closed tickets", inputSchema: {}, outputSchema: z.object({ open: z.number(), closed: z.number() }), }) export class TicketStats extends ToolContext { async execute() { const counts: Record = { open: 12, pending: 3 }; // no "closed" today return { open: counts.open, closed: counts.closed }; } } ``` ```ts ticket-stats.test.ts import { test, expect } from "@frontmcp/testing"; test("a missing field fails the call", async ({ mcp }) => { const result = await mcp.tools.call("ticket_stats", {}); expect(result.raw._meta?.code).toBe("INVALID_OUTPUT"); expect(result.text()).toBe("Tool output validation failed (output does not match outputSchema at closed)"); }); ``` Fix the result, or change `outputSchema` if the result is right. Here, `counts.closed ?? 0` would do. ### Calls fail with "Invalid tool input" The arguments didn't match `inputSchema`, so `execute()` never ran. The result text lists each problem with the field's path. If a model keeps sending bad arguments, the schema probably isn't telling it enough: add `.describe()` notes, and prefer `z.enum()` over free text where you can. ### Calls fail with error `-32001` and an `authUrl` The tool lists a required entry in `authProviders`, and the user hasn't connected that credential yet. `execute()` doesn't run. Send the user to `authUrl` to connect it, or mark the provider `required: false` if the tool can work without it. With `signInRequired: true` in the error's `data` instead, the caller isn't signed in: sign in to the server first, then call the tool again for a link. Without either, no credential provider or vault has one for this caller: see [`this.authProviders`](https://frontmcp.dev/reference/sdk/auth-providers#tool--requires-credentials-for--which-are-not-connected-for-this-session-please-authorize-the-required-providers-and-retry). --- # @Resource > Declare data at a fixed URI that clients can list and read, like a policy document or a settings file. Source: https://frontmcp.dev/reference/sdk/resource [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@Resource` declares an MCP [resource](https://frontmcp.dev/learn/exposing-data-with-resources): data at a fixed URI, like `policy://sla`, that a client can list and read. The client application decides when to read it, usually to attach it to a conversation. For a family of URIs that share a pattern, like `ticket://{id}`, use [`@ResourceTemplate`](https://frontmcp.dev/reference/sdk/resource-template). ```ts @Resource(options) class MyResource extends ResourceContext { async execute(uri) { /* ... */ } } ``` --- ## Reference ### `@Resource(options)` Apply `@Resource` to a class that extends `ResourceContext`, and list the class in an app's `resources` array. ```ts sla.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "sla", uri: "policy://sla", description: "How fast the help desk replies, by ticket priority", mimeType: "application/json", }) class SlaPolicy extends ResourceContext { async execute() { return { high: "4 hours", normal: "1 business day", low: "3 business days" }; } } ``` [See more examples below.](https://frontmcp.dev/reference/sdk/resource#usage) #### Options Required: | Option | Type | Description | | --- | --- | --- | | `name` | `string` | Identifies the resource. Unique within the server. | | `uri` | `string` | The address clients read. It must start with a scheme and `://`, like `policy://sla` or `file:///docs/faq.md`. | Optional: | Option | Type | Description | | --- | --- | --- | | `enabled` | `EnabledOption` | Optional; defaults to on. A boolean or `{ get(context?), subscribe(listener), remedy? }`. Off entries are omitted from lists and refused with `FEATURE_OFF`. Changes announce `list_changed`. See [live availability](https://frontmcp.dev/reference/sdk/tool#changing-availability-while-the-server-runs). | | `from` | `ResourceKey` | Optional. A key from `resourceStore()`; writes announce resource updates. Extend `MaterializedResourceContext` to serve the value and its revision. | | `worker` | `boolean \| { budgetMs?: number }` | Optional; off by default. Runs the resource's reads in the [offload pool](https://frontmcp.dev/reference/sdk/offload), on Node; the budget defaults to the server's `offload.budgetMs`, 30000 ms unless set. | | `title` | `string` | A display name for people. Clients show it instead of `name`. | | `description` | `string` | What the data is and when it's useful. Clients and models read it in `resources/list`. | | `mimeType` | `string` | The content type, like `application/json`. Listed in `resources/list`, and used for the content blocks FrontMCP builds from what `execute()` returns. Without it, FrontMCP picks one per block. Blocks you return in `{ contents }` are sent as they are. | | `icons` | `Icon[]` | Images clients can show: `src`, and optionally `mimeType`, `sizes` and `theme` (`"light"` or `"dark"`). | | `annotations` | `ResourceAnnotations` | Hints for clients: `audience` (`["user"]`, `["assistant"]` or both), `priority` (from 0 to 1) and `lastModified` (an ISO 8601 date). | | `_meta` | `Record` | Extra metadata, sent as is in `resources/list`. Use reverse-DNS keys, like `com.example/owner`. | | `availableWhen` | `EntryAvailability` | Only offer the resource on certain platforms, runtimes or deployments. Elsewhere it isn't listed, and reading it fails with [`-32003`](https://frontmcp.dev/reference/sdk/resource#reads-fail-with--32003-resource--is-not-available-in-the-current-environment). See [Environment awareness](https://frontmcp.dev/reference/server/environment). | #### `execute(uri, params)` FrontMCP calls `execute()` every time a client reads the resource. - `uri`: the URI that was read. For a `@Resource`, that's always its `uri` option. - `params`: template parameters. Always `{}` for a `@Resource`. - **Returns** the content. FrontMCP turns it into the `contents` array of the `resources/read` result: | `execute()` returns | The client receives | | --- | --- | | An object or number, like `{ high: "4 hours" }` | One text block with the value as JSON. MIME type `application/json`. | | A string | One text block. The MIME type comes from the URI's extension (`.md` is `text/markdown`) or the text itself, and is `text/plain` otherwise. | | A `Uint8Array` or `Buffer` | One `blob` block, base64-encoded. MIME type `application/octet-stream`, unless you set `mimeType`. | | An object with a `text` or `blob` string | That block, with the resource's URI. | | An array | One block per item, converted as above. Items without their own `uri` get `#0`, `#1`… appended to the resource's URI. | | `{ contents: [...] }` | Exactly those blocks. Use this for full control. | Inside `execute()`, `this` is the `ResourceContext`: `this.uri` and `this.params` hold the same values as the arguments, `this.get()` returns [providers](https://frontmcp.dev/reference/sdk/provider), `this.fetch()` makes outbound HTTP requests, `this.context` and `this.auth` describe the request and the caller, and `this.notifyUpdated()` tells subscribed clients that the content changed. `this.notify()`, `this.progress()` and `this.elicit()` belong to tools, not resources. #### `resource(options)(handler)` The function form takes the same options. The handler receives `(uri, params)` and returns a `ReadResourceResult`, the `{ contents: [...] }` shape. #### Caveats - The class **must extend `ResourceContext`**. Using `@Resource` on any other class is a compile error. - `uri` **must have a scheme followed by `://`**. Otherwise the server doesn't start, and reports "URI must have a valid scheme". - Reads match the URI **exactly**. `policy://sla/` and `policy://SLA` are different URIs, and reading them fails with "Resource not found". - A resource takes no arguments. For data that depends on an id, use [`@ResourceTemplate`](https://frontmcp.dev/reference/sdk/resource-template). If a resource and a template both match a URI, the resource wins. - If `execute()` throws `ResourceNotFoundError(uri)`, the client gets the same error as for a URI that matches nothing: `-32602`, `Resource not found: …`. A `PublicMcpError` also gives `-32602`, with your error's message as the whole message. - Any other error is an internal one: JSON-RPC error `-32603`, with `Resource "…" read failed:` and your error's message in development. With `NODE_ENV=production`, FrontMCP hides the message and sends `Internal FrontMCP error. Please contact support with error ID: …` instead. See [troubleshooting](https://frontmcp.dev/reference/sdk/resource#reads-fail-with--32603-resource--read-failed). - `this.fail(error)` fails the read the same way as `throw error` for a `PublicMcpError`. For any other error it's still `-32603`, but the message is your error's message without the `read failed:` prefix, and `data.code` is `SERVER_ERROR` instead of `RESOURCE_READ_ERROR`. Production hides it the same way. ### `resourceStore(options?)` Creates a store of values with revisions, which [`@Resource({ from })`](https://frontmcp.dev/reference/sdk/resource#serving-a-stored-value) serves. `store.key(name, { initial? })` returns a key: `get()`, `set(value)`, `update(change)` and `subscribe(listener)`. The store's own `subscribe(topic, listener)` and `publish(topic)` follow the change feed, where a key's topic is its name; an [`sse` route](https://frontmcp.dev/reference/sdk/http-route#streaming-a-live-view) listens there. New in 1.11.0. | Option | Type | Default | Description | | --- | --- | --- | --- | | `storage` | `StorageConfig` with type `"memory"`, `"redis"` or `"sqlite"` | memory | Backend with atomic compare-and-set. Redis and SQLite share values and changes between processes. | | `pollIntervalMs` | `number` | `250` | Positive whole milliseconds between SQLite change checks. | | `coalesceMs` | `number` | `50` | Nonnegative whole milliseconds in which writes to a key produce one announcement. | | `onError` | `(error: unknown) => void` | none | Receives failed polls, subscriptions, announcements and listeners. | --- ## Usage ### Exposing data at a fixed URI Give the resource a URI with your own scheme and a description that says what's in it. Return a plain object and FrontMCP sends it as JSON. Initial call configuration: ```js { resource: "policy://sla" } ``` ```ts sla.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "sla", title: "Reply-time policy", uri: "policy://sla", description: "How fast the help desk replies, by ticket priority. Read it before promising a customer a reply time.", }) export class SlaPolicy extends ResourceContext { async execute() { return { high: "4 hours", normal: "1 business day", low: "3 business days" }; } } ``` Open the **Capabilities** tab to see the resource as `resources/list` describes it. Clients read it with `resources/read` and the URI. ### Choosing what the client receives What `execute()` returns decides the content blocks and their MIME types. ### Content types ### Example: Text A string becomes one text block. The URI ends in `.md`, so the MIME type is `text/markdown`. Initial call configuration: ```js { resource: "guide://replies.md" } ``` ```ts replies.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "reply-guide", uri: "guide://replies.md", description: "How to word replies to customers" }) export class ReplyGuide extends ResourceContext { async execute() { return "# Replying to customers\n\n- Greet them by name.\n- Say what you did, then what happens next.\n- Link the ticket id, like T-1."; } } ``` ### Example: Full control Return `{ contents }` to set every field yourself, here a CSV export. Initial call configuration: ```js { resource: "export://tickets/open.csv" } ``` ```ts export.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "open-tickets-csv", uri: "export://tickets/open.csv", description: "Open tickets as CSV" }) export class OpenTicketsCsv extends ResourceContext { async execute(uri: string) { const csv = "id,title,priority\nT-1,Cannot log in,high\nT-3,Login link expired,normal"; return { contents: [{ uri, mimeType: "text/csv", text: csv }] }; } } ``` ### Example: Binary Bytes arrive base64-encoded in `blob`. Set `mimeType`, or clients get `application/octet-stream`. Initial call configuration: ```js { resource: "brand://logo.png" } ``` ```ts logo.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; // The first bytes of a PNG file, to keep the example short. const png = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); @Resource({ name: "logo", uri: "brand://logo.png", mimeType: "image/png", description: "The help desk logo" }) export class Logo extends ResourceContext { async execute() { return png; } } ``` ### Example: Several blocks Return an array for several blocks. Blocks without a `uri` get `#0`, `#1`… after the resource's URI. Initial call configuration: ```js { resource: "policy://handbook" } ``` ```ts handbook.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "handbook", uri: "policy://handbook", description: "The support handbook, one block per section" }) export class Handbook extends ResourceContext { async execute(uri: string) { return [ { text: "Escalate high-priority tickets after 2 hours.", mimeType: "text/plain" }, { uri: `${uri}#hours`, mimeType: "application/json", text: JSON.stringify({ open: "08:00", close: "18:00" }) }, ]; } } ``` ### Reading from a provider Get shared services with `this.get()`, and register the provider in the same app's `providers` array. Initial call configuration: ```js { resource: "desk://on-duty" } ``` ```ts on-duty.resource.ts active import { Resource, ResourceContext } from "@frontmcp/sdk"; import { Rota } from "./rota"; @Resource({ name: "on-duty", uri: "desk://on-duty", description: "Which agents are on duty right now" }) export class OnDuty extends ResourceContext { async execute() { return { agents: this.get(Rota).onDuty() }; } } ``` ```ts rota.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "Rota", scope: ProviderScope.GLOBAL }) export class Rota { onDuty() { return ["Nour", "Sam"]; } } ``` ### Describing a resource for clients Everything except `availableWhen` goes out in `resources/list`. Clients use `title` and `icons` for display, and `annotations` to decide who the content is for and how prominent it should be. The test below reads the list the way a client would. ```ts sla.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "sla", title: "Reply-time policy", uri: "policy://sla", description: "How fast the help desk replies, by ticket priority", mimeType: "application/json", annotations: { audience: ["assistant"], priority: 0.8, lastModified: "2026-09-01T09:00:00Z" }, _meta: { "com.example/owner": "support-ops" }, }) export class SlaPolicy extends ResourceContext { async execute() { return { high: "4 hours", normal: "1 business day", low: "3 business days" }; } } ``` ```ts sla.test.ts import { test, expect } from "@frontmcp/testing"; test("resources/list describes the policy", async ({ mcp }) => { const resources = await mcp.resources.list(); expect(resources).toContainResource("policy://sla"); expect(resources[0]).toMatchObject({ name: "sla", title: "Reply-time policy", mimeType: "application/json", annotations: { audience: ["assistant"], priority: 0.8 }, _meta: { "com.example/owner": "support-ops" }, }); }); test("reading it returns JSON", async ({ mcp }) => { const content = await mcp.resources.read("policy://sla"); expect(content).toHaveMimeType("application/json"); expect(content.json()).toEqual({ high: "4 hours", normal: "1 business day", low: "3 business days" }); }); ``` ### Writing a resource as a function For a resource that doesn't need context, the function form is shorter. Its handler returns the full `{ contents }` shape, which is sent as it is, so set each block's `mimeType` there. Initial call configuration: ```js { resource: "policy://hours" } ``` ```ts hours.resource.ts import { resource } from "@frontmcp/sdk"; export const openingHours = resource({ name: "opening-hours", uri: "policy://hours", mimeType: "application/json", description: "When the help desk answers tickets", })((uri) => ({ contents: [{ uri, mimeType: "application/json", text: JSON.stringify({ weekdays: "08:00-18:00", weekends: "closed" }) }], })); ``` ### Serving a stored value A materialized resource serves a value that tools or another process write. The store uses memory by default; `storage` also takes a Redis or SQLite configuration for `createStorage()`. Memory, Redis and SQLite are the backends with the atomic compare-and-set its writes need. Redis and SQLite are refused in a browser. `pollIntervalMs` defaults to 250 for SQLite change checks; `coalesceMs` defaults to 50 for update announcements; `onError(error)` receives feed failures. New in 1.11.0. `key(name, { initial })` starts at revision 0. `get()`, `set(value)` and `update(change)` return `{ value, revision, updatedAt? }`. Each write increments the revision. Keep `change` pure: a concurrent write can make it run again. Values are JSON copies. `subscribe(listener)` returns a function that stops listening. Initial call configuration: ```js { resource: "desk://board" } ``` ```ts board.ts active import { MaterializedResourceContext, Resource, resourceStore, Tool, ToolContext } from "@frontmcp/sdk"; export const store = resourceStore(); export const board = store.key("board", { initial: { open: 2 } }); @Resource({ name: "board", uri: "desk://board", from: board }) export class Board extends MaterializedResourceContext {} @Tool({ name: "close_ticket", inputSchema: {} }) export class CloseTicket extends ToolContext { async execute() { return (await board.update((current) => ({ open: current.open - 1 }))).value; } } ``` ```ts board.test.ts import { test, expect } from "@frontmcp/testing"; import { board } from "./board"; test("a write changes the served value and increments its revision", async ({ mcp }) => { const before = await board.get(); await mcp.tools.call("close_ticket", {}); const result = await mcp.resources.read("desk://board"); expect(result.json()).toEqual({ open: before.value.open - 1 }); expect((await board.get()).revision).toBe(before.revision + 1); }); ``` Resource reads also inherit the app's `output.budget`, then the server's, when set. UI widget resources are never cut. Reads include `_meta["frontmcp/materialized"]` with the revision and write time. Access to a `ResourceKey` in your code can write it, so the store itself is not an authorization boundary. Custom stores should pair `connect()` with `close()`; the server manages these for its resources. ### Telling subscribers about a write A write to a materialized resource's key announces its URI: clients subscribed to it get `notifications/resources/updated`, also for a write from another process that shares a Redis or SQLite store. A subscription is refused as a read would be, including by the resource's `authorities`. Changed in 1.11.0: before, `resources/subscribe` didn't check the resource's `authorities`, and `subscriptions/listen` acknowledged every URI it was asked for. Now `resources/subscribe` refuses a caller the rule refuses, `subscriptions/listen` acknowledges only the URIs the caller may read, and it checks access again for an update to a resource under an acknowledged URI. ```ts board.ts active import { App, FrontMcp, MaterializedResourceContext, Resource, resourceStore } from "@frontmcp/sdk"; export const store = resourceStore(); export const board = store.key("board", { initial: { open: 2 } }); @Resource({ name: "board", uri: "desk://board", from: board, authorities: { roles: { any: ["agent"] } } }) class Board extends MaterializedResourceContext {} @App({ name: "Desk", resources: [Board] }) class Desk {} export const config = { info: { name: "desk", version: "1.0.0" }, apps: [Desk], authorities: { claimsMapping: { roles: "roles" } }, }; @FrontMcp(config) export default class Server {} ``` ```ts subscribe.test.ts import { test, expect } from "@frontmcp/testing"; import { connect } from "@frontmcp/sdk"; import { board, config } from "./board"; const settle = () => new Promise((resolve) => setTimeout(resolve, 200)); test("an agent hears of the write, and a customer can't subscribe", async () => { const agent = await connect(config, { session: { user: { sub: "nour", roles: ["agent"] } } }); const customer = await connect(config, { session: { user: { sub: "sam" } } }); const updated: unknown[] = []; agent.onResourceUpdated((uri: unknown) => { updated.push(uri); }); try { await agent.subscribeResource("desk://board"); await expect(customer.subscribeResource("desk://board")).rejects.toMatchObject({ code: -32003 }); const { value } = await board.update((current) => ({ open: current.open - 1 })); await settle(); expect(updated).toEqual(["desk://board"]); expect((await agent.readResource("desk://board")).contents[0]).toMatchObject({ text: JSON.stringify(value) }); } finally { await agent.close(); await customer.close(); } }); ``` --- ## Troubleshooting ### The server doesn't start: "URI must have a valid scheme" The `uri` option needs a scheme followed by `://`. `policy:sla` and `/policy/sla` are rejected; `policy://sla` works. ### `Resource output validation failed (…)` The resource returned content the protocol cannot serve. The `INVALID_OUTPUT` development message includes the validation reason. Production hides it. Changed in 1.11.3: before, the resource message omitted that reason. ### Reads fail with `-32602` "Resource not found" No resource or template matches the URI exactly, or `execute()` threw `ResourceNotFoundError`. Check for a trailing slash, different letter case, or a typo, and compare with `resources/list`. Under MCP 2026-07-28 this error has code `-32602`; earlier protocol versions use `-32002`. A resource whose `availableWhen.surface` leaves out `"mcp"` gets the same answer: MCP clients can't read it. Initial call configuration: ```js { resource: "policy://SLA" } ``` ```ts sla.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "sla", uri: "policy://sla" }) export class SlaPolicy extends ResourceContext { async execute() { return { high: "4 hours" }; } } ``` ### Reads fail with `-32603` "Resource … read failed" `execute()` threw an error that isn't a `PublicMcpError`, so FrontMCP treats it as a failure of the server. In development, the message after `read failed:` is your error's message: Initial call configuration: ```js { resource: "policy://sla" } ``` ```ts sla.resource.ts import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "sla", uri: "policy://sla" }) export class SlaPolicy extends ResourceContext { async execute(): Promise { // 🚩 A server failure, and production hides the message throw new Error("The SLA policy hasn't been published yet"); } } ``` With `NODE_ENV=production`, the client only gets `Internal FrontMCP error. Please contact support with error ID: …`. If the client should read the message, throw a `PublicMcpError`. The read then fails with `-32602` and your message, in production too: Initial call configuration: ```js { resource: "policy://sla" } ``` ```ts sla.resource.ts active import { PublicMcpError, Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "sla", uri: "policy://sla" }) export class SlaPolicy extends ResourceContext { async execute(): Promise { // ✅ The client sees exactly this message throw new PublicMcpError("The SLA policy hasn't been published yet"); } } ``` ```ts sla.test.ts import { test, expect } from "@frontmcp/testing"; test("the message reaches the client as it was thrown", async ({ mcp }) => { const result = await mcp.resources.read("policy://sla"); expect(result).toBeError(-32602); expect(result.error?.message).toBe("The SLA policy hasn't been published yet"); }); ``` A message ending in `read failed: Resource output not found` means `execute()` returned nothing. Return the content, or end with [`this.respond()`](https://frontmcp.dev/reference/sdk/respond), which works in resources since 1.9.3. ### Reads fail with `-32003` "Resource "…" is not available in the current environment" The resource's `availableWhen` doesn't match where the server runs. It's left out of `resources/list`, and a client that reads it by URI gets this error, with what the resource requires and what the server is: Initial call configuration: ```js { resource: "policy://deno-deploy" } ``` ```ts deploy.resource.ts active import { Resource, ResourceContext } from "@frontmcp/sdk"; @Resource({ name: "deploy-notes", uri: "policy://deno-deploy", mimeType: "text/plain", availableWhen: { runtime: ["deno"] } }) export class DeployNotes extends ResourceContext { async execute() { return "Deploy with deployctl."; } } ``` ```ts deploy.test.ts import { test, expect } from "@frontmcp/testing"; test("it isn't listed, and reading it fails", async ({ mcp }) => { expect(await mcp.resources.list()).toEqual([]); const result = await mcp.resources.read("policy://deno-deploy"); expect(result).toBeError(-32003); expect(result.error?.message).toMatch(/^Resource "policy:\/\/deno-deploy" is not available in the current environment \(requires: \{"runtime":\["deno"\]\}\)/); }); ``` The message lists the server's OS, runtime and deployment, in production too. If the resource should be readable here, fix its `availableWhen`. ### My resource isn't in `resources/list` Check, in order: 1. The class is in its app's `resources` array, and the app is in `@FrontMcp({ apps })`. 2. It's a `@Resource`. Templates are listed separately, in `resources/templates/list`. 3. Its `availableWhen` matches the environment the server runs in. --- # @ResourceTemplate > Declare a family of resources whose URIs follow a pattern, like ticket://{id}, and read the parameters from the URI. Source: https://frontmcp.dev/reference/sdk/resource-template [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@ResourceTemplate` declares a family of MCP [resources](https://frontmcp.dev/learn/exposing-data-with-resources) that share a URI pattern, like `ticket://{id}`. Clients fill in the pattern to read one member, such as `ticket://T-1`, and FrontMCP passes the parts it matched to your code. For a single resource at a fixed URI, use [`@Resource`](https://frontmcp.dev/reference/sdk/resource). ```ts @ResourceTemplate(options) class MyTemplate extends ResourceContext { async execute(uri, params) { /* ... */ } } ``` --- ## Reference ### `@ResourceTemplate(options)` Apply `@ResourceTemplate` to a class that extends `ResourceContext`, and list the class in an app's `resources` array, next to static resources. ```ts ticket.resource.ts import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; @ResourceTemplate({ name: "ticket", uriTemplate: "ticket://{id}", description: "One support ticket by id, like ticket://T-1", mimeType: "application/json", }) class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, params: { id: string }) { const ticket = await findTicket(params.id); if (!ticket) throw new ResourceNotFoundError(uri); return ticket; } } ``` [See more examples below.](https://frontmcp.dev/reference/sdk/resource-template#usage) #### Options Required: | Option | Type | Description | | --- | --- | --- | | `name` | `string` | Identifies the template. Unique within the server. | | `uriTemplate` | `string` | The URI pattern, with parameters in braces, like `ticket://{id}`. It must start with a scheme and `://`. See [URI template syntax](https://frontmcp.dev/reference/sdk/resource-template#uri-template-syntax). | Optional: | Option | Type | Description | | --- | --- | --- | | `worker` | `boolean \| { budgetMs?: number }` | Optional; off by default. Runs each read in the [offload pool](https://frontmcp.dev/reference/sdk/offload). | | `enabled` | `EnabledOption` | Optional; defaults to on. A boolean or `{ get(context?), subscribe(listener), remedy? }`. Off entries are omitted from lists and refused with `FEATURE_OFF`. Changes announce `list_changed`. See [live availability](https://frontmcp.dev/reference/sdk/tool#changing-availability-while-the-server-runs). | | `title` | `string` | A display name for people. Clients show it instead of `name`. | | `description` | `string` | What each resource is, and what the parameters mean. Clients and models read it in `resources/templates/list`. | | `mimeType` | `string` | The content type of every matching resource. Listed in `resources/templates/list`, and used for content blocks FrontMCP builds from what `execute()` returns. | | `icons` | `Icon[]` | Images clients can show: `src`, and optionally `mimeType`, `sizes` and `theme`. | | `annotations` | `ResourceAnnotations` | `audience`, `priority` and `lastModified`, as for [`@Resource`](https://frontmcp.dev/reference/sdk/resource#options). Sent in `resources/templates/list`. | | `_meta` | `Record` | Extra metadata. Sent in `resources/templates/list`, like `annotations`. Changed in 1.11.3: before, both were omitted. | | `availableWhen` | `EntryAvailability` | Only offer the template on certain platforms, runtimes or deployments. Elsewhere it isn't in `resources/templates/list`, and reading a URI it matches fails with [`-32003`](https://frontmcp.dev/reference/sdk/resource-template#reads-fail-with--32003-resourcetemplate--is-not-available-in-the-current-environment). See [Environment awareness](https://frontmcp.dev/reference/server/environment). | #### URI template syntax | Pattern | Matches | Example | | --- | --- | --- | | `{name}` | One path segment: anything up to the next `/` | `ticket://{id}` matches `ticket://T-1` with `id` = `"T-1"` | | `{+name}` | One or more segments, slashes included | `kb://{+path}` matches `kb://billing/refunds.md` with `path` = `"billing/refunds.md"` | | Other text | Itself, exactly | `customer://{customer}/tickets` needs the literal `/tickets` | Parameter values are percent-decoded, so reading `note://a%2Fb` from `note://{id}` gives `id` = `"a/b"`. #### `execute(uri, params)` FrontMCP calls `execute()` for each read whose URI matches the template. - `uri`: the URI that was read, like `ticket://T-1`. - `params`: the matched parameters, like `{ id: "T-1" }`. Values are always strings. Type them with `ResourceContext<{ id: string }>`. - **Returns** the content, converted as for [`@Resource`](https://frontmcp.dev/reference/sdk/resource#executeuri-params). Content FrontMCP builds for you is labelled with the URI that was read, like `ticket://T-1`, and a string's MIME type can come from that URI's extension. Blocks you return in `{ contents }` are sent as they are. `this.uri` and `this.params` hold the same values as the arguments. The rest of `this` is the same `ResourceContext` as for `@Resource`. #### Completing parameters Add a method named after a parameter with `Completer` appended, like `idCompleter` for `{id}`. When a client sends `completion/complete` for the template, FrontMCP calls it with what the user has typed so far. ```ts async idCompleter(partial: string) { return { values: ["T-1", "T-12"], total: 2, hasMore: false }; } ``` It returns `values`, and optionally `total` and `hasMore`. Completers can use `this.get()`. To choose a completer at run time instead, override `getArgumentCompleter(name)` and return a function, or `null`. #### `resourceTemplate(options)(handler)` The function form takes the same options. The handler receives `(uri, params)` and returns the `{ contents: [...] }` shape. Function-form templates can't have completers. #### Caveats - The class **must extend `ResourceContext`**. Using `@ResourceTemplate` on any other class is a compile error. - **Parameters are strings, and they aren't validated.** `ticket://anything` matches `ticket://{id}`. Check the value in `execute()`. - A `{name}` parameter **doesn't match `/`**. Use `{+name}` for paths. - If a [`@Resource`](https://frontmcp.dev/reference/sdk/resource) has exactly the URI that was read, it wins over any template. - Templates are listed in `resources/templates/list`, not `resources/list`. - To answer "not found" for parameters that don't point at anything, throw `ResourceNotFoundError(uri)`. The client gets `-32602`, the same error as for a URI no template matches. Other errors fail the read as they do for [`@Resource`](https://frontmcp.dev/reference/sdk/resource#caveats). --- ## Usage ### Reading one item by id Put the id in the URI, and return the item. FrontMCP sends it as JSON, labelled with the URI that was read. Initial call configuration: ```js { resource: "ticket://T-2" } ``` ```ts ticket.resource.ts active import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @ResourceTemplate({ name: "ticket", uriTemplate: "ticket://{id}", description: "One support ticket by id, like ticket://T-1", mimeType: "application/json", }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { return tickets.find((t) => t.id === id); } } ``` ```ts tickets.ts export const tickets = [ { id: "T-1", customer: "acme", title: "Cannot log in", status: "open" }, { id: "T-2", customer: "acme", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", customer: "globex", title: "Login link expired", status: "open" }, ]; ``` In the **Call** tab, pick `ticket://{id}` from the **Request** menu and read any id. The content's `uri` is the one you read. ### Handling an id that doesn't exist Throw `ResourceNotFoundError` with the URI. The client gets a `-32602` error that names it, the same as for a URI that matches no template at all. Initial call configuration: ```js { resource: "ticket://T-9" } ``` ```ts ticket.resource.ts active import { ResourceContext, ResourceNotFoundError, ResourceTemplate } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @ResourceTemplate({ name: "ticket", uriTemplate: "ticket://{id}", mimeType: "application/json" }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new ResourceNotFoundError(uri); return ticket; } } ``` ```ts tickets.ts export const tickets = [ { id: "T-1", title: "Cannot log in", status: "open" }, { id: "T-2", title: "Invoice total is wrong", status: "closed" }, ]; ``` ```ts not-found.test.ts import { test, expect } from "@frontmcp/testing"; test("an unknown id is not found", async ({ mcp }) => { const result = await mcp.resources.read("ticket://T-9"); expect(result).toBeError(-32602); expect(result.error?.message).toBe("Resource not found: ticket://T-9"); }); test("a known id still reads", async ({ mcp }) => { expect((await mcp.resources.read("ticket://T-1")).json()).toMatchObject({ id: "T-1", status: "open" }); }); ``` To send a message of your own instead, like `There's no ticket T-9. Ticket ids look like T-1.`, throw a `PublicMcpError`: the read fails with `-32602` and exactly that message. A plain `Error` is a server failure, `-32603`, and production hides its message. See [`@Resource`](https://frontmcp.dev/reference/sdk/resource#reads-fail-with--32603-resource--read-failed). ### Using several parameters Each `{name}` becomes a key in `params`. Literal text between them has to match exactly. Initial call configuration: ```js { resource: "customer://acme/tickets/open" } ``` ```ts customer-tickets.resource.ts active import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; import { tickets } from "./tickets"; type Params = { customer: string; status: string }; @ResourceTemplate({ name: "customer-tickets", uriTemplate: "customer://{customer}/tickets/{status}", description: "A customer's tickets with one status, open or closed", mimeType: "application/json", }) export class CustomerTickets extends ResourceContext { async execute(uri: string, { customer, status }: Params) { const found = tickets.filter((t) => t.customer === customer && t.status === status); return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify({ customer, status, tickets: found }) }] }; } } ``` ```ts tickets.ts export const tickets = [ { id: "T-1", customer: "acme", title: "Cannot log in", status: "open" }, { id: "T-2", customer: "acme", title: "Invoice total is wrong", status: "closed" }, { id: "T-3", customer: "acme", title: "Login link expired", status: "open" }, ]; ``` ### Matching paths with slashes `{name}` stops at the first `/`. Use `{+name}` when a parameter is a path. ### Path parameters ### Example: {+path} matches the whole path Initial call configuration: ```js { resource: "kb://billing/refunds.md" } ``` ```ts kb.resource.ts import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; @ResourceTemplate({ name: "kb-article", uriTemplate: "kb://{+path}", description: "A knowledge-base article by path" }) export class KbArticle extends ResourceContext<{ path: string }> { async execute(uri: string, { path }: { path: string }) { return { contents: [{ uri, mimeType: "text/markdown", text: `# ${path}\n\nRefunds take 5 business days.` }] }; } } ``` ### Example: {path} doesn't match a slash The same read fails with "Resource not found", because `{path}` only matches one segment. Initial call configuration: ```js { resource: "kb://billing/refunds.md" } ``` ```ts kb.resource.ts import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; @ResourceTemplate({ name: "kb-article", uriTemplate: "kb://{path}", description: "A knowledge-base article by path" }) export class KbArticle extends ResourceContext<{ path: string }> { async execute(uri: string, { path }: { path: string }) { return { contents: [{ uri, mimeType: "text/markdown", text: `# ${path}` }] }; } } ``` ### Example: An encoded slash matches {path} A client can percent-encode the slash instead. FrontMCP decodes it, so `path` is `"billing/refunds.md"` again. Initial call configuration: ```js { resource: "kb://billing%2Frefunds.md" } ``` ```ts kb.resource.ts import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; @ResourceTemplate({ name: "kb-article", uriTemplate: "kb://{path}", description: "A knowledge-base article by path" }) export class KbArticle extends ResourceContext<{ path: string }> { async execute(uri: string, { path }: { path: string }) { return { contents: [{ uri, mimeType: "text/markdown", text: `# ${path}` }] }; } } ``` ### Suggesting parameter values Clients can offer suggestions as the user types an id. Add an `idCompleter()` method, and FrontMCP answers `completion/complete` requests for the `{id}` parameter with it. The test sends the request a client would. ```ts ticket.resource.ts active import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; import { tickets } from "./tickets"; @ResourceTemplate({ name: "ticket", uriTemplate: "ticket://{id}", mimeType: "application/json" }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(tickets.find((t) => t.id === id)) }] }; } async idCompleter(partial: string) { const values = tickets.map((t) => t.id).filter((id) => id.startsWith(partial)); return { values, total: values.length }; } } ``` ```ts tickets.ts export const tickets = [ { id: "T-1", title: "Cannot log in" }, { id: "T-2", title: "Invoice total is wrong" }, { id: "T-12", title: "Export times out" }, ]; ``` ```ts complete.test.ts import { test, expect } from "@frontmcp/testing"; test("typing T-1 suggests T-1 and T-12", async ({ mcp }) => { const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "completion/complete", params: { ref: { type: "ref/resource", uri: "ticket://{id}" }, argument: { name: "id", value: "T-1" } }, }); expect(response).toHaveResult(); expect(response.result.completion).toEqual({ values: ["T-1", "T-12"], total: 2 }); }); test("the template is listed", async ({ mcp }) => { expect(await mcp.resources.listTemplates()).toContainResourceTemplate("ticket://{id}"); }); ``` ### Writing a template as a function For a template that doesn't need context, the function form is shorter. Its handler gets the same `(uri, params)` and returns the full `{ contents }` shape. Initial call configuration: ```js { resource: "agent://nour/queue" } ``` ```ts queue.resource.ts import { resourceTemplate } from "@frontmcp/sdk"; export const agentQueue = resourceTemplate({ name: "agent-queue", uriTemplate: "agent://{agent}/queue", description: "The tickets assigned to one support agent", mimeType: "application/json", })((uri, { agent }) => ({ contents: [{ uri, mimeType: "application/json", text: JSON.stringify({ agent, tickets: ["T-1", "T-3"] }) }], })); ``` --- ## Troubleshooting ### The server doesn't start: "URI template must have a valid scheme" `uriTemplate` needs a scheme followed by `://`, like `ticket://{id}`. `{id}` or `ticket:{id}` are rejected. ### Reads fail with `-32602` "Resource not found" No template matched the URI. Check, in order: 1. The literal parts match exactly, including case and slashes. 2. No `{name}` value contains a `/`. Use `{+name}`, or have the client percent-encode the value with `encodeURIComponent()`. 3. The template is in its app's `resources` array. 4. `execute()` threw `ResourceNotFoundError`, which gives the same error. Check that the item exists. 5. The template's `availableWhen.surface`, if it has one, includes `"mcp"`. MCP clients can't read a template that leaves it out. ### Reads fail with `-32003` "ResourceTemplate "…" is not available in the current environment" The template's `availableWhen` doesn't match where the server runs. It's left out of `resources/templates/list`, and reading a URI it matches fails with this error, which names the URI, what the template requires and what the server is: Initial call configuration: ```js { resource: "deploy://T-1/notes" } ``` ```ts deploy-notes.template.ts active import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; @ResourceTemplate({ name: "deploy-notes", uriTemplate: "deploy://{id}/notes", mimeType: "text/plain", availableWhen: { runtime: ["deno"] } }) export class DeployNotes extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { return `Deploy notes for ${id}`; } } ``` ```ts deploy.test.ts import { test, expect } from "@frontmcp/testing"; test("it isn't listed, and reading a matching URI fails", async ({ mcp }) => { expect(await mcp.resources.listTemplates()).toEqual([]); const result = await mcp.resources.read("deploy://T-1/notes"); expect(result).toBeError(-32003); expect(result.error?.message).toMatch(/^ResourceTemplate "deploy:\/\/T-1\/notes" is not available in the current environment \(requires: \{"runtime":\["deno"\]\}\)/); }); ``` ### My template isn't in `resources/list` That's expected. Clients find templates with `resources/templates/list`, and `mcp.resources.listTemplates()` in tests. ### Completions come back empty Check that the method is named after the parameter, `idCompleter` for `{id}`, and that the template is a class. If the completer throws, FrontMCP logs a warning and answers with no values. --- # @Prompt > Declare a reusable message template that users pick in their client and fill in with arguments. Source: https://frontmcp.dev/reference/sdk/prompt [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@Prompt` declares an MCP [prompt](https://frontmcp.dev/learn/reusable-prompts): a message template that a user picks in their client, often from a slash menu, and fills in with arguments. FrontMCP runs your `execute()` with those arguments and returns the messages it builds, which the client then puts in front of the model. ```ts @Prompt(options) class MyPrompt extends PromptContext { async execute(args): Promise { /* ... */ } } ``` --- ## Reference ### `@Prompt(options)` Apply `@Prompt` to a class that extends `PromptContext`, and list the class in an app's `prompts` array. ```ts triage-ticket.prompt.ts import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "triage_ticket", title: "Triage a ticket", description: "Suggest a priority and a next step for a support ticket", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "tone", description: "friendly or formal" }, ], }) class TriageTicket extends PromptContext { async execute(args: Record): Promise { return { messages: [ { role: "user", content: { type: "text", text: `Read ticket ${args.id}, then suggest a priority and a next step.` } }, ], }; } } ``` [See more examples below.](https://frontmcp.dev/reference/sdk/prompt#usage) #### Options Required: | Option | Type | Description | | --- | --- | --- | | `name` | `string` | What clients list and ask for with `prompts/get`. Unique within the server. | Optional: | Option | Type | Description | | --- | --- | --- | | `enabled` | `EnabledOption` | Optional; defaults to on. A boolean or `{ get(context?), subscribe(listener), remedy? }`. Off entries are omitted from lists and refused with `FEATURE_OFF`. Changes announce `list_changed`. See [live availability](https://frontmcp.dev/reference/sdk/tool#changing-availability-while-the-server-runs). | | `arguments` | `PromptArgument[]` | The values the user fills in. Leave it out for a prompt without arguments. | | `title` | `string` | A readable name for menus, like `"Triage a ticket"`. Clients fall back to `name` without it. | | `description` | `string` | What the prompt is for. Also becomes the result's `description` when `execute()` doesn't return one. | | `icons` | `Icon[]` | Icons clients can show next to the prompt. Each has a `src`, and optionally `mimeType`, `sizes` and `theme` (`"light"` or `"dark"`). | | `availableWhen` | `EntryAvailability` | Only offer the prompt in matching environments. Takes arrays of `os`, `platform`, `runtime`, `deployment`, `provider`, `target`, `surface` and `env` values. Elsewhere the prompt isn't listed, and `prompts/get` fails with [`-32003`](https://frontmcp.dev/reference/sdk/prompt#prompt--is-not-available-in-the-current-environment). See [Environment awareness](https://frontmcp.dev/reference/server/environment). | Each entry in `arguments`: | Field | Type | Description | | --- | --- | --- | | `name` | `string` | The key the value arrives under in `args`. | | `description` | `string` | Shown to the user filling it in. | | `required` | `boolean` | Defaults to `false`. When `true`, FrontMCP rejects a `prompts/get` that leaves it out, and `execute()` doesn't run. | #### `execute(args)` FrontMCP calls `execute()` when a client sends `prompts/get`, once every required argument is present. - `args`: the arguments the client sent, as strings. They're also available as `this.args`. - **Returns** the prompt's messages. FrontMCP turns what `execute()` returns into the `prompts/get` result: | `execute()` returns | The client receives | | --- | --- | | `{ description?, messages }` | Those messages. Each has a `role`, `"user"` or `"assistant"`, and one `content` block of type `text`, `image`, `audio`, `resource` (an embedded resource) or `resource_link`. | | A string | One `user` message with that text. | | An array of `{ role, content }` messages | Those messages, as if you had returned `{ messages }`. | | Any other object | One `user` text message with the object as JSON. | The result's `description` is the one you return, or else the prompt's `description` option. FrontMCP checks the result when `execute()` returns: a message whose `role` isn't `"user"` or `"assistant"` [fails the request](https://frontmcp.dev/reference/sdk/prompt#prompt-output-validation-failed). Inside `execute()`, `this` is the `PromptContext`, with the members [every context class](https://frontmcp.dev/reference/sdk/contexts#members-every-class-shares) has: `this.get()` and `this.tryGet()` for [providers](https://frontmcp.dev/reference/sdk/provider), [`this.auth`](https://frontmcp.dev/reference/sdk/auth) for who is asking, [`this.context`](https://frontmcp.dev/reference/sdk/context#reading-the-request-in-a-prompt) for the request, [`this.fetch()`](https://frontmcp.dev/reference/sdk/fetch) and [`this.callTool()`](https://frontmcp.dev/reference/sdk/call-tool). It adds `this.args` for the arguments, and `this.metadata` for the options above. (Changed in 1.9.2: before, `PromptContext` had none of `this.auth`, `this.context`, `this.fetch()` and `this.callTool()`, and the caller was in `this.authInfo`, now deprecated.) #### Caveats - The class **must extend `PromptContext`**. Using `@Prompt` on any other class is a compile error. - Argument values are **always strings**, because that's all MCP allows. Convert them yourself. - Arguments that aren't declared are **passed through** to `execute()`, not dropped as they are for tools. - When `execute()` throws a `PublicMcpError` (or a subclass, like `InvalidInputError`), the client gets a JSON-RPC error, code `-32602`, whose message is your error's message. [See rejecting bad arguments.](https://frontmcp.dev/reference/sdk/prompt#rejecting-bad-arguments) - Any other error is an internal one: code `-32603`, and `Prompt execution failed: ` followed by its message in development. With `NODE_ENV=production`, FrontMCP hides the message and sends `Internal FrontMCP error. Please contact support with error ID: …` instead. - `this.fail(error)` fails the request the same way as `throw error` for a `PublicMcpError`. For any other error it's still `-32603`, but the message is your error's message without the `Prompt execution failed: ` prefix, and `data.code` is `SERVER_ERROR` instead of `PROMPT_EXECUTION_FAILED`. Production hides it the same way. - [`this.respond(value)`](https://frontmcp.dev/reference/sdk/respond) ends `execute()` as `return value` would. (Changed in 1.9.3: before, the request failed with [`Prompt output not found`](https://frontmcp.dev/reference/sdk/prompt#prompt-execution-failed-prompt-output-not-found).) - Declaring `execute()` as returning `Promise` is optional. With it, TypeScript checks each message's `role` and `content` as you write them. --- ## Usage ### Declaring arguments List every value the user should fill in. Clients read `arguments` from `prompts/list` to build the form, so describe each one. Open the **Capabilities** tab to see the prompt the way a client does, and the **Tests** tab to see what `required` does. Initial call configuration: ```js { prompt: "triage_ticket", arguments: { id: "T-2", tone: "friendly" } } ``` ```ts triage-ticket.prompt.ts active import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "triage_ticket", title: "Triage a ticket", description: "Suggest a priority and a next step for a support ticket", arguments: [ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "tone", description: "friendly or formal (default: formal)" }, ], }) export class TriageTicket extends PromptContext { async execute(args: Record): Promise { const tone = args.tone ?? "formal"; return { messages: [ { role: "user", content: { type: "text", text: `Read ticket ${args.id}. Suggest a priority (low, normal or high) and a next step, in a ${tone} tone.`, }, }, ], }; } } ``` ```ts triage.test.ts import { test, expect } from "@frontmcp/testing"; test("clients see which arguments are required", async ({ mcp }) => { const prompt = (await mcp.prompts.list()).find((p) => p.name === "triage_ticket"); expect(prompt?.arguments).toEqual([ { name: "id", description: "Ticket id, like T-1", required: true }, { name: "tone", description: "friendly or formal (default: formal)" }, ]); }); test("leaving out a required argument is an error", async ({ mcp }) => { const result = await mcp.prompts.get("triage_ticket", {}); expect(result).toBeError(-32602); expect(result.error?.message).toBe("Missing required argument: id"); }); test("optional arguments can be left out", async ({ mcp }) => { const result = await mcp.prompts.get("triage_ticket", { id: "T-1" }); expect(result).toHaveMessages(1); expect(result.messages[0].content.text).toContain("in a formal tone"); }); test("undeclared arguments aren't rejected", async ({ mcp }) => { const result = await mcp.prompts.get("triage_ticket", { id: "T-1", colour: "blue" }); expect(result).toBeSuccessful(); }); ``` ### Writing several messages A prompt can start a conversation with more than one turn. An `assistant` message puts words in the model's mouth, which is a reliable way to set the format of its answer. Initial call configuration: ```js { prompt: "draft_reply", arguments: { customer: "Amira", problem: "The invoice total is wrong" } } ``` ```ts draft-reply.prompt.ts import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "draft_reply", title: "Draft a reply", description: "Draft a short reply to a customer", arguments: [ { name: "customer", description: "The customer's first name", required: true }, { name: "problem", description: "What they reported", required: true }, ], }) export class DraftReply extends PromptContext { async execute({ customer, problem }: Record): Promise { return { description: `Reply to ${customer}`, messages: [ { role: "user", content: { type: "text", text: `You're a support agent. Keep replies under 80 words and end with one clear next step.` } }, { role: "assistant", content: { type: "text", text: "Understood. What did the customer report?" } }, { role: "user", content: { type: "text", text: `${customer} wrote: "${problem}". Draft the reply.` } }, ], }; } } ``` The result's `description` is the one you return. Without one, FrontMCP uses the prompt's `description` option. ### Returning a string or an array A prompt that's a single user message can return just its text. A prompt with several messages can return the array of messages, without the `{ messages }` around it. Open the **Tests** tab to see what each one sends. Initial call configuration: ```js { prompt: "escalation_note", arguments: { id: "T-3" } } ``` ```ts shortcuts.prompt.ts active import { Prompt, PromptContext } from "@frontmcp/sdk"; @Prompt({ name: "escalation_note", description: "Write an escalation note for the on-call engineer", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class EscalationNote extends PromptContext { async execute({ id }: Record) { return `Write a two-line escalation note for ticket ${id}: impact first, then what was tried.`; } } @Prompt({ name: "reply_in_house_style", description: "Draft a reply in the help desk's style" }) export class ReplyInHouseStyle extends PromptContext { async execute() { return [ { role: "user", content: { type: "text", text: "Draft replies in two sentences: what we did, then what happens next." } }, { role: "assistant", content: { type: "text", text: "Understood. Paste the ticket." } }, ]; } } ``` ```ts shortcuts.test.ts import { test, expect } from "@frontmcp/testing"; test("a string is one user message", async ({ mcp }) => { const result = await mcp.prompts.get("escalation_note", { id: "T-3" }); expect(result.messages).toEqual([ { role: "user", content: { type: "text", text: "Write a two-line escalation note for ticket T-3: impact first, then what was tried." } }, ]); }); test("the prompt's description comes along", async ({ mcp }) => { const result = await mcp.prompts.get("escalation_note", { id: "T-3" }); expect(result.description).toBe("Write an escalation note for the on-call engineer"); }); test("an array is the list of messages", async ({ mcp }) => { const result = await mcp.prompts.get("reply_in_house_style", {}); expect(result.messages.map((m) => m.role)).toEqual(["user", "assistant"]); expect(result.messages[0].content.text).toContain("two sentences"); }); ``` ### Including data in a message A message can carry data as well as text. Embed it, or link to a [resource](https://frontmcp.dev/reference/sdk/resource) the client can read. ### Data in a message ### Example: Embedded resource Get the data from a [provider](https://frontmcp.dev/reference/sdk/provider) with `this.get()`, and embed it as a `resource` block. The client sends the model the data itself, with its URI and MIME type. Initial call configuration: ```js { prompt: "summarize_ticket", arguments: { id: "T-1" } } ``` ```ts summarize-ticket.prompt.ts active import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Prompt({ name: "summarize_ticket", description: "Summarize a ticket and its history for a handover", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class SummarizeTicket extends PromptContext { async execute({ id }: Record): Promise { const ticket = this.get(TicketStore).find(id); return { messages: [ { role: "user", content: { type: "resource", resource: { uri: `ticket://${id}`, mimeType: "application/json", text: JSON.stringify(ticket) }, }, }, { role: "user", content: { type: "text", text: "Summarize this ticket in three bullet points for the next agent." } }, ], }; } } ``` ```ts ticket-store.ts import { Provider } from "@frontmcp/sdk"; @Provider({ name: "TicketStore" }) export class TicketStore { private tickets = [ { id: "T-1", title: "Cannot log in", status: "open", history: ["Reported by Amira", "Password reset sent"] }, { id: "T-2", title: "Invoice total is wrong", status: "closed", history: ["Refund issued"] }, ]; find(id: string) { return this.tickets.find((t) => t.id === id); } } ``` ### Example: Resource link A `resource_link` block sends only the URI. The client reads the resource itself with `resources/read` if it needs it, which keeps large data out of the prompt. Here the link points at a resource template in the same server; use the **Request** menu to read `ticket://T-1`. Initial call configuration: ```js { prompt: "summarize_ticket", arguments: { id: "T-1" } } ``` ```ts summarize-ticket.prompt.ts active import { Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "summarize_ticket", description: "Summarize a ticket and its history for a handover", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class SummarizeTicket extends PromptContext { async execute({ id }: Record): Promise { return { messages: [ { role: "user", content: { type: "resource_link", uri: `ticket://${id}`, name: id, mimeType: "application/json" } }, { role: "user", content: { type: "text", text: "Read the linked ticket, then summarize it in three bullet points." } }, ], }; } } ``` ```ts ticket.resource.ts import { ResourceContext, ResourceTemplate } from "@frontmcp/sdk"; @ResourceTemplate({ name: "ticket", uriTemplate: "ticket://{id}", mimeType: "application/json", description: "One ticket by id" }) export class TicketResource extends ResourceContext<{ id: string }> { async execute(uri: string, { id }: { id: string }) { const ticket = { id, title: "Cannot log in", status: "open" }; return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(ticket) }] }; } } ``` ### Rejecting bad arguments Arguments are free text, so a prompt can't declare a format the way a tool's schema can. Check the values in `execute()` and throw a `PublicMcpError` with a message the user can act on. The client gets a JSON-RPC error, code `-32602`, with your message. Initial call configuration: ```js { prompt: "summarize_ticket", arguments: { id: "T-9" } } ``` ```ts summarize-ticket.prompt.ts active import { Prompt, PromptContext, PublicMcpError, type GetPromptResult } from "@frontmcp/sdk"; const tickets = [{ id: "T-1", title: "Cannot log in", status: "open" }]; @Prompt({ name: "summarize_ticket", description: "Summarize a ticket for a handover", arguments: [{ name: "id", description: "Ticket id, like T-1", required: true }], }) export class SummarizeTicket extends PromptContext { async execute({ id }: Record): Promise { const ticket = tickets.find((t) => t.id === id); if (!ticket) throw new PublicMcpError(`There's no ticket ${id}. Ticket ids look like T-1.`); return { messages: [{ role: "user", content: { type: "text", text: `Summarize: ${ticket.title} (${ticket.status})` } }] }; } } ``` ```ts summarize.test.ts import { test, expect } from "@frontmcp/testing"; test("the user gets the message as it was thrown", async ({ mcp }) => { const result = await mcp.prompts.get("summarize_ticket", { id: "T-9" }); expect(result).toBeError(-32602); expect(result.error?.message).toBe("There's no ticket T-9. Ticket ids look like T-1."); }); ``` > **Note** > > Only a `PublicMcpError` keeps its message everywhere. Any other error thrown from a prompt is internal: in development the client sees `Prompt execution failed: ` and its message, and with `NODE_ENV=production` an error ID instead. So errors from databases and other services don't reach the user, and the user doesn't learn what went wrong either. Catch the ones you expect, and throw a `PublicMcpError` of your own. ### Writing a prompt as a function For a prompt that doesn't need providers, the function form is shorter. It takes the same options, and the handler receives the arguments. Initial call configuration: ```js { prompt: "escalate", arguments: { id: "T-3" } } ``` ```ts escalate.prompt.ts import { prompt } from "@frontmcp/sdk"; export const escalate = prompt({ name: "escalate", description: "Write an escalation note for the on-call engineer", arguments: [{ name: "id", description: "Ticket id", required: true }], })((args) => ({ messages: [ { role: "user", content: { type: "text", text: `Write a two-line escalation note for ticket ${args?.id}: impact first, then what was tried.` } }, ], })); ``` --- ## Troubleshooting ### `Missing required argument: id` The client asked for the prompt without a value for an argument marked `required: true`, so `execute()` didn't run. The response is a JSON-RPC error with code `-32602`. If users often skip the argument, say more about it in its `description`, or make it optional and use a default in `execute()`. ### `Prompt not found: triage_ticket` No prompt with that name is registered on the server, and the response is a JSON-RPC error with code `-32602`. Check, in order: 1. The class is in its app's `prompts` array (not `tools`), and the app is in `@FrontMcp({ apps })`. `@FrontMcp` has no `prompts` option; one there is silently ignored. 2. The name matches exactly, including case. 3. The prompt's `availableWhen.surface`, if it has one, includes `"mcp"`. MCP clients get this error for a prompt that leaves it out. ### The plain name gets another app's prompt Two apps declare a prompt with the same name. `prompts/list` shows them as `:`, like `desk:triage_ticket` and `billing:triage_ticket`, and `prompts/get` finds each by that name. The plain name, `triage_ticket`, gets the first app's prompt. Use the names `prompts/list` gives: Initial call configuration: ```js { prompt: "billing:triage_ticket" } ``` ```ts main.ts import { App, FrontMcp, Prompt, PromptContext, type GetPromptResult } from "@frontmcp/sdk"; @Prompt({ name: "triage_ticket", arguments: [] }) class DeskTriage extends PromptContext { async execute(): Promise { return { messages: [{ role: "user", content: { type: "text", text: "Triage the newest support ticket." } }] }; } } @Prompt({ name: "triage_ticket", arguments: [] }) class BillingTriage extends PromptContext { async execute(): Promise { return { messages: [{ role: "user", content: { type: "text", text: "Triage the newest billing dispute." } }] }; } } @App({ id: "desk", name: "Help Desk", prompts: [DeskTriage] }) class DeskApp {} @App({ id: "billing", name: "Billing", prompts: [BillingTriage] }) class BillingApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [DeskApp, BillingApp] }) export default class Server {} ``` ```ts names.test.ts import { test, expect } from "@frontmcp/testing"; test("each app's prompt by its listed name; the plain name gets the first app's", async ({ mcp }) => { expect((await mcp.prompts.list()).map((prompt) => prompt.name)).toEqual(["billing:triage_ticket", "desk:triage_ticket"]); const expected = { "desk:triage_ticket": "Triage the newest support ticket.", "billing:triage_ticket": "Triage the newest billing dispute.", triage_ticket: "Triage the newest support ticket.", }; for (const [name, text] of Object.entries(expected)) { expect((await mcp.prompts.get(name, {})).messages[0].content.text).toBe(text); } }); ``` Give prompts names that are unique across the whole server, like `triage_billing_dispute`, so clients don't need the prefix. (Changed in 1.9.2: before, `prompts/get` answered `Prompt not found: billing:triage_ticket`, and the second app's prompt couldn't be reached.) ### `Prompt "…" is not available in the current environment` The prompt's `availableWhen` doesn't match where the server runs. It's left out of `prompts/list`, and `prompts/get` fails with a JSON-RPC error with code `-32003`, whose message says what the prompt requires and what the server is: Initial call configuration: ```js { prompt: "deploy_checklist" } ``` ```ts deploy-checklist.prompt.ts active import { Prompt, PromptContext } from "@frontmcp/sdk"; @Prompt({ name: "deploy_checklist", description: "Walk through a Deno Deploy release", availableWhen: { runtime: ["deno"] } }) export class DeployChecklist extends PromptContext { async execute() { return "List what to check before running deployctl."; } } ``` ```ts deploy.test.ts import { test, expect } from "@frontmcp/testing"; test("it isn't listed, and getting it fails", async ({ mcp }) => { expect(await mcp.prompts.list()).toEqual([]); const result = await mcp.prompts.get("deploy_checklist", {}); expect(result).toBeError(-32003); expect(result.error?.message).toMatch(/^Prompt "deploy_checklist" is not available in the current environment \(requires: \{"runtime":\["deno"\]\}\)/); }); ``` The message lists the server's OS, runtime and deployment, in production too. If the prompt should be offered here, fix its `availableWhen`. ### `Prompt execution failed: Prompt output not found` `execute()` finished without returning anything, or returned `undefined`. Here a lookup misses for every ticket but `T-1`: Initial call configuration: ```js { prompt: "summarize_ticket", arguments: { id: "T-2" } } ``` ```ts summarize-ticket.prompt.ts import { Prompt, PromptContext } from "@frontmcp/sdk"; const summaries: Record = { "T-1": "Summarize ticket T-1, our oldest." }; @Prompt({ name: "summarize_ticket", arguments: [{ name: "id", required: true }] }) export class SummarizeTicket extends PromptContext { async execute({ id }: Record) { return summaries[id]; // 🚩 undefined for T-2 } } ``` Return a result on every path: ```ts // ✅ Every id gets a message return summaries[id] ?? `Summarize ticket ${id}.`; ``` Before 1.9.3, a prompt that called `this.respond()` failed with this error too. It now ends the request with the value it's given. ### `Prompt output validation failed` A message has a `role` other than `"user"` or `"assistant"`, usually `"system"`. MCP prompts have no system role. The request fails with JSON-RPC `-32603` and `data.code: "INVALID_OUTPUT"`. In development, `Prompt output validation failed ( at )` names the problem; details include `entry`, `reason` and `path`. Production hides the details. Changed in 1.11.3: before, the message said `Tool output validation failed` without a path or reason: Initial call configuration: ```js { prompt: "support_persona" } ``` ```ts persona.prompt.ts import { Prompt, PromptContext } from "@frontmcp/sdk"; @Prompt({ name: "support_persona" }) export class SupportPersona extends PromptContext { async execute() { return { messages: [{ role: "system", content: { type: "text", text: "You are a patient support agent." } }] }; } } ``` Put instructions in the first `user` message instead. Declaring `execute()` as returning `Promise` catches this while you write it: TypeScript only accepts `"user"` and `"assistant"` there. ### TypeScript says `Property 'execute' in type '…' is not assignable to the same property in base type 'PromptContext'` `execute()` can finish without returning anything, usually because a code path has no `return`. It must return a string, an array or an object, or throw, on every path: ```ts // 🚩 Promise on the path where the ticket exists async execute({ id }: Record) { if (!tickets.has(id)) throw new PublicMcpError(`There's no ticket ${id}.`); } // ✅ Every path returns or throws async execute({ id }: Record) { if (!tickets.has(id)) throw new PublicMcpError(`There's no ticket ${id}.`); return `Summarize ticket ${id}.`; } ``` --- # @Provider > Declare a shared service, like a database client or a cache, that tools, resources and prompts get with this.get(). Source: https://frontmcp.dev/reference/sdk/provider [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@Provider` declares a service that tools, resources and prompts share: a database client, an API wrapper, a cache, your configuration. FrontMCP creates it, keeps it for as long as its scope says, and hands it to any code that asks with `this.get()`. This is dependency injection: your tools say what they need, not how to build it. ```ts @Provider(options?) class MyService { /* ... */ } ``` --- ## Reference ### `@Provider(options?)` Apply `@Provider` to a class, list it in the `providers` of an app or of the server, and get it inside `execute()` with `this.get(MyService)`. ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets = new Map([["T-1", { id: "T-1", title: "Cannot log in", status: "open" }]]); find(id: string) { return this.tickets.get(id); } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { GetTicket } from "./get-ticket.tool"; import { TicketStore } from "./ticket-store"; @App({ id: "help-desk", name: "Help Desk", providers: [TicketStore], tools: [GetTicket] }) export class HelpDeskApp {} ``` [See more examples below.](https://frontmcp.dev/reference/sdk/provider#usage) #### Options | Option | Type | Description | | --- | --- | --- | | `name` | `string` | Optional. Defaults to the class name, symbol description or string token. Names the provider in logs and error messages; an empty name is refused. | | `scope` | `ProviderScope` | How long one instance lives. Defaults to `ProviderScope.GLOBAL`. See [scopes](https://frontmcp.dev/reference/sdk/provider#scopes). | | `description` | `string` | What the provider is for. | | `id` | `string` | A stable identifier, if `name` isn't one. | #### Scopes | Scope | Value | One instance per | | --- | --- | --- | | `ProviderScope.GLOBAL` | `"global"` | Server. Created when the server starts, and kept until it stops. **The default.** | | `ProviderScope.CONTEXT` | `"context"` | Session, for clients that open one (MCP before 2026-07-28). Under 2026-07-28, which has no sessions, one per request, for callers with a token too. Created when the request starts. | | `ProviderScope.SESSION`, `ProviderScope.REQUEST` | `"session"`, `"request"` | Deprecated. Both mean `CONTEXT`. | The Playground speaks 2026-07-28, so a `CONTEXT` provider in an example is new on every call. #### Registering providers A provider is available where it's registered, and nowhere else: | Where | Visible to | | --- | --- | | `@App({ providers })` | That app's tools, resources and prompts, and its other providers. | | `@FrontMcp({ providers })` | Every app on the server. | | `@Plugin({ providers })` | The plugin only. Also list a provider in the plugin's `exports` to make it visible to the apps that use the plugin. Each app that installs the plugin gets its own instance. | Each entry in `providers` is one of: | Form | Example | Notes | | --- | --- | --- | | A class | `TicketStore` | Must be decorated with `@Provider`. The class is also the token you pass to `this.get()`. | | A factory | `{ provide: DeskConfig, name: "DeskConfig", inject: () => [], useFactory: () => ({ slaHours: 4 }) }` | `name` is optional. `inject` is a **function** that returns the tokens to pass to `useFactory`. `useFactory` can be `async`. Add `scope` to change the default `GLOBAL`. | | A value | `{ provide: TicketStore, useValue: new TicketStore() }` | `useValue` may be a plain value or a class instance. | | Another class | `{ provide: DeskConfig, useClass: EnvConfig }` | Builds `EnvConfig` for the token. | `provide` is the token: a class, an abstract class, a symbol or a string. An abstract class makes a good token for configuration, because `this.get()` then knows its type. A factory whose `inject` lists `ProviderRegistry`, exported by `@frontmcp/sdk`, gets the registry that's building it. New in 1.11.1. Changed in 1.10.16: before, the types required a provider `name` and a bare `@Provider()` was refused. Names are now derived everywhere providers are accepted, including `AsyncProvider({ provide, useFactory })`, `dynamicProviders()` and the `FrontMcpInstance` entry points. `@Provider()` on a subclass derives that subclass's own name. Provider lookup uses the token. `tokenName(token)` from `@frontmcp/di` returns a class name, symbol description or the string itself. Symbols with no description or an empty one return `[ref]`. Changed in 1.10.16: symbol and string tokens previously printed `[ref]`, including in provider errors and circular dependency messages. #### `this.get(token)` and `this.tryGet(token)` Available in `ToolContext`, `ResourceContext` and `PromptContext`. - `this.get(token)` returns the instance. If no provider for `token` is registered where the caller can see it, it throws, and a tool call fails with `Provider "…" is not available`. - `this.tryGet(token)` returns `undefined` instead of throwing. For a symbol or string token, pass the type yourself: `this.get(SLA_HOURS)`. #### Constructor injection In a project compiled by `tsc` with `emitDecoratorMetadata`, a provider's constructor parameters are injected by type: ```ts ticket-repo.ts import { Provider } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Provider({ name: "TicketRepo" }) export class TicketRepo { constructor(private store: TicketStore) {} titleOf(id: string) { return this.store.find(id)?.title; } } ``` The Playground can't run this: it compiles with esbuild, which doesn't emit decorator metadata, so `store` would be `undefined`. The examples below use factories with `inject` instead, which work everywhere. #### Provider lifecycle FrontMCP calls these methods by name on the instance of a `GLOBAL` provider, a value provider's object included. Implementing `OnBootstrap`, `OnReady` or `OnShutdown` only checks the signature. A `CONTEXT` provider's instances, built per request, never get these calls. | Method | When it runs | If it fails | | --- | --- | --- | | `onBootstrap()` | After construction and dependency setup, before startup completes. Awaited. | `ProviderBootstrapError` stops startup. | | `onReady()` | Once the server is ready to serve, on every transport. Awaited. | Logged; the server stays up. | | `onShutdown()` | During disposal, in reverse order; apps before their parent providers. | Logged; disposal continues. Each hook has a 3000 ms limit by default. | `lifecycle.shutdownHookTimeoutMs` changes the per-hook shutdown limit. A build that inspects the server runs `onBootstrap()` but never `onReady()`. Serverless hosts may never run shutdown hooks. [Opening and closing a service](https://frontmcp.dev/reference/sdk/provider#opening-and-closing-a-service) runs them. A [`@Duty`](https://frontmcp.dev/reference/sdk/duty) or [`@Worker`](https://frontmcp.dev/reference/sdk/worker) class is a provider with a `run()` method: the server starts it in the `onReady()` phase, after the class's own `onReady()`, and stops it at shutdown before the class's own `onShutdown()`, within the same limit. Changed in 1.11.0: before, these method names had no lifecycle meaning. Rename an existing method with one of these names if it serves another purpose. #### `createContainer(options)` Builds providers without tools, resources, flows or a transport. It runs bootstrap hooks, never ready hooks; `dispose()` runs shutdown hooks. New in 1.11.0. | Option | Type | Default | Description | | --- | --- | --- | --- | | `providers` | `ProviderType[]` | `[]` | Server-level providers. | | `apps` | `AppType[]` | `[]` | Builds class apps' providers below the server's; skips remote apps. | | `logging` | `LoggingOptionsInput` | server defaults | Logger settings. | | `lifecycle` | `LifecycleOptionsInput` | shutdown limit 3000 ms | Provider shutdown settings. | | `runBackground` | `boolean` | `false` | Starts the registered [duties](https://frontmcp.dev/reference/sdk/duty) and [workers](https://frontmcp.dev/reference/sdk/worker), as a server does once it serves; `dispose()` stops them and releases their leases. New in 1.12.0. | | `runDuties` | `boolean` | `false` | The older name of `runBackground`, with the same effect. Changed in 1.12.0: before, it started duties only. | | `info` | `{ name: string }` | none | Required with `runBackground`; names the server whose leases the duties and workers share. | | `redis` | `RedisOptionsInput` | none | The server's top-level `redis`: duties and workers keep their leases there when it is a Redis server, and `scope: "cluster"` needs one. Vercel KV keeps no lease. New in 1.12.0. | Returns `Promise`: `get(token)`, `tryGet(token)` and async `dispose()`. Lookup checks server providers first, then each app in order. With `runBackground`, each duty's and worker's own `onReady()` runs before its first run; no other provider's does. Without `info`, the container is refused with `runBackground needs info.name: duties and workers share their leases by server name`. A container that runs duties and workers refuses a `"cluster"` one without `redis`, like a server; one that doesn't run them builds it. A container has no events, so a provider that injects [`EVENT_PUBLISHER`](https://frontmcp.dev/reference/sdk/worker#publishing-events-from-a-worker) cannot be built there, and no `/readyz`, so its duties and workers add no check. #### Caveats - A provider must be **registered** in `providers`. Decorating the class isn't enough. - A `GLOBAL` provider **can't depend on** a `CONTEXT` provider, its app's or the server's. The server fails to start with `InvalidDependencyScopeError`: `Invalid dependency: DEFAULT-scoped provider … cannot depend on scoped provider ….` Changed in 1.12.1: before, an app's factory that injected one of the server's `CONTEXT` providers wasn't checked. - `GLOBAL` means one instance per server **process**. Several processes or serverless instances each have their own, so keep shared data in a database or Redis. - A provider on an `@App` can declare hooks, and they run for that app's tools. Hooks on a `@FrontMcp` provider run for every app; hooks on a `CONTEXT` provider run on that request's instance. See [where hooks can be declared](https://frontmcp.dev/reference/sdk/hooks#where-hooks-can-be-declared). --- ## Usage ### Sharing state between tools A `GLOBAL` provider is created once, so every tool that gets it sees the same data. Call `assign_ticket`, then `my_queue`, and the ticket is there. Initial call configuration: ```js { tool: "assign_ticket", arguments: { id: "T-1", agent: "nour" } } ``` ```ts tools.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { Assignments } from "./assignments"; @Tool({ name: "assign_ticket", description: "Assign a ticket to a support agent", inputSchema: { id: z.string(), agent: z.string() }, }) export class AssignTicket extends ToolContext { async execute({ id, agent }: { id: string; agent: string }) { this.get(Assignments).assign(id, agent); return { id, agent }; } } @Tool({ name: "my_queue", description: "List the tickets assigned to an agent", inputSchema: { agent: z.string() }, }) export class MyQueue extends ToolContext { async execute({ agent }: { agent: string }) { return { tickets: this.get(Assignments).queue(agent) }; } } ``` ```ts assignments.ts import { Provider } from "@frontmcp/sdk"; @Provider() // GLOBAL is the default; the name comes from this class export class Assignments { private byTicket = new Map(); assign(id: string, agent: string) { this.byTicket.set(id, agent); } queue(agent: string) { return [...this.byTicket].filter(([, a]) => a === agent).map(([id]) => id); } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { AssignTicket, MyQueue } from "./tools"; import { Assignments } from "./assignments"; @App({ id: "help-desk", name: "Help Desk", tools: [AssignTicket, MyQueue], providers: [Assignments] }) export class HelpDeskApp {} ``` ```ts queue.test.ts import { test, expect } from "@frontmcp/testing"; test("the next call sees the assignment", async ({ mcp }) => { await mcp.tools.call("assign_ticket", { id: "T-1", agent: "nour" }); await mcp.tools.call("assign_ticket", { id: "T-2", agent: "nour" }); const result = await mcp.tools.call("my_queue", { agent: "nour" }); expect(result.json()).toEqual({ tickets: ["T-1", "T-2"] }); }); ``` ### Keeping state for one request A `CONTEXT` provider is new for each request (each session, for clients that use sessions). Within a request, every `this.get()` returns the same instance, so it can collect what happens during one call without leaking into the next. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { AuditTrail } from "./audit-trail"; @Tool({ name: "close_ticket", description: "Close a ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { this.get(AuditTrail).record(`checked that ${id} exists`); this.get(AuditTrail).record(`closed ${id}`); return { id, status: "closed", trail: this.get(AuditTrail).steps }; } } ``` ```ts audit-trail.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "AuditTrail", scope: ProviderScope.CONTEXT }) export class AuditTrail { steps: string[] = []; record(step: string) { this.steps.push(step); } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket } from "./close-ticket.tool"; import { AuditTrail } from "./audit-trail"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], providers: [AuditTrail] }) export class HelpDeskApp {} ``` ```ts audit.test.ts import { test, expect } from "@frontmcp/testing"; test("each call starts with an empty trail", async ({ mcp }) => { await mcp.tools.call("close_ticket", { id: "T-1" }); const second = await mcp.tools.call("close_ticket", { id: "T-2" }); expect(second.json<{ trail: string[] }>().trail).toEqual(["checked that T-2 exists", "closed T-2"]); }); ``` With `ProviderScope.GLOBAL`, the second call would return all four steps. ### Deriving names from provider tokens Omit `name` when the token already says what the provider is. This app registers a class implementation and an async factory without names. Missing providers report the symbol's description or the string token: Initial call configuration: ```js { tool: "desk_settings", arguments: { missing: false } } ``` ```ts main.ts active import { App, AsyncProvider, Tool, ToolContext, z } from "@frontmcp/sdk"; const API_URL = Symbol("api-url"); abstract class DeskConfig { abstract region: string; } class EnvConfig extends DeskConfig { region = "eu"; } @Tool({ name: "desk_settings", inputSchema: { missing: z.boolean() } }) class DeskSettings extends ToolContext { async execute({ missing }: { missing: boolean }) { if (missing) this.get(Symbol("missing-api")); return { apiUrl: this.get(API_URL), region: this.get(DeskConfig).region }; } } @App({ name: "Help Desk", tools: [DeskSettings], providers: [ { provide: DeskConfig, useClass: EnvConfig }, AsyncProvider({ provide: API_URL, useFactory: async () => "https://api.example.com" }), ], }) export class HelpDeskApp {} ``` ```ts names.test.ts import { test, expect } from "@frontmcp/testing"; test("unnamed class and async providers resolve by token", async ({ mcp }) => { expect((await mcp.tools.call("desk_settings", { missing: false })).json()).toEqual({ apiUrl: "https://api.example.com", region: "eu" }); }); test("a missing symbol provider reports its description", async ({ mcp }) => { expect(await mcp.tools.call("desk_settings", { missing: true })).toHaveTextContent('Provider "missing-api" is not available'); }); ``` ### Providing a value or configuration Register a settings object with `useValue`, or build a service with `useClass` or `useFactory`. A name is optional. For a factory, `inject` returns the tokens whose instances `useFactory` receives, in order. ### Values and factories ### Example: A value An abstract class works as a typed token: `this.get(DeskConfig)` knows it has a `slaHours`. Initial call configuration: ```js { tool: "reply_due", arguments: { priority: "high" } } ``` ```ts help-desk.app.ts active import { App, Tool, ToolContext, z } from "@frontmcp/sdk"; export abstract class DeskConfig { abstract slaHours: { high: number; normal: number }; } @Tool({ name: "reply_due", description: "How many hours we have to reply to a ticket of this priority", inputSchema: { priority: z.enum(["high", "normal"]) }, }) export class ReplyDue extends ToolContext { async execute({ priority }: { priority: "high" | "normal" }) { return { hours: this.get(DeskConfig).slaHours[priority] }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ReplyDue], providers: [ { provide: DeskConfig, useValue: { slaHours: { high: 4, normal: 24 } } }, ], }) export class HelpDeskApp {} ``` ```ts config.test.ts import { test, expect } from "@frontmcp/testing"; test("an unnamed plain-value provider is available by its token", async ({ mcp }) => { expect((await mcp.tools.call("reply_due", { priority: "high" })).json()).toEqual({ hours: 4 }); expect((await mcp.tools.call("reply_due", { priority: "normal" })).json()).toEqual({ hours: 24 }); }); ``` ### Example: Built from another provider `inject` lists the providers the factory needs. With `as const`, TypeScript infers the factory's parameter types from them. Initial call configuration: ```js { tool: "reply_due", arguments: { priority: "normal" } } ``` ```ts help-desk.app.ts active import { App, Provider, Tool, ToolContext, z } from "@frontmcp/sdk"; @Provider({ name: "Settings" }) export class Settings { get(key: string) { return { SLA_HIGH_HOURS: "4", SLA_NORMAL_HOURS: "24" }[key]; } } export abstract class DeskConfig { abstract slaHours: { high: number; normal: number }; } @Tool({ name: "reply_due", description: "How many hours we have to reply to a ticket of this priority", inputSchema: { priority: z.enum(["high", "normal"]) }, }) export class ReplyDue extends ToolContext { async execute({ priority }: { priority: "high" | "normal" }) { return { hours: this.get(DeskConfig).slaHours[priority] }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ReplyDue], providers: [ Settings, { provide: DeskConfig, name: "DeskConfig", inject: () => [Settings] as const, useFactory: (settings) => ({ slaHours: { high: Number(settings.get("SLA_HIGH_HOURS")), normal: Number(settings.get("SLA_NORMAL_HOURS")) }, }), }, ], }) export class HelpDeskApp {} ``` ### Example: Async An `async` factory is awaited before the server takes requests, so tools never see a half-built provider. Initial call configuration: ```js { tool: "list_agents", arguments: {} } ``` ```ts help-desk.app.ts active import { App, Tool, ToolContext } from "@frontmcp/sdk"; export abstract class Roster { abstract agents: string[]; } async function loadRoster() { await new Promise((resolve) => setTimeout(resolve, 50)); // stands in for a database query return { agents: ["nour", "sam", "li"] }; } @Tool({ name: "list_agents", description: "List the support agents on the roster", inputSchema: {} }) export class ListAgents extends ToolContext { async execute() { return { agents: this.get(Roster).agents }; } } @App({ id: "help-desk", name: "Help Desk", tools: [ListAgents], providers: [{ provide: Roster, name: "Roster", inject: () => [], useFactory: loadRoster }], }) export class HelpDeskApp {} ``` ### Reading the request in a provider Inject `FRONTMCP_CONTEXT` into a `CONTEXT` factory to build something for the current request: its id, its trace, who is calling. Here each ticket is stamped with the request that created it. Initial call configuration: ```js { tool: "create_ticket", arguments: { title: "Printer on fire" } } ``` ```ts help-desk.app.ts active import { App, FRONTMCP_CONTEXT, ProviderScope, Tool, ToolContext, z } from "@frontmcp/sdk"; export abstract class RequestInfo { abstract requestId: string; abstract traceId: string; } @Tool({ name: "create_ticket", description: "Open a new support ticket", inputSchema: { title: z.string() } }) export class CreateTicket extends ToolContext { async execute({ title }: { title: string }) { const { requestId } = this.get(RequestInfo); return { id: "T-4", title, createdBy: requestId }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CreateTicket], providers: [ { provide: RequestInfo, name: "RequestInfo", scope: ProviderScope.CONTEXT, inject: () => [FRONTMCP_CONTEXT] as const, useFactory: (ctx) => ({ requestId: ctx.requestId, traceId: ctx.traceContext.traceId }), }, ], }) export class HelpDeskApp {} ``` ```ts request.test.ts import { test, expect } from "@frontmcp/testing"; test("each call has its own request id", async ({ mcp }) => { const a = (await mcp.tools.call("create_ticket", { title: "First" })).json<{ createdBy: string }>(); const b = (await mcp.tools.call("create_ticket", { title: "Second" })).json<{ createdBy: string }>(); expect(a.createdBy).toEqual(expect.any(String)); expect(a.createdBy).not.toBe(b.createdBy); }); ``` `FRONTMCP_CONTEXT` only makes sense per request, so inject it into `CONTEXT` providers only. A `CONTEXT` provider can also hold something built for the caller, like a client for your own API that acts as them. Under 2026-07-28, every request gets its own instance, whoever is calling, with a token or without, and even when two requests send the same `mcp-session-id` header. So one caller's client is never handed to another. This server uses `transparent` auth, and the test calls it as two users, one after the other: Initial call configuration: ```js { tool: "my_tickets", arguments: {} } ``` ```ts help-desk.app.ts active import { App, FRONTMCP_CONTEXT, ProviderScope, Tool, ToolContext } from "@frontmcp/sdk"; /** A client for the ticket API that acts as the caller. */ export abstract class TicketApi { abstract actingAs: string | undefined; } @Tool({ name: "my_tickets", description: "List the tickets assigned to the caller", inputSchema: {} }) export class MyTickets extends ToolContext { async execute() { return { actingAs: this.get(TicketApi).actingAs }; } } @App({ id: "help-desk", name: "Help Desk", tools: [MyTickets], providers: [ { provide: TicketApi, name: "TicketApi", scope: ProviderScope.CONTEXT, inject: () => [FRONTMCP_CONTEXT] as const, // In transparent mode, clientId is the token's sub. useFactory: (ctx) => ({ actingAs: ctx.authInfo.clientId }), }, ], }) export class HelpDeskApp {} ``` ```ts main.ts import { FrontMcp } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; export const config = { info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp], auth: { mode: "transparent" as const, provider: "https://auth.example.com", expectedAudience: "https://desk.example.com", allowAnonymous: true, providerConfig: { jwks: { keys: [{ kty: "EC", crv: "P-256", kid: "desk-1", alg: "ES256", use: "sig", x: "1CjT9Do3B6PgOMVsIY0Amz_l1QbuUfoNLcq3E1OFip0", y: "4Je6s1T1RHT7obF4lowUe-63m0pat0TZfmnRxLfDCE8" }] } }, }, }; @FrontMcp(config) export default class Server {} ``` **Hidden fixture/test file (runs with the example):** ```ts tokens.ts hidden // Access tokens for two users, signed ahead of time with the key in main.ts. export const NOUR = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImRlc2stMSJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJub3VyIiwiYXVkIjoiaHR0cHM6Ly9kZXNrLmV4YW1wbGUuY29tIiwiaWF0IjoxNzkwMDAwMDAwLCJleHAiOjQxMDI0NDQ4MDAsInNjb3BlIjoidGlja2V0czpyZWFkIHRpY2tldHM6d3JpdGUiLCJyb2xlcyI6WyJhZ2VudCJdLCJuYW1lIjoiTm91ciBIYWRkYWQiLCJlbWFpbCI6Im5vdXJAZXhhbXBsZS5jb20iLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsibGVhZCJdfSwidGVuYW50IjoiYWNtZSJ9.NGr_C0VEuc3p0Fc0GKq92Gytmn3Ig8XaDEO2GfA-X8g1rzN2flqNbuSB3Z_b1Mb0hy4mkv8KW7_ngW5sWE_YPw"; export const SAM = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImRlc2stMSJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJzYW0iLCJhdWQiOiJodHRwczovL2Rlc2suZXhhbXBsZS5jb20iLCJpYXQiOjE3OTAwMDAwMDAsImV4cCI6NDEwMjQ0NDgwMCwic2NvcGUiOiJ0aWNrZXRzOnJlYWQiLCJuYW1lIjoiU2FtIE9ydGl6In0.VHIKGx65AgtNp4Y4PtdLCJoQgXg5pOeBYp03oLgpr1l2elL9Gui6EcQuuBUeb-sYYFJo2-labA_nJwhSV9BLpw"; ``` ```ts callers.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./main"; import { NOUR, SAM } from "./tokens"; test("each caller gets a client of their own", async () => { // One server; each call is a 2026-07-28 request over HTTP with the caller's token. const handler = await FrontMcpInstance.createFetchHandler(config); const callAs = async (token: string) => { const response = await handler( new Request("https://desk.example.com/", { method: "POST", headers: { "content-type": "application/json", "mcp-protocol-version": "2026-07-28", "mcp-method": "tools/call", "mcp-name": "my_tickets", "mcp-session-id": "the-same-id", authorization: `Bearer ${token}`, }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "my_tickets", arguments: {}, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } }, }), }), ); return (await response.json()).result.structuredContent; }; expect(await callAs(NOUR)).toEqual({ actingAs: "nour" }); expect(await callAs(SAM)).toEqual({ actingAs: "sam" }); }); ``` Clients on protocol versions before 2026-07-28 keep a `CONTEXT` provider for their whole session, and that includes this one: FrontMCP builds it on the session's first request, so later requests in the session see that request's `requestId`. When a value has to be right for every request, read it from `this.context` in the tool instead. ### Using a provider only if it's there `this.tryGet()` returns `undefined` for a provider that isn't registered, so a tool can work with or without it. Here notifications are optional. Add `Notifier` to the app's `providers`, and `notified` becomes `true`. Initial call configuration: ```js { tool: "close_ticket", arguments: { id: "T-1" } } ``` ```ts close-ticket.tool.ts active import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { Notifier } from "./notifier"; @Tool({ name: "close_ticket", description: "Close a ticket, and tell the customer if we can", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { const notifier = this.tryGet(Notifier); notifier?.send(`Ticket ${id} was closed.`); return { id, status: "closed", notified: notifier !== undefined }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CloseTicket } from "./close-ticket.tool"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], providers: [] }) export class HelpDeskApp {} ``` ```ts notifier.ts import { Provider } from "@frontmcp/sdk"; @Provider({ name: "Notifier" }) export class Notifier { send(message: string) { console.log(message); } } ``` ### Opening and closing a service Keep asynchronous setup and release with the provider. The first test builds a container, which makes the order visible without starting a server; the second runs a server, which also calls `onReady()`: **Hidden fixture/test file (runs with the example):** ```ts main.ts hidden import { App } from "@frontmcp/sdk"; @App({ name: "Lifecycle" }) export class LifecycleApp {} ``` ```ts lifecycle.test.ts active import { test, expect } from "@frontmcp/testing"; import { App, createContainer, FrontMcpInstance, Provider, ProviderScope, Tool, ToolContext } from "@frontmcp/sdk"; test("bootstrap runs before lookup, and shutdown runs on disposal", async () => { const events: string[] = []; @Provider() class TicketStore { onBootstrap() { events.push("opened"); } onReady() { events.push("ready"); } onShutdown() { events.push("closed"); } } const container = await createContainer({ providers: [TicketStore] }); expect(container.get(TicketStore)).toBeInstanceOf(TicketStore); expect(events).toEqual(["opened"]); await container.dispose(); expect(events).toEqual(["opened", "closed"]); }); test("a container that runs duties and workers needs the server's name", async () => { const container = createContainer({ providers: [], runBackground: true }); await expect(container).rejects.toThrow("runBackground needs info.name: duties and workers share their leases by server name"); }); test("a server calls onReady(), and a CONTEXT provider gets no lifecycle calls", async () => { const events: string[] = []; @Provider({ name: "TicketStore" }) class TicketStore { onBootstrap() { events.push("store opened"); } onReady() { events.push("store ready"); } onShutdown() { events.push("store closed"); } } @Provider({ name: "RequestLog", scope: ProviderScope.CONTEXT }) class RequestLog { onBootstrap() { events.push("log opened"); } onShutdown() { events.push("log closed"); } } @Tool({ name: "close_ticket", description: "Close a ticket", inputSchema: {} }) class CloseTicket extends ToolContext { async execute() { this.get(TicketStore); this.get(RequestLog); return { closed: true }; } } @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], providers: [TicketStore, RequestLog] }) class HelpDeskApp {} const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); expect((await server.callTool("close_ticket", {})).structuredContent).toEqual({ closed: true }); await server.dispose(); expect(events).toEqual(["store opened", "store ready", "store closed"]); }); ``` --- ## Troubleshooting ### `Provider "…" failed in onBootstrap(): …` `ProviderBootstrapError` (`PROVIDER_BOOTSTRAP_FAILED`) stops startup and keeps the cause in `originalError`. Check the provider's setup and dependencies. An `onReady()` failure instead logs an error and leaves the server running; an `onShutdown()` failure logs a warning and disposal continues. ### `Provider "TicketStore" is not available: not found in local or parent registries` A tool asked for a provider that isn't registered anywhere it can see, so the call failed: Initial call configuration: ```js { tool: "get_ticket", arguments: { id: "T-1" } } ``` ```ts help-desk.app.ts active import { App, Provider, Tool, ToolContext, z } from "@frontmcp/sdk"; @Provider({ name: "TicketStore" }) export class TicketStore { find(id: string) { return { id, title: "Cannot log in" }; } } @Tool({ name: "get_ticket", description: "Get one ticket by id", inputSchema: { id: z.string() } }) export class GetTicket extends ToolContext { async execute({ id }: { id: string }) { return this.get(TicketStore).find(id); } } // 🚩 TicketStore is decorated, but not in `providers` @App({ id: "help-desk", name: "Help Desk", tools: [GetTicket] }) export class HelpDeskApp {} ``` Add it to the `providers` of the tool's app, or of `@FrontMcp` to share it with every app. A provider registered in **another** app isn't visible: apps don't see each other's providers. ### `providers items must be classes annotated with @Provider() … or { provide, useValue | useClass | useFactory } objects` A provider entry is neither a decorated class nor an object with a token and a supported implementation. Register an undecorated implementation with `useClass`: ```ts providers: [ TicketStore, // a @Provider class { provide: DeskConfig, useValue: config }, { provide: DeskConfig, useClass: EnvConfig }, { provide: DeskConfig, useFactory: () => config }, ]; ``` Choose one implementation per token. Provider names are optional; a bare undecorated class is still refused. ### `Invalid dependency: DEFAULT-scoped provider Audit cannot depend on scoped provider RequestLog.` A `GLOBAL` provider (here `Audit`) injects a `CONTEXT` provider (`RequestLog`). The global one would outlive the request it was built for, so the server refuses to start. Make the dependent provider `CONTEXT` too, or pass the request-scoped value in as a method argument. ### `Provider TicketRepo depends on TicketStore, which is not registered (local or parent).` A constructor parameter or an `inject` token names a provider that isn't registered. Add it to `providers`. If the message says `depends on Function` or `depends on Object`, the parameter's type was imported with `import type`, which leaves no class at run time for `emitDecoratorMetadata` to record. Use a normal `import`. ### A constructor parameter is `undefined` The provider was built without its dependencies. Check that: 1. `tsconfig.json` sets `experimentalDecorators` and `emitDecoratorMetadata` to `true`, and your build uses `tsc` (or a compiler that emits decorator metadata). 2. `import "reflect-metadata"` is the first line of your entry file. In the Playground this always happens, because esbuild doesn't emit decorator metadata. Use a factory with `inject` there. ### `Failed to construct provider "DeskConfig": Cannot read properties of undefined` The factory was called without the providers it needs. Most often, `inject` is an array. It must be a function that returns one; FrontMCP ignores an array and calls the factory with no arguments: ```ts // 🚩 An array: `settings` is undefined { provide: DeskConfig, name: "DeskConfig", inject: [Settings], useFactory: (settings) => ({ slaHours: settings.slaHours }) } // ✅ A function that returns the array { provide: DeskConfig, name: "DeskConfig", inject: () => [Settings] as const, useFactory: (settings) => ({ slaHours: settings.slaHours }) } ``` TypeScript reports the array form as an error, unless it's been cast away. A `GLOBAL` factory runs when the server starts, so the server fails to start. A `CONTEXT` factory runs at the start of every request, so every call to that app's tools fails, even calls to tools that don't use it. ### State I stored in a provider is gone on the next call Check the provider's scope. A `CONTEXT` provider is rebuilt for every request under MCP 2026-07-28, and for every session on older clients. Use `GLOBAL` for state that should last. If it already is `GLOBAL`, your server probably runs as several processes or serverless instances, each with its own copy; keep the state in a database or Redis. --- # @Duty > Run recurring provider work in one process of a machine, a workspace or a cluster, every interval or on a cron schedule, under a lease another process can take over. Source: https://frontmcp.dev/reference/sdk/duty [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 A timer in a provider runs in every copy of a server. `@Duty` gives recurring work a lease, so one process runs it: one on a machine, one in a workspace, or one among all the machines that share the server's Redis. It runs every interval or at the times of a cron expression. Use it for refreshing an index, clearing old files or a report every weekday morning; use a [job](https://frontmcp.dev/reference/sdk/job) for work a client starts and follows by run id, and a [worker](https://frontmcp.dev/reference/sdk/worker) for work that never ends by itself. ```ts @Provider() @Duty({ name?, every | cron, timezone?, scope, leaseMs? }) class RefreshIndex { async run({ signal }: DutyRunContext) { /* refresh while the lease is held */ } } ``` --- ## Reference ### `@Duty(options)` Decorate a provider class with a `run(context)` method and register it in `providers`. `@Duty` marks the class as a provider, so `@Provider()` is optional. | Option | Type | Default | Description | | --- | --- | --- | --- | | `name` | `string` | class name | Lease name within the server. Set it explicitly when a build renames classes. | | `every` | `number \| string` | one of `every` or `cron` | Positive whole milliseconds or a duration such as `"500ms"`, `"30s"`, `"5m"`, `"1h"` or `"1d"`. At most 2147483647 ms. | | `cron` | `string` | one of `every` or `cron` | A cron expression of five fields, or six with seconds first. See [cron schedules](https://frontmcp.dev/reference/sdk/duty#cron-schedules). New in 1.12.0. | | `timezone` | `string` | `"UTC"` | The IANA time zone `cron` is read in, such as `"Europe/Berlin"`. Only with `cron`. New in 1.12.0. | | `scope` | `"machine" \| "workspace" \| "cluster"` | required | Among which processes one holds the lease. See [scopes and leases](https://frontmcp.dev/reference/sdk/duty#scopes-and-leases). `"cluster"` is new in 1.12.0. | | `leaseMs` | `number` | three intervals, clamped to 3000–60000 ms; 60000 ms with `cron` | Lease lifetime; renewed every third of it. Minimum 1000 ms. | A duty has exactly one of `every` and `cron`. `scope` is required with both: TypeScript refuses a `@Duty` without it. `run({ signal })` returns `void` or a promise. The signal aborts on lease loss or shutdown. A run that would start while the last one is still running is skipped, not queued; an exception is logged as `Duty "" failed: ` and the holder keeps the lease. Another process can take over after the holder stops renewing its lease. `dutyMetadataOf(instance)` returns its class's `ResolvedDutyMetadata`: `name`, `scope`, `leaseMs`, and either `everyMs` or `cron: { expression, timezone }`. It returns `undefined` when the class has none. `dutyMetadataSchema` validates the decorator options and converts `every` to milliseconds. #### Cron schedules New in 1.12.0. `cron` takes five fields, `minute hour day-of-month month day-of-week`, or six with `second` first. The framework reads it with `croner`, a dependency of `@frontmcp/sdk` that loads when the first duty or workflow with a cron is built. | Expression | Runs | | --- | --- | | `0 9 * * 1-5` | At 09:00, Monday to Friday | | `*/15 * * * *` | Every 15 minutes | | `0 0 1 * *` | At midnight on the first of each month | | `0 8-18/2 * * MON,WED,FRI` | Every second hour from 08:00 to 18:00 on three weekdays | | `*/10 * * * * *` | Every 10 seconds (six fields) | | `@daily` | At midnight; `@hourly` works too | - **Fields.** Lists (`1,15`), ranges (`1-5`), steps (`*/15`, `8-18/2`), month and day names; `0` and `7` are both Sunday. When both day-of-month and day-of-week are set, the duty runs on either: `0 0 13 * FRI` runs on the 13th and on every Friday. - **Time zone.** The expression is read in `timezone`, `"UTC"` by default. A local time the clocks skip in spring (`30 2 * * *` in `Europe/Berlin` on the last Sunday of March) runs once, at 03:00 when the clocks resume. A time they repeat in autumn runs once, the first time. - **First start.** A cron duty does not run when the server starts. It waits for its next scheduled time. - **Catching up.** The lease store keeps the time the schedule was last taken, without expiry. A process that gets the lease after a restart or a takeover compares it with the clock: when a scheduled time passed since, it runs once now, however many were missed, then continues on schedule. - **Skipped while running.** A scheduled time that comes while the last run is still running is skipped: with `* * * * * *` and a run of 2.5 seconds, the duty ran every third second. - **At most once.** A scheduled time is taken before its run starts. A holder that dies after taking it loses that run: the process that takes over runs only the scheduled times after it. A [scheduled workflow](https://frontmcp.dev/reference/sdk/workflow#running-on-a-schedule), whose run is a record in the job store, is recovered instead. An expression that can't be read stops startup: a wrong field, a seventh (year) field, a date, or one that never matches a date, such as `0 0 30 2 *`. See [errors](https://frontmcp.dev/reference/sdk/duty#errors). #### Scopes and leases Every copy of the server registers the duty. The one whose id is stored under the lease key runs it; the others try to take the lease at each check. | Scope | One holder among | Needs | | --- | --- | --- | | `"machine"` | The processes of one machine that run a server with the same `info.name` | `@frontmcp/storage-sqlite`, or a top-level `redis` | | `"workspace"` | Those of them that run from the same project root: the nearest folder at or above the working directory with a `package.json` | The same | | `"cluster"` | Every process, on every machine, that shares the server's top-level `redis`. New in 1.12.0. | A top-level `redis` that is a Redis provider. Without one the server does not start. | Where the lease lives: | Server | Scope | Store | Key | | --- | --- | --- | --- | | No top-level `redis` | `"machine"`, `"workspace"` | The SQLite file `~/.frontmcp/duties.sqlite`, or `$FRONTMCP_HOME/duties.sqlite` | `frontmcp:duty::` | | A top-level `redis` | `"machine"`, `"workspace"` | That Redis | `frontmcp:duty:::` | | A top-level `redis` | `"cluster"` | That Redis | `frontmcp:cluster:duty::` | A top-level `redis` here is a Redis server. Vercel KV keeps no lease: with it as the top-level `redis`, `"machine"` and `"workspace"` leases stay in the SQLite file, and a `"cluster"` duty stops startup as it does without `redis`. In a key, `info.name` and the duty's name are percent-encoded, as `encodeURIComponent()` writes them: a server named `Help Desk` has `Help%20Desk` there. A `"workspace"` key ends with `:` and the SHA-256 of the project root. Next to each lease, `:ran` records the last run: for an interval it expires after one interval, for a cron it holds the time the schedule was last taken and does not expire. With a top-level `redis`, `"machine"` means one hostname, so containers and pods, which have hostnames of their own, each run a `"machine"` duty: use `"cluster"` to run it once among them. - **Renewing.** The holder extends the lease every third of `leaseMs`, and again right before each run. A holder that can't renew for two thirds of `leaseMs` stops holding the duty, aborts the run in flight and contends again. - **Taking over.** A holder that shuts down aborts the run in flight, waits for it, then deletes the lease, so another process takes over at its next check. One that is killed or hangs is taken over once the lease expires: within `leaseMs` plus a third of it. With `leaseMs: 3000`, a second process took over about three seconds after the holder was killed. - **An interval's first run.** A process that gets the lease runs at once when no process started a run within the last interval, and otherwise once that interval has passed. - **The lease store opens at the first lease check.** When it can't be opened (a missing `@frontmcp/storage-sqlite`, an unreachable Redis, an unsafe folder), the server still starts. Each lease check logs `Duty "": the lease store failed: ` and tries again, and the duty runs once the store opens and this process gets the lease, without a restart. Changed in 1.12.0: before, a duty whose lease store failed to open at startup never ran in that process. A lease gives one holder at a time, not an exactly-once guarantee for what `run()` does: a process paused longer than its lease finds the lease gone when it wakes, while the process that took over already runs. Make the work safe to repeat. #### Health New in 1.12.0. Each duty the server started adds a check named `duty:` to [`/readyz`](https://frontmcp.dev/reference/deployment/health-and-metrics#background-work-and-events). It is `healthy` with `details: { holdsLease }`, which says whether this process holds the lease now. While the lease store cannot be opened it is `unhealthy` with `error: "the lease store cannot be opened: "`, and `/readyz` answers `503`. A run that fails is logged, not reported here. ```json {"duty:refresh-ticket-index":{"status":"healthy","details":{"holdsLease":true}}} ``` #### Errors An invalid option throws `InvalidDecoratorMetadataError` (`INVALID_DECORATOR_METADATA`) when the class is decorated, with a message that starts `@Duty invalid metadata for "":`. | Mistake | Field and message | | --- | --- | | A malformed `every` | `"every": every must be milliseconds or a duration such as "30s", "5m", "1h"` | | Both `every` and `cron` | `"cron": set either every or cron, not both` | | Neither | `"every": a duty needs every (an interval) or cron (a cron expression)` | | An empty `cron` | `"cron": cron must be a cron expression such as "0 9 * * 1-5"` | | An unknown time zone | `"timezone": timezone must be an IANA time zone such as "Europe/Berlin"` | | `timezone` with `every` | `"timezone": timezone applies to cron; a duty with every has none` | | An unknown `scope` | `"scope": scope must be 'machine', 'workspace' or 'cluster'` | | A class without `run()` | `"run": has no run() method` | Two mistakes are found when the server starts, in the duty's `onBootstrap()` phase. The server, or `createContainer()`, fails with `ProviderBootstrapError` (`PROVIDER_BOOTSTRAP_FAILED`) whose `originalError` is: | Error | Code | Message | | --- | --- | --- | | `InvalidDutyCronError` | `INVALID_DUTY_CRON` | `Duty "" has a cron expression that can't be read (""): ` | | `ClusterScopeNeedsRedisError` | `CLUSTER_SCOPE_NEEDS_REDIS` | `Duty "" has scope 'cluster', which keeps one lease for every machine in Redis, and none is configured: set a top-level redis (@FrontMcp({ redis }) or createContainer({ redis })), or use scope 'machine'` | The cluster check runs only where duties start: not in a serverless deployment, and not in a container without `runBackground`. Both errors are new in 1.12.0. A duty's name belongs to one class in its server, whatever the scopes. The second class to start with it fails with `DutyNameConflictError` (`DUTY_NAME_CONFLICT`), logged as `Provider "" failed in onReady(): Duty "" of server "" is declared by two classes in this process (A and B): give one of them its own name with @Duty({ name })`. The server stays up and the first class runs; `createContainer()` rejects with the error. Changed in 1.12.1: before, only duties with one lease conflicted, so two of one name, one `"workspace"` and the other `"machine"` or `"cluster"`, both ran. #### Caveats - Duties need a long-lived Node process. A serverless deployment logs `Duty "" does not run in a serverless or edge deployment: it needs a long-lived process` and does not run it. FrontMCP's browser build, which the Playground uses, starts none either. - The SQLite file and its folder are created owner-only. A folder the group or others can write to, or one that belongs to another user, is refused with [`UnsafeDutyStoreError`](https://frontmcp.dev/reference/sdk/duty#refusing-to-keep-duty-leases-under-). - Side effects should tolerate an interrupted holder: a process that ignores an aborted signal can continue working after losing its lease. - A [lazy app](https://frontmcp.dev/reference/sdk/app#lazy-apps) cannot have a duty: duties start with the server. - A `"cluster"` cron duty reads the schedule by the clock of the machine that holds it. Keep the machines' clocks in sync. [`createContainer()`](https://frontmcp.dev/reference/sdk/provider#createcontaineroptions) does not run duties unless `runBackground: true` and `info.name` are set. `runDuties: true`, the older name, does the same. ## Usage > **Note** > > No duty starts in the Playground: it runs FrontMCP's browser build, and a duty needs a long-lived Node process and a lease store. The registration examples below belong in a Node server. They were run as one, with two or three processes sharing a lease. ### Refreshing an index periodically ```ts refresh-index.duty.ts import { Duty, DutyRunContext, Provider } from "@frontmcp/sdk"; @Provider() @Duty({ name: "refresh-ticket-index", every: "5m", scope: "workspace" }) export class RefreshTicketIndex { async run({ signal }: DutyRunContext) { if (signal.aborted) return; // Refresh the index here, passing signal to cancellable work. } } ``` Register `RefreshTicketIndex` in the app's `providers`. Every server copy registers it; the lease chooses the holder. The holder logs `Duty "refresh-ticket-index" runs in this process every 300000 ms`, and the others `Duty "refresh-ticket-index" already runs elsewhere (lease ""); this one takes it over if that one stops`. ### Running on a calendar schedule Give the duty `cron` in place of `every`, and the time zone the schedule is meant in: ```ts weekday-report.duty.ts import { Duty, DutyRunContext, Provider } from "@frontmcp/sdk"; @Provider() @Duty({ name: "weekday-report", cron: "0 9 * * 1-5", timezone: "Europe/Berlin", scope: "machine" }) export class WeekdayReport { async run({ signal }: DutyRunContext) { // Build and send the report, passing signal to cancellable work. } } ``` The holder logs `Duty "weekday-report" runs in this process on cron "0 9 * * 1-5" (Europe/Berlin)`. Nothing runs at startup. After a restart or a takeover, the duty runs once at once if a scheduled time passed since the schedule was last taken, then continues on schedule. ### Running one duty among several machines `scope: "machine"` gives one holder per machine, so three replicas send three reports. `scope: "cluster"` keeps one lease for all of them in the server's Redis: ```ts main.ts @Provider() @Duty({ name: "weekday-report", cron: "0 9 * * 1-5", timezone: "Europe/Berlin", scope: "cluster" }) class WeekdayReport { async run({ signal }: DutyRunContext) { /* … */ } } @App({ id: "help-desk", name: "Help Desk", providers: [WeekdayReport] }) class HelpDesk {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk], redis: { url: process.env.REDIS_URL }, // the same Redis on every instance }) export default class Server {} ``` Every server with the same `info.name` on that Redis, and the same Redis database, shares the lease `frontmcp:cluster:duty:help-desk:weekday-report`. With two processes on a per-three-seconds cron and `leaseMs: 3000`, one ran each scheduled time; three seconds after it was killed, the other took over, ran once for the time that was missed, and continued on schedule. [High availability](https://frontmcp.dev/reference/deployment/high-availability#background-work-across-instances) lists what else instances share. ### Publishing an event from a duty A duty tells the clients subscribed to an [event](https://frontmcp.dev/reference/sdk/event) what it found. It takes the server's publisher, which the `EVENT_PUBLISHER` token provides. A factory provider injects it, which works whether or not the build emits constructor types: ```ts clock.duty.ts import { AsyncProvider, Duty, EVENT_PUBLISHER, type DutyInterface, type EventPublisher } from "@frontmcp/sdk"; import { clockTick } from "./clock.event"; @Duty({ name: "clock-tick", cron: "* * * * *", scope: "machine" }) class ClockTickDuty implements DutyInterface { constructor(private readonly events: EventPublisher) {} async run(): Promise { await this.events.publish(clockTick, { time: new Date().toISOString() }); } } export const clockTickDuty = AsyncProvider({ provide: ClockTickDuty, name: "clock-tick-duty", inject: () => [EVENT_PUBLISHER] as const, useFactory: (events) => new ClockTickDuty(events), }); ``` Register `clockTickDuty` in `providers` in place of the class, and the event in an app's `events`. The duty runs in the one process that holds its lease, so each run publishes once among the copies of the server. On a server without events, `publish()` is refused with `EventsNotEnabledError`, and the run is logged as failed. A container from `createContainer()` has no publisher, so a duty that takes one cannot be built there. [`@Worker`](https://frontmcp.dev/reference/sdk/worker#publishing-events-from-a-worker) shows the same with a class-typed constructor. ### Running duties from a script `createContainer()` builds a duty without starting it. To run duties and workers without serving MCP, ask for it: ```ts sweep.ts import { createContainer } from "@frontmcp/sdk"; const container = await createContainer({ apps: [HelpDesk], runBackground: true, // starts the @Duty and @Worker providers info: { name: "help-desk" }, // the server's info.name, so the script shares its leases redis: { url: process.env.REDIS_URL }, // the server's redis, when it has one }); // … await container.dispose(); // stops the duties and releases their leases ``` Each duty's own `onReady()` runs before its first run, as in a server. Without `info`, the container is refused: `runBackground needs info.name: duties and workers share their leases by server name`. See [`createContainer()`](https://frontmcp.dev/reference/sdk/provider#createcontaineroptions). ### Checking what a duty resolves to `@Duty` checks its options when the class is decorated, so a mistake fails at import, before any lease is taken. `dutyMetadataOf()` shows what the decorator resolved: `every` in milliseconds or the cron and its time zone, and the lease it defaults to. This tool reads it from three duties that aren't registered, so nothing runs: Initial call configuration: ```js { tool: "describe_duties", arguments: {} } ``` ```ts duties.ts import { Duty, DutyRunContext, Provider } from "@frontmcp/sdk"; @Provider() @Duty({ name: "refresh-ticket-index", every: "5m", scope: "workspace" }) export class RefreshTicketIndex { async run({ signal }: DutyRunContext) { if (signal.aborted) return; } } @Provider() @Duty({ name: "flush-audit-log", every: "2s", scope: "machine" }) export class FlushAuditLog { async run() {} } @Provider() @Duty({ name: "weekday-report", cron: "0 9 * * 1-5", timezone: "Europe/Berlin", scope: "cluster" }) export class WeekdayReport { async run() {} } ``` ```ts main.ts active import { App, Tool, ToolContext, dutyMetadataOf } from "@frontmcp/sdk"; import { FlushAuditLog, RefreshTicketIndex, WeekdayReport } from "./duties"; @Tool({ name: "describe_duties", description: "Show how each duty's options resolve", inputSchema: {} }) class DescribeDuties extends ToolContext { async execute() { const duties = [new RefreshTicketIndex(), new FlushAuditLog(), new WeekdayReport()]; return { duties: duties.map((duty) => dutyMetadataOf(duty)) }; } } @App({ id: "help-desk", name: "Help Desk", tools: [DescribeDuties] }) export class HelpDesk {} ``` ```ts duties.test.ts import { test, expect } from "@frontmcp/testing"; import { Duty, InvalidDecoratorMetadataError, InvalidDutyCronError, createContainer } from "@frontmcp/sdk"; const decorate = (options: Record) => () => Duty(options as never)(class Sweep { async run() {} }); test("an interval resolves to milliseconds, a cron to its expression and time zone", async ({ mcp }) => { const { duties } = (await mcp.tools.call("describe_duties", {})).json(); expect(duties).toEqual([ { name: "refresh-ticket-index", everyMs: 300000, scope: "workspace", leaseMs: 60000 }, { name: "flush-audit-log", everyMs: 2000, scope: "machine", leaseMs: 6000 }, { name: "weekday-report", cron: { expression: "0 9 * * 1-5", timezone: "Europe/Berlin" }, scope: "cluster", leaseMs: 60000 }, ]); }); test("an interval FrontMCP can't read fails when the class is decorated", () => { expect(decorate({ every: "5 minutes", scope: "machine" })).toThrow(InvalidDecoratorMetadataError); expect(decorate({ every: "5 minutes", scope: "machine" })).toThrow(/every must be milliseconds or a duration/); }); test("a duty has every or cron, not both, and a time zone only with cron", () => { expect(decorate({ every: "1h", cron: "0 * * * *", scope: "machine" })).toThrow('@Duty invalid metadata for "cron": set either every or cron, not both'); expect(decorate({ scope: "machine" })).toThrow('@Duty invalid metadata for "every": a duty needs every (an interval) or cron (a cron expression)'); expect(decorate({ every: "1h", timezone: "Europe/Berlin", scope: "machine" })).toThrow("timezone applies to cron; a duty with every has none"); expect(decorate({ cron: "0 9 * * 1-5", timezone: "Berlin", scope: "machine" })).toThrow('timezone must be an IANA time zone such as "Europe/Berlin"'); expect(decorate({ every: "1h", scope: "everywhere" })).toThrow("scope must be 'machine', 'workspace' or 'cluster'"); }); test("a duty needs a run() method", () => { expect(() => Duty({ every: "1h", scope: "machine" })(class Sweep {} as never)).toThrow(/has no run\(\) method/); }); test("a cron that can't be read stops startup, not decoration", async () => { @Duty({ name: "leap-day-report", cron: "0 0 30 2 *", scope: "machine" }) class LeapDayReport { async run() {} } const failure = await createContainer({ providers: [LeapDayReport] }).catch((error) => error); expect(failure.code).toBe("PROVIDER_BOOTSTRAP_FAILED"); expect(failure.originalError).toBeInstanceOf(InvalidDutyCronError); expect(failure.originalError.message).toBe(`Duty "leap-day-report" has a cron expression that can't be read ("0 0 30 2 *"): it never matches a date`); }); ``` The lease defaults to three intervals, kept between 3000 and 60000 ms: 60000 for every five minutes, 6000 for every two seconds. A cron duty's is 60000. The last test builds the duty in a container, which reads the expression without starting the duty. ## Troubleshooting ### `@Duty invalid metadata for "every"` Use positive whole milliseconds or a duration such as `"30s"`. Intervals must fit within 2147483647 ms. A duty with neither `every` nor `cron` fails with the same field. The class needs a `run()` method; unknown options and an invalid `scope`, `timezone` or `leaseMs` also fail decoration with `InvalidDecoratorMetadataError`. See [errors](https://frontmcp.dev/reference/sdk/duty#errors). ### `Duty "…" has a cron expression that can't be read` The server did not start: `InvalidDutyCronError` names the expression and the reason, such as `Invalid value for minute: 61` or `it never matches a date`. Use five fields, or six with seconds first. A year field and a date are refused. ### `Duty "…" has scope 'cluster', which keeps one lease for every machine in Redis, and none is configured` `ClusterScopeNeedsRedisError` stopped startup. Add a top-level `redis` to `@FrontMcp()`, or to `createContainer()` in a script, or use `scope: "machine"`. ### `Duty "…": the lease store failed: …` The duty could not read or write its lease, and tries again at its next check. With `Invalid sqlite configuration: the sqlite type needs @frontmcp/storage-sqlite. Install it with: npm install @frontmcp/storage-sqlite`, install that package or set a top-level `redis`. Meanwhile `/readyz` answers `503` with `duty:` `unhealthy` and `the lease store cannot be opened: `. The duty starts without a restart once the store opens. ### `Duty "…" of server "…" is declared by two classes in this process` Give one class its own `name`. Two classes can't give a duty of one server the same name, whatever their scopes. ### `Duty "…" already runs elsewhere` with one server Another server on the machine has the same `info.name` and a duty with the same name, so they share a lease. Give the server a distinctive `info.name`, or the duty its own `name`. ### `Refusing to keep duty leases under …` `UnsafeDutyStoreError` refuses unsafe ownership or permissions. Set `FRONTMCP_HOME` to a folder only the server's user can write. ### A cron duty did not run at startup It waits for its next scheduled time. Start the work another way when it must also run at startup. ### A cron duty runs at the wrong hour The expression is read in UTC unless `timezone` names the zone the schedule is meant in. ### A takeover is slow after a crash The lease has to expire first: `leaseMs` plus a third of it at most. A cron duty's default is 60000 ms. Lower `leaseMs`, to 1000 at least. --- # @Worker > Keep a long-running background process supervised. The server starts its run() once it serves, runs it again with a growing wait when it ends, stops it at shutdown, and runs it in every process or in one under a lease. Source: https://frontmcp.dev/reference/sdk/worker [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 Some work never ends by itself: a mail connection that stays open, a folder to watch, an upstream socket, a queue to consume. A loop started in a provider's `onReady()` has nothing to run it again when it throws, nothing to stop it at shutdown, and runs in every copy of the server. `@Worker` supervises it: the server starts `run()` once it serves, runs it again after a wait when it returns or throws, and aborts its `signal` at shutdown. With a `scope` other than `"process"`, one process holds the worker's lease and runs it, and another takes it over when the holder stops. New in 1.12.0. Use a [duty](https://frontmcp.dev/reference/sdk/duty) for work that runs, ends, and runs again on a schedule. ```ts @Worker({ name?, scope, restart?, leaseMs? }) class InboxWatcher { async run({ signal }: WorkerRunContext) { /* stay connected until signal aborts */ } } ``` --- ## Reference ### `@Worker(options)` Decorate a class with a `run(context)` method and register it in `providers`, of an `@App`, of `@FrontMcp` or of a plugin. `@Worker` marks the class as a `GLOBAL` [provider](https://frontmcp.dev/reference/sdk/provider): its constructor gets its dependencies injected, and it can implement `onBootstrap()`, `onReady()` and `onShutdown()`. | Option | Type | Default | Description | | --- | --- | --- | --- | | `name` | `string` | class name | The worker's name in logs, in its `/readyz` check and in its lease. Set it explicitly when a build renames classes. | | `scope` | `"process" \| "machine" \| "workspace" \| "cluster"` | required | Whether every process runs the worker, or one under a lease. See [scopes](https://frontmcp.dev/reference/sdk/worker#scopes). | | `restart` | `false \| { minDelayMs?, maxDelayMs?, factor? }` | `{ minDelayMs: 1000, maxDelayMs: 60000, factor: 2 }` | The waits before `run()` runs again. `false` runs it once. | | `leaseMs` | `number` | `15000` | Lease lifetime, which is how soon another process takes over from a holder that died; renewed every third of it. Minimum 1000 ms. Not with `scope: "process"`. | `run({ signal })` returns `void` or a promise that stays pending for as long as the worker works. `signal` aborts at shutdown, and when this process loses the worker's lease: pass it to what `run()` awaits, or listen to its `abort` event, and return. `workerMetadataOf(instance)` returns its class's `ResolvedWorkerMetadata` (`name`, `scope`, `restart`, `leaseMs`), or `undefined` when it has none. `workerMetadataSchema` validates the decorator options. The types `WorkerInterface` (a class with `run()`), `WorkerRunContext`, `WorkerMetadata`, `WorkerRestartOptions` and `WorkerScope` are exported from `@frontmcp/sdk` too. #### Scopes | Scope | Runs in | Lease | | --- | --- | --- | | `"process"` | Every server process, each its own instance | None | | `"machine"` | One process of the machine, among servers with the same `info.name` | The SQLite file, or Redis per hostname | | `"workspace"` | One process per project root: the nearest folder at or above the working directory with a `package.json` | The same | | `"cluster"` | One process among the machines that share the server's top-level `redis` | Redis, which it requires | A leased worker uses the store and the mechanism of duties: see [scopes and leases](https://frontmcp.dev/reference/sdk/duty#scopes-and-leases). Its keys have a prefix of their own, so a worker and a duty with one name do not share a lease: | Server | Scope | Store | Key | | --- | --- | --- | --- | | No top-level `redis` | `"machine"`, `"workspace"` | The SQLite file `~/.frontmcp/duties.sqlite`, or `$FRONTMCP_HOME/duties.sqlite`. It needs `@frontmcp/storage-sqlite`. | `frontmcp:worker::` | | A top-level `redis` | `"machine"`, `"workspace"` | That Redis | `frontmcp:worker:::` | | A top-level `redis` | `"cluster"` | That Redis | `frontmcp:cluster:worker::` | As for duties, a top-level `redis` that is Vercel KV keeps no lease, and the names in a key are percent-encoded. `scope: "process"` needs neither store. #### Lifecycle - **Start.** `run()` starts once the server serves, after the worker's own `onReady()`. A leased worker starts when this process gets the lease. The server logs `Worker "" runs in this process`. - **Restart.** When `run()` returns or throws while `signal` is not aborted, the server runs it again after a wait: `minDelayMs` the first time, then `factor` times longer each time, up to `maxDelayMs`. With the defaults: 1, 2, 4 … 60 seconds. A run that lasted longer than `maxDelayMs` starts the waits over at `minDelayMs`. - **Errors.** What `run()` throws is logged with the worker's name and never reaches the server: a failing worker does not crash it, and does not stop other workers. - **`restart: false`.** `run()` runs once. When it ends, the worker stays stopped. A leased one keeps its lease, so no other process runs it while this one is up; a process that takes the lease over later runs it once. - **Abort.** `signal` aborts at shutdown, and when this process loses the lease. An error thrown after that is not logged as a failure. A process that cannot renew the lease aborts `signal` a third of `leaseMs` before the store could give the lease to another process, so `run()` has that long to return. - **Shutdown.** The server aborts `signal` and waits for `run()` to end, up to `lifecycle.shutdownHookTimeoutMs` (3000 ms by default), then moves on. A leased worker keeps renewing its lease while `run()` ends, then releases it, so another process takes over at its next check. The worker's own `onShutdown()` runs once `run()` has ended. - **One at a time.** A process that gets the lease back while its last run is still ending waits for it before it starts the next. #### Health Each worker the server started adds a check named `worker:` to [`/readyz`](https://frontmcp.dev/reference/deployment/health-and-metrics#background-work-and-events): | `details.state` | Meaning | Status | | --- | --- | --- | | `running` | `run()` is running | `healthy` | | `standby` | Another process holds the lease, or this one has not got it yet | `healthy` | | `restarting` | `run()` ended and the server waits to run it again | `degraded` | | `stopped` | `run()` ended and `restart: false` keeps it so | `unhealthy` after an error, `healthy` after a return | `details` also holds `restarts`, how many times `run()` was started again, and `lastError`, the message of the last error it threw, until a run returns. `error` repeats `lastError` when the status is not `healthy`. While a leased worker's lease store cannot be opened, the check is `unhealthy` with `error: "the lease store cannot be opened: "`; each lease check tries again, and the worker runs once the store opens and this process gets the lease. Only `unhealthy` makes `/readyz` answer `503`. ```json {"worker:inbox-watcher":{"status":"degraded","details":{"state":"restarting","restarts":3,"lastError":"connection lost"},"error":"connection lost"}} ``` #### Where a worker runs A worker runs for as long as its server process does. | How the server runs | The worker | | --- | --- | | A long-lived Node process: `node dist/main.js`, a container | Runs until the process stops. Something else restarts the process: a container's restart policy, a service manager. | | The [shared local server](https://frontmcp.dev/reference/sdk/frontmcp-instance#frontmcpinstancerunsharedconfigorclass-options), `FrontMcpInstance.runShared()` | Runs while a session is attached, and `idleTimeoutMs` (600000 ms) after the last one left. See [below](https://frontmcp.dev/reference/sdk/worker#keeping-a-worker-alive-under-the-shared-local-server). | | A stdio server an MCP client starts | Runs only while its client is connected. | | A serverless or edge deployment, a browser | Not started. The server logs `Worker "" does not run in a serverless or edge deployment: it needs a long-lived process`. | | [`createContainer()`](https://frontmcp.dev/reference/sdk/provider#createcontaineroptions) | Not started unless `runBackground: true`. | A [lazy app](https://frontmcp.dev/reference/sdk/app#lazy-apps) cannot have a worker: the app is refused with `it has workers (""), which start with the server`. #### Errors An invalid option throws `InvalidDecoratorMetadataError` (`INVALID_DECORATOR_METADATA`) when the class is decorated, with a message that starts `@Worker invalid metadata for "":`. | Mistake | Field and message | | --- | --- | | An unknown or missing `scope` | `"scope": scope must be 'process', 'machine', 'workspace' or 'cluster'` | | `restart: true`, or another value that is not `false` or an object | `"restart": restart must be false or { minDelayMs, maxDelayMs, factor }` | | A wait below 1 ms | `"restart.minDelayMs": restart.minDelayMs must be at least 1` | | `minDelayMs` above `maxDelayMs` | `"restart.minDelayMs": restart.minDelayMs must not be greater than restart.maxDelayMs` | | A `factor` below 1 | `"restart.factor": restart.factor must be at least 1` | | `leaseMs` below 1000 | `"leaseMs": leaseMs must be at least 1000 (stores keep a TTL in whole seconds)` | | `leaseMs` with `scope: "process"` | `"leaseMs": leaseMs applies to a leased scope; a 'process' worker has no lease` | | A class without `run()` | `"run": has no run() method` | Found when the server starts: | Error | Code | When | | --- | --- | --- | | `ClusterScopeNeedsRedisError` | `CLUSTER_SCOPE_NEEDS_REDIS` | A `"cluster"` worker and no top-level `redis`. The server, or a container that runs workers, fails with `ProviderBootstrapError`, whose `originalError` it is. | | `WorkerNameConflictError` | `WORKER_NAME_CONFLICT` | Two classes give a worker of one server the same name, whatever their scopes, `"process"` included. Logged as `Provider "" failed in onReady(): Worker "" of server "" is declared by two classes in this process (A and B): give one of them its own name with @Worker({ name })`. The server stays up, and the second class does not run. `createContainer()` rejects with it. | #### Caveats - **A worker runs on the server's event loop**, not in a worker thread. For CPU-heavy work that should leave the event loop free, see [`this.offload`](https://frontmcp.dev/reference/sdk/offload). - **`run()` must return promptly once `signal` aborts.** A run that ignores it holds shutdown up for `lifecycle.shutdownHookTimeoutMs`, and after a lost lease it still runs when the next holder starts. - **A lease gives one holder at a time, not exactly-once work.** A process paused longer than its lease finds the lease gone when it wakes and aborts `signal`, while the process that took over already runs. Make what the worker does safe to resume from another process. - **A worker's name belongs to one class in its server**, whatever the scopes: a second class with it fails with `WorkerNameConflictError`. Changed in 1.12.1: before, only leased workers conflicted, so two `"process"` workers of one name both ran, and `/readyz` showed one `worker:` entry for the two. - **Don't write a retry loop inside `run()`.** Let it throw or return: the server already waits, grows the wait and reports the state to `/readyz`. - No worker starts in the Playground, which runs FrontMCP's browser build. The behavior on this page was seen with FrontMCP's Node server, one to three processes sharing a lease in the SQLite file and in Redis. --- ## Usage ### Keeping a connection open `run()` connects, handles what arrives, and closes the connection when `signal` aborts: ```ts inbox.worker.ts import { Worker, type WorkerRunContext } from "@frontmcp/sdk"; import { connectToMailbox } from "./mailbox"; @Worker({ name: "inbox-watcher", scope: "machine" }) export class InboxWatcher { async run({ signal }: WorkerRunContext) { const connection = await connectToMailbox({ signal }); try { for await (const message of connection.messages({ signal })) { await connection.store(message); } } finally { await connection.close(); } } } ``` ```ts mail.app.ts @App({ id: "mail", name: "Mail", providers: [InboxWatcher] }) export class MailApp {} ``` Started twice on one machine, the first process logs `Worker "inbox-watcher" runs in this process`, and its `/readyz` shows `"state": "running"`. The second logs `Worker "inbox-watcher" already runs elsewhere (lease ""); this one takes it over if that one stops`, and shows `"state": "standby"`. When the first is stopped with `SIGTERM`, its `run()` sees the abort and returns, its `onShutdown()` runs, and the second takes the worker over at its next lease check. When the first is killed, the second takes over once the lease expires: with `leaseMs: 3000`, within four seconds. ### Restarting after a failure When the connection drops, let `run()` throw. The server logs the cause and the wait, and runs it again: ```text Worker "inbox-watcher" runs in this process Worker "inbox-watcher" failed: connection lost; it runs again in 1000 ms Worker "inbox-watcher" failed: connection lost; it runs again in 2000 ms Worker "inbox-watcher" failed: connection lost; it runs again in 4000 ms ``` Between two runs `/readyz` shows the worker `degraded`, with `"state": "restarting"`, the count of `restarts` and the `lastError`, and still answers `200`. A `run()` that returns before its signal aborted is run again the same way, logged as a warning: `Worker "inbox-watcher" returned before its signal was aborted; it runs again in 1000 ms`. Set the waits with `restart`, or turn restarts off: ```ts @Worker({ name: "inbox-watcher", scope: "machine", restart: { minDelayMs: 300, maxDelayMs: 1000, factor: 3 } }) // waits 300, 900, 1000, 1000 ms ``` ```ts @Worker({ name: "import-archive", scope: "machine", restart: false }) // runs once ``` With `restart: false`, a run that throws logs `Worker "import-archive" failed: ; it does not run again (restart: false)`, and the check turns `unhealthy`, so `/readyz` answers `503` until the server restarts. A run that returns leaves it `healthy` with `"state": "stopped"`. ### Running one worker among several machines `scope: "cluster"` keeps one lease for every machine in the server's top-level `redis`: ```ts main.ts @Worker({ name: "inbox-watcher", scope: "cluster" }) class InboxWatcher { async run({ signal }: WorkerRunContext) { /* … */ } } @FrontMcp({ info: { name: "mail", version: "1.0.0" }, apps: [MailApp], redis: { url: process.env.REDIS_URL }, // the same Redis on every instance }) export default class Server {} ``` One instance shows `"state": "running"` in `/readyz` and the others `"state": "standby"`. When the holder's process ends, another takes the worker over. Without `redis`, the server does not start: `Worker "inbox-watcher" has scope 'cluster', which keeps one lease for every machine in Redis, and none is configured`. Use `scope: "process"` for work every instance needs for itself, like refreshing a cache in its own memory. ### Publishing events from a worker A worker that watches something tells the clients subscribed to an [event](https://frontmcp.dev/reference/sdk/event) about it. It takes the server's publisher in its constructor, by the `EventPublisher` class, and publishes from `run()`: ```ts inbox.worker.ts import { EventPublisher, Worker, type WorkerRunContext } from "@frontmcp/sdk"; import { mailReceived } from "./mail-received.event"; import { Mailbox } from "./mailbox"; @Worker({ name: "inbox-watcher", scope: "cluster" }) export class InboxWatcher { constructor( private readonly mailbox: Mailbox, private readonly events: EventPublisher, ) {} async run({ signal }: WorkerRunContext) { for await (const message of this.mailbox.messages({ signal })) { await this.events.publish(mailReceived, { messageId: message.id, from: message.from }); } } } ``` Import `EventPublisher` as a value, not with `import type`: FrontMCP injects by the class. Where the build emits no constructor types (`tsx`, esbuild), build the worker with a factory provider that injects the `EVENT_PUBLISHER` token, and register the factory in `providers` in place of the class. A worker built by a factory is supervised like one registered by its class: ```ts inbox.worker.ts import { AsyncProvider, EVENT_PUBLISHER } from "@frontmcp/sdk"; export const inboxWatcher = AsyncProvider({ provide: InboxWatcher, name: "inbox-watcher", inject: () => [Mailbox, EVENT_PUBLISHER] as const, useFactory: (mailbox, events) => new InboxWatcher(mailbox, events), }); ``` ```ts mail.app.ts @App({ id: "mail", name: "Mail", events: [mailReceived], providers: [Mailbox, inboxWatcher] }) export class MailApp {} ``` - The event must be in the `events` of an app. On a server without events, `publish()` is refused with `EventsNotEnabledError`; the run then fails and is run again after its wait, like any error. - With a leased `scope`, one process publishes. With `scope: "process"`, every copy of the server publishes its own occurrence of the same thing. - A published event also starts the workflows with [`trigger: "event"`](https://frontmcp.dev/reference/sdk/workflow#starting-from-a-published-event) that listen to its name. - A container from `createContainer()` has no publisher, so a worker that takes one cannot be built there. ### Watching files `watchFiles()` from `@frontmcp/utils` yields what happens to the files of a folder, as an async iterator a worker loops over until its `signal` aborts: ```ts drop-folder.worker.ts import { EventPublisher, Worker, type WorkerRunContext } from "@frontmcp/sdk"; import { watchFiles } from "@frontmcp/utils"; import { fileDropped } from "./file-dropped.event"; @Worker({ name: "drop-folder", scope: "machine" }) export class DropFolderWatcher { constructor(private readonly events: EventPublisher) {} async run({ signal }: WorkerRunContext) { for await (const { type, path } of watchFiles("./drop", { events: ["add", "change"], signal })) { await this.events.publish(fileDropped, { path, change: type }); } } } ``` `watchFiles(paths, options?)` takes one path or several, files or directories, relative to the working directory or absolute. `@frontmcp/utils` is installed with `@frontmcp/sdk`; add it to your own dependencies, at the same version, to import it. | Option | Type | Default | Description | | --- | --- | --- | --- | | `events` | `("add" \| "change" \| "unlink")[]` | all three | The kinds of event to yield. | | `debounceMs` | `number` | `100` | How long the directory of a path must stay quiet before its changes are yielded. | | `signal` | `AbortSignal` | none | Ends the iteration and closes the watchers when it aborts. Pass the worker's. | - Each event is `{ type, path }`, with `path` absolute. `add`: a file appeared. `change`: it was written to or replaced. `unlink`: it is gone. - A directory is watched for its direct files. Its subdirectories, and what they hold, are left out. - A path that does not exist yet is watched from the moment it appears, as a file or as a directory. - The files that are there when the watch starts are not yielded. A worker that must handle those lists the folder first. - Several writes to one file within `debounceMs` are one `change`, and a file created and removed within it yields nothing. - The iteration ends when `signal` aborts or the loop is left with `break` or `return`. - It needs Node.js. ### Keeping a worker alive under the shared local server The [shared local server](https://frontmcp.dev/reference/sdk/frontmcp-instance#frontmcpinstancerunsharedconfigorclass-options) exits when it is idle. Idle means no request and no attached session: a running worker does not count as activity. Changed in 1.12.0: before, the server exited `idleTimeoutMs` after its last request, also under attached sessions; it now stays up while a session is attached, and exits `idleTimeoutMs` after the last one left, 10 minutes by default. So a worker there stops, with its server, ten minutes after the last client went away, and starts again when a session's next request starts a new server. For a worker that must keep running without a client, turn the idle exit off: ```ts shared.ts import { FrontMcpInstance } from "@frontmcp/sdk"; import { config } from "./config"; await FrontMcpInstance.runShared(config, { key: "mail", idleTimeoutMs: false }); ``` Or run the server as a long-lived process of its own, under something that restarts it. Do not rely on a stdio server that a client starts: the worker stops when the client disconnects. ### Running workers from a script [`createContainer()`](https://frontmcp.dev/reference/sdk/provider#createcontaineroptions) builds a worker without starting it. To run workers and duties without serving MCP, ask for it: ```ts consume.ts import { createContainer } from "@frontmcp/sdk"; const container = await createContainer({ apps: [MailApp], runBackground: true, // starts the @Worker and @Duty providers info: { name: "mail" }, // the server's info.name, so the script shares its leases redis: { url: process.env.REDIS_URL }, // the server's redis, when it has one: scope "cluster" needs it }); // … await container.dispose(); // aborts the workers, waits for them, and releases their leases ``` A container has no `/readyz`, so its workers add no check. ### Checking what a worker resolves to `@Worker` checks its options when the class is decorated, so a mistake fails at import, before anything runs. `workerMetadataOf()` shows what the decorator resolved. This tool reads it from three workers that aren't registered, so none starts: Initial call configuration: ```js { tool: "describe_workers", arguments: {} } ``` ```ts workers.ts import { Worker, type WorkerRunContext } from "@frontmcp/sdk"; const untilAborted = (signal: AbortSignal) => new Promise((resolve) => signal.addEventListener("abort", resolve, { once: true })); @Worker({ name: "inbox-watcher", scope: "cluster" }) export class InboxWatcher { async run({ signal }: WorkerRunContext) { await untilAborted(signal); } } @Worker({ name: "cache-warmer", scope: "process", restart: { minDelayMs: 500, maxDelayMs: 10_000 } }) export class CacheWarmer { async run({ signal }: WorkerRunContext) { await untilAborted(signal); } } @Worker({ name: "import-archive", scope: "machine", restart: false, leaseMs: 5000 }) export class ImportArchive { async run() {} } ``` ```ts main.ts active import { App, Tool, ToolContext, workerMetadataOf } from "@frontmcp/sdk"; import { CacheWarmer, ImportArchive, InboxWatcher } from "./workers"; @Tool({ name: "describe_workers", description: "Show how each worker's options resolve", inputSchema: {} }) class DescribeWorkers extends ToolContext { async execute() { const workers = [new InboxWatcher(), new CacheWarmer(), new ImportArchive()]; return { workers: workers.map((worker) => workerMetadataOf(worker)) }; } } @App({ id: "mail", name: "Mail", tools: [DescribeWorkers] }) export class MailApp {} ``` ```ts workers.test.ts import { test, expect } from "@frontmcp/testing"; import { InvalidDecoratorMetadataError, Worker } from "@frontmcp/sdk"; const decorate = (options: Record) => () => Worker(options as never)(class Inbox { async run() {} }); test("the defaults: restarts from 1 s to 60 s, and a 15 s lease", async ({ mcp }) => { const { workers } = (await mcp.tools.call("describe_workers", {})).json(); expect(workers).toEqual([ { name: "inbox-watcher", scope: "cluster", leaseMs: 15000, restart: { minDelayMs: 1000, maxDelayMs: 60000, factor: 2 } }, { name: "cache-warmer", scope: "process", leaseMs: 15000, restart: { minDelayMs: 500, maxDelayMs: 10000, factor: 2 } }, { name: "import-archive", scope: "machine", leaseMs: 5000, restart: false }, ]); }); test("a worker needs a scope and a run() method", () => { expect(decorate({})).toThrow(InvalidDecoratorMetadataError); expect(decorate({})).toThrow(`@Worker invalid metadata for "scope": scope must be 'process', 'machine', 'workspace' or 'cluster'`); expect(() => Worker({ scope: "process" })(class Inbox {} as never)).toThrow('@Worker invalid metadata for "run": Inbox has no run() method'); }); test("restart is false or the waits, and the waits must make sense", () => { expect(decorate({ scope: "process", restart: true })).toThrow('@Worker invalid metadata for "restart": restart must be false or { minDelayMs, maxDelayMs, factor }'); expect(decorate({ scope: "process", restart: { minDelayMs: 0 } })).toThrow("restart.minDelayMs must be at least 1"); expect(decorate({ scope: "process", restart: { minDelayMs: 5000, maxDelayMs: 1000 } })).toThrow("restart.minDelayMs must not be greater than restart.maxDelayMs"); expect(decorate({ scope: "process", restart: { factor: 0.5 } })).toThrow("restart.factor must be at least 1"); }); test("a lease is at least a second, and a process worker has none", () => { expect(decorate({ scope: "machine", leaseMs: 500 })).toThrow("leaseMs must be at least 1000 (stores keep a TTL in whole seconds)"); expect(decorate({ scope: "process", leaseMs: 5000 })).toThrow("leaseMs applies to a leased scope; a 'process' worker has no lease"); }); ``` ### Testing `run()` without a server A worker is a class: a test can build it and call `run()` with a signal of its own. That checks the two things the server relies on, without waiting for a real connection: `run()` returns when its signal aborts, and it leaves by throwing when its work fails. **Hidden fixture/test file (runs with the example):** ```ts main.ts hidden import { App } from "@frontmcp/sdk"; @App({ name: "Mail" }) export class MailApp {} ``` ```ts inbox.worker.ts import { Worker, type WorkerRunContext } from "@frontmcp/sdk"; import { Mailbox } from "./mailbox"; @Worker({ name: "inbox-watcher", scope: "machine" }) export class InboxWatcher { constructor(private readonly mailbox: Mailbox) {} async run({ signal }: WorkerRunContext) { for await (const message of this.mailbox.messages(signal)) { this.mailbox.stored.push(message); } } } ``` ```ts mailbox.ts /** A stand-in for a mail connection: messages arrive with deliver(), and the connection drops with fail(). */ export class Mailbox { readonly stored: string[] = []; open = false; private arrived: string[] = []; private failure?: Error; private wake: () => void = () => {}; deliver(message: string) { this.arrived.push(message); this.wake(); } fail(error: Error) { this.failure = error; this.wake(); } async *messages(signal: AbortSignal): AsyncGenerator { this.open = true; signal.addEventListener("abort", () => this.wake(), { once: true }); try { while (!signal.aborted) { if (this.failure) throw this.failure; const message = this.arrived.shift(); if (message === undefined) await new Promise((resolve) => (this.wake = resolve)); else yield message; } } finally { this.open = false; } } } ``` ```ts inbox.test.ts active import { test, expect } from "@frontmcp/testing"; import { InboxWatcher } from "./inbox.worker"; import { Mailbox } from "./mailbox"; test("run() handles messages until its signal aborts, then returns", async () => { const mailbox = new Mailbox(); const controller = new AbortController(); const running = new InboxWatcher(mailbox).run({ signal: controller.signal }); mailbox.deliver("m1"); mailbox.deliver("m2"); await new Promise((resolve) => setTimeout(resolve, 10)); expect(mailbox.stored).toEqual(["m1", "m2"]); expect(mailbox.open).toBe(true); controller.abort(); await running; expect(mailbox.open).toBe(false); }); test("a lost connection leaves run() by throwing, which is what makes the server run it again", async () => { const mailbox = new Mailbox(); const running = new InboxWatcher(mailbox).run({ signal: new AbortController().signal }); mailbox.fail(new Error("connection lost")); await expect(running).rejects.toThrow("connection lost"); expect(mailbox.open).toBe(false); }); ``` --- ## Troubleshooting ### The worker never starts It is not in a `providers` array, the server runs serverless or on the edge, or a `createContainer()` was built without `runBackground: true`. A leased worker whose `/readyz` check says `standby` runs in another process. ### `Worker "…" failed: …; it runs again in … ms`, over and over `run()` throws on every start. Read the cause in the log line, or in `lastError` in `/readyz`. A `run()` that returns right away loops the same way, with `returned before its signal was aborted`: keep it pending until `signal` aborts. Raise `restart.minDelayMs` to slow the attempts down. ### The worker stops a few minutes after the last client left It runs under the shared local server, which exited idle. Pass `idleTimeoutMs: false` to `runShared()`, or run a long-lived server: see [keeping a worker alive](https://frontmcp.dev/reference/sdk/worker#keeping-a-worker-alive-under-the-shared-local-server). ### `Worker "…" has scope 'cluster', which keeps one lease for every machine in Redis, and none is configured` `ClusterScopeNeedsRedisError` stopped startup. Add a top-level `redis` to `@FrontMcp()`, or to `createContainer()` in a script, or use `scope: "machine"`. ### `Worker "…" of server "…" is declared by two classes in this process` Two classes give a worker of the server the same name, and the second one did not start, whatever their scopes. Give one of them its own `name`. ### `Worker "…" already runs elsewhere` with one server Another server on the machine has the same `info.name` and a worker with the same name. Give the server a distinctive `info.name`, or the worker its own `name`. ### `Provider "…" onShutdown() did not finish within 3000 ms` `run()` did not end when `signal` aborted, so shutdown waited for `lifecycle.shutdownHookTimeoutMs` and moved on, and the worker's own `onShutdown()` did not run before the process exited. Pass `signal` to what `run()` awaits, or return on its `abort` event. ### `Provider InboxWatcher depends on Object, which is not registered (local or parent).` The worker's constructor names `EventPublisher`, and it was imported with `import type`, so the build recorded `Object` in its place. Import it as a value, or build the worker with a factory that injects `EVENT_PUBLISHER`: see [publishing events](https://frontmcp.dev/reference/sdk/worker#publishing-events-from-a-worker). ### `/readyz` answers `503` because of a worker A `restart: false` worker ended on an error: fix the cause and restart the server, or let it restart. Or its lease store cannot be opened (`the lease store cannot be opened: `): with `Invalid sqlite configuration: the sqlite type needs @frontmcp/storage-sqlite`, install that package or set a top-level `redis`. The worker starts at the next lease check once the store opens. In production the answer leaves the checks out unless `health.includeDetails` is `true`. ### Two processes run the worker for a moment The old holder was paused past its lease, or its `run()` ignores `signal`. Return on `signal`, keep the event loop free, or raise `leaseMs`. --- # @Job > Declare a unit of work with validated input that clients run by name, while they wait or in the background, with retries. Source: https://frontmcp.dev/reference/sdk/job [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@Job` declares a [job](https://frontmcp.dev/learn/your-first-job): a piece of work with validated input that a client starts by name, with the built-in `execute_job` tool. A job can run while the client waits, or [in the background](https://frontmcp.dev/learn/running-jobs-in-the-background) while the client does something else, and FrontMCP can retry it when it fails. Jobs are also the steps of a [`@Workflow`](https://frontmcp.dev/reference/sdk/workflow). ```ts @Job(options) class MyJob extends JobContext { async execute(input) { /* ... */ } } ``` --- ## Reference ### `@Job(options)` Apply `@Job` to a class that extends `JobContext`, and list the class in an app's `jobs` array. FrontMCP then adds the tools that run jobs to the server; you don't write a tool for each job. ```ts count-open.job.ts import { Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "count-open-tickets", description: "Count a customer's open tickets", inputSchema: { customer: z.string() }, outputSchema: { customer: z.string(), open: z.number() }, retry: { maxAttempts: 3, backoffMs: 500 }, }) export class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { this.log(`Counting open tickets for ${customer}`); const open = await countOpenTickets(customer); return { customer, open }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CountOpenTickets } from "./count-open.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] }) export class HelpDeskApp {} ``` [See more examples below.](https://frontmcp.dev/reference/sdk/job#usage) #### Options Required: | Option | Type | Description | | --- | --- | --- | | `name` | `string` | What clients pass to `execute_job`, and what a workflow step's `jobName` refers to. Unique within the server. If you also set `id`, the id replaces it. | | `inputSchema` | object of Zod types | One Zod type per input field, like `{ customer: z.string() }`. `execute_job` checks the input against it before `execute()` runs. | | `outputSchema` | object of Zod types, or any output schema a [tool](https://frontmcp.dev/reference/sdk/tool#options) accepts | The shape of the result. TypeScript checks `execute()`'s return type against it, and FrontMCP checks the result when the job runs: fields it doesn't declare are dropped, and a result that doesn't match fails the run with `INVALID_OUTPUT`, without a retry. See [Troubleshooting](https://frontmcp.dev/reference/sdk/job#tool-output-validation-failed-output-does-not-match-outputschema-at-). (Changed in 1.9.2: before, the result wasn't checked at run time.) | Optional: | Option | Type | Default | Description | | --- | --- | --- | --- | | `description` | `string` | | What the job does. `list_jobs` shows it. | | `id` | `string` | `name` | A stable identifier. When set, it **replaces** `name`: clients, `list_jobs` and workflow steps all use the id. | | `retry` | `JobRetryConfig` | none: one attempt | Run `execute()` again when it throws. See [`retry`](https://frontmcp.dev/reference/sdk/job#retry). | | `timeout` | `number` | server default | Maximum milliseconds per attempt; `0` disables the deadline. When unset, uses `jobs.defaultTimeoutMs` (300000). Applies to `execute_job` too. | | `cleanup` | `JobCleanup \| { run: JobCleanup; timeoutMs?: number }` | none | Called with the attempt's instance and reason (`"interrupt"`, `"timeout"` or `"cancel"`). Default cleanup limit: 3000 ms. A failure only logs a warning. | | `runner` | `"inline" \| "worker" \| "detached"` | `jobs.runner`, else `"inline"` | Event loop, offload worker pool, or a Node process that survives the server. | | `tags` | `string[]` | `[]` | Labels to filter `list_jobs` by. | | `labels` | `Record` | `{}` | Key-value labels to filter `list_jobs` by. | | `hideFromDiscovery` | `boolean` | `false` | Leave the job out of `list_jobs`. It still runs by name. | | `permissions` | `JobPermission[]` | none: anyone may run it | Who may run and list the job. See [`permissions`](https://frontmcp.dev/reference/sdk/job#permissions). | #### `retry` | Field | Type | Default | Description | | --- | --- | --- | --- | | `maxAttempts` | `number` | `3` | Attempts in all, counting the first. | | `backoffMs` | `number` | `1000` | How long to wait before the second attempt, in milliseconds. | | `backoffMultiplier` | `number` | `2` | Each wait is this many times longer than the one before. | | `maxBackoffMs` | `number` | `60000` | The longest any one wait can be. | The wait after attempt *n* is `backoffMs × backoffMultiplier^(n−1)`, capped at `maxBackoffMs`. The defaults apply as soon as you set `retry`: `retry: {}` means three attempts, with waits of 1 and 2 seconds. A job without `retry` runs once, including as a workflow step. Changed in 1.11.3: before, a workflow step without a retry policy was tried three times. #### `permissions` Each entry is a rule for one action: | Field | Type | Description | | --- | --- | --- | | `action` | `"execute" \| "list" \| "delete" \| "create" \| "read" \| "update"` | What the rule guards. FrontMCP checks `execute` (when `execute_job` starts a run, again before each attempt, and for a workflow step that runs the job), `list` (`list_jobs`) and `delete` (`remove_job`). `read` permits reading another caller's run, and `delete` also permits cancelling it. `create` gates submission of a new run, whatever submits it: `execute_job`, `execute_workflow`, or a workflow's [webhook, event or schedule](https://frontmcp.dev/reference/sdk/workflow#workflow-triggers), whose runs carry the role `webhook:`, `event:` or `schedule:` (schedules are new in 1.12.0). It is checked once, with `execute`, before the run exists. `update` gates changes through `update_job` or `update_workflow`. Workflow steps check the job's `execute` rules without submitting a new job run through `execute_job`. | | `roles` | `string[]` | The caller needs at least one of these, in their `roles` claim. | | `scopes` | `string[]` | The caller needs at least one of these, in their token's `scope` claim. | | `custom` | `(authInfo) => boolean \| Promise` | Your own check. It receives the caller's `authInfo`, with the token's claims in `authInfo.user`. For `execute`, it runs when the run starts and again before each attempt: four times for a job that runs three times. (Changed in 1.9.4: before, once per run.) | A rule passes when each of its fields passes, and the caller needs every rule for the action. `list_jobs` leaves out jobs the caller can't list, submit **or** run. A caller who isn't allowed to run a job gets the same error as for a job that doesn't exist, so they can't find out which jobs exist by guessing names. When the check before a later attempt refuses the caller, as a `custom` check can, the run fails at once, without a retry. #### `execute(input)` FrontMCP calls `execute()` once the input passes validation, and again for each retry. - `input`: the validated input. Fields with a `.default()` are filled in, and fields that aren't in `inputSchema` are dropped. The same object is `this.input`. - **Returns** the job's result: `result` in what `execute_job` returns, and `outputs` when the job is a workflow step, where later steps read it. Return an object. To fail, throw, or call `this.fail()`. A failed attempt is retried if the job has `retry`, except public errors, invalid output, authorization denials, cancellations, interruptions and admission timeouts. #### `JobContext` Inside `execute()`, `this` is the `JobContext`: | Member | Description | | --- | --- | | `this.log(message)` | Adds a line to the run's `logs`, prefixed with the time: `[2026-09-27T09:00:00.000Z] message`. Only the lines of the attempt that succeeded are kept, and a failed run's `logs` is empty, but every line also goes to the server's log. | | `this.input` | The validated input. | | `this.get(token)`, `this.tryGet(token)` | [Providers](https://frontmcp.dev/reference/sdk/provider), from the job's app and from the server. See [Using a provider](https://frontmcp.dev/reference/sdk/job#using-a-provider). (Changed in 1.9.2: before, a job only saw the server's.) | | `this.fail(error)` | Ends the attempt with `error`. The message and code of a `PublicMcpError` reach the client as they are. | | `this.auth` | The caller who started the run, as in [tools](https://frontmcp.dev/reference/sdk/auth): `user.sub`, `isAnonymous`, `roles`, `scopes`. | | `this.callTool(name, args)` | Calls a tool of the server as the caller who started the run, on the `"job"` surface: a tool whose `availableWhen.surface` leaves out `"job"` answers `Tool "…" not found`. See [`this.callTool()`](https://frontmcp.dev/reference/sdk/call-tool#where-it-works). | | `this.context`, `this.fetch()` | The request's context, as in a tool. When `execute_job` runs the job while the client waits, it's the caller's; in the background, it's a copy with the same session, caller and trace, and a request id of its own. `this.fetch()` sends the tracing headers, `traceparent` and `x-request-id`. See [Calling another service from a job](https://frontmcp.dev/reference/sdk/job#calling-another-service-from-a-job). [Context classes](https://frontmcp.dev/reference/sdk/contexts) compares every member. (Changed in 1.9.2: before, `this.context` threw in a job, and `this.fetch()` sent no tracing headers.) | | `this.workerEnv` | On a Cloudflare Worker, the bindings of the request that ran `execute_job`, when it runs the job while the client waits. On a server from [`create()`](https://frontmcp.dev/reference/sdk/create#call-options), the `workerEnv` of the `executeJob()` call, or else of the server, in the background too. `undefined` elsewhere. (Since 1.9; before, always `undefined`. Changed in 1.9.4: before, a server from `create()` had none.) | | `this.metadata` | The job's options. | | `this.attempt` | The attempt number, from 1: `2` on the first retry. See [Retrying a job that fails](https://frontmcp.dev/reference/sdk/job#retrying-a-job-that-fails). (Changed in 1.9.2: before, it was always `1`.) | | `this.progress(progress, total?, message?)` | Records `{ progress, total?, message? }` on a job run and announces a resource update. Workflow steps have no run recorder. Also sends a session notification when a session exists. Returns `true` when either succeeds. | | `this.signal` | An `AbortSignal` for each attempt: aborts on the step deadline in a workflow, and on timeout, cancellation or shutdown for `execute_job`. Pass it to cancellable work or check it in a loop. `this.fetch()` uses it. Work that ignores it can continue after the attempt ends. | | `this.respond(value)` | Ends the attempt with `value` as the job's result, as returning it does, and `value` is checked against `outputSchema` the same way. (Changed in 1.9.2: before, `value` replaced the whole `execute_job` response.) | ### `job(options)(handler)` The function form takes the same options. `handler(input, ctx)` receives the validated input and the `JobContext`. List the result in `jobs` like a class. ```ts import { job, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; export const countOpenTickets = job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { customer: z.string(), open: z.number() }, })(async ({ customer }, ctx) => { return { customer, open: ctx.get(TicketStore).openFor(customer).length }; }); ``` `ctx.log()` and `ctx.progress()` work in a handler. `fail()` is `protected`, so TypeScript rejects `ctx.fail()` with error `TS2445`: throw a `PublicMcpError` instead, which fails the attempt the same way. (Changed in 1.9.1: before, `log()` and `progress()` were `protected` too.) ### `JobHook` Changed in 1.10.16: when a hook calls `ctx.fail(error)`, the attempt records that error's message instead of an empty control-flow message. An aborted attempt records `Flow aborted: ` instead of `The job attempt ended before it produced a result`. `ctx.error` exposes the first failure, and `JobHook.Finally(stage)` runs cleanup after any outcome of that stage. Each attempt of a job runs the [`jobs:execute-job` flow](https://frontmcp.dev/reference/server/flows#jobsexecute-job): a run `execute_job` starts, inline or in the background, each retry, and each workflow step. `JobHook` hooks it, as [`ToolHook`](https://frontmcp.dev/reference/sdk/hooks#decorator-sets-and-their-flows) hooks tool calls, and `FlowCtxOf<"jobs:execute-job">` types the hook's `ctx`. `@frontmcp/sdk` also exports the flow's class as the type `ExecuteJobFlow`. A hook runs once per attempt: three times for a job that succeeds on its third. (New in 1.9.4: before, jobs ran through no flow.) | Stage | Group | What it does | | --- | --- | --- | | `parseInput` | first | Sets `job`, `attempt`, `runId`, `workflow`, `authInfo` and `input`. | | `checkJobAuthorization` | first | Checks the job's `execute` [`permissions`](https://frontmcp.dev/reference/sdk/job#permissions) against the caller. A refusal fails the run with `JOB_NOT_AUTHORIZED`, without a retry. | | `validateInput` | first | Parses `input` with `inputSchema` into `parsedInput`. | | `admit` | first | Waits for the scope's admission slot. | | `createJobContext` | first | Builds the job's instance, the `JobContext`, as `jobContext`. | | `execute` | execute | Runs `execute()`. | | `validateOutput` | execute | Parses the result with `outputSchema`, and sets `answer`: `{ result, logs }`. | | `cleanup` | error | Runs the job's cleanup when an attempt was interrupted, timed out or cancelled after its instance was built. | | `updateRunState` | always | Records the attempt on the run, including timeout, cancellation and interruption states. | | `finalize` | always | Answers with `answer`. | `ctx.state` has: | Field | What it is | | --- | --- | | `job` | The job: `name`, and `metadata`, its options. | | `attempt` | The attempt number, from 1. | | `runId` | The run's id. `undefined` for a workflow step, whose workflow run keeps the record. | | `workflow` | For a workflow step, `{ name, stepId, runId }`: the workflow, the step's `id` and the workflow run's id. `undefined` otherwise. | | `authInfo` | The caller who started the run. | | `input`, `parsedInput` | The job's input as given, and once `inputSchema` has parsed it. A hook before `validateInput` can replace `input`. | | `jobContext` | The job's instance, from `createJobContext` on. | | `answer` | `{ result, logs }`, from `validateOutput` on. | | `flowError` | In the `always` stages, the error that failed the attempt. | - **Where hooks go.** A hook on a plugin or a provider of an app runs for that app's jobs; on `@FrontMcp`, for every job. On a `@Job` class, it runs for that job's attempts only: as an instance method from `createJobContext` on, with the job's context as `this`, or as a `static` method on any stage, with the class as `this`. A hook for another flow on a `@Job` class stops the server from starting. See [Hooking every attempt of a job](https://frontmcp.dev/reference/sdk/job#hooking-every-attempt-of-a-job). - **A hook that throws fails the attempt**, and the job's `retry` applies, unless the error is public, including `JobNotAuthorizedError`. A throw from a `Finally` hook is logged and ignored. - **`ctx.respond({ result, logs })`** answers for the job, from a cache say: the stages that haven't run are skipped, `execute()` included, apart from the `always` group, and the run completes with `result` and `logs`. `result` is checked against `outputSchema`: extra fields are dropped, and a mismatch fails with `INVALID_OUTPUT` without retrying. Changed in 1.9.5: before, hook results skipped validation. ### Built-in tools When any app declares a job or a workflow, FrontMCP adds these tools to the server: | Tool | In `tools/list` | Arguments | Returns | | --- | --- | --- | --- | | `execute_job` | Yes | `name`, `input?` (an object, default `{}`), `background?` (default `false`) | Without `background`: waits for the job, then `{ runId, state, uri, result, logs }`. With `background: true`: `{ runId, state: "pending", uri }` at once. | | `get_job_status` | Yes | `runId` | `{ runId, jobName, state, result?, error?, startedAt, completedAt?, attempt, logs }`. Times are milliseconds since 1970. It also reads a workflow's run, whose `result` holds the step results. The owner or a caller passing an explicit `read` rule can read it: see [who can read a run](https://frontmcp.dev/reference/sdk/job#who-can-read-a-run). | | `cancel_job` | Yes | `runId` | `{ runId, state: "cancelled" }`. Owner or a caller passing an explicit `delete` rule only. Cannot cancel workflows or finished runs. | | `list_jobs` | No | `query?`, `tags?`, `labels?` | `{ jobs: [{ name, description?, tags, labels, inputSchema? }], count }`. `query` matches the name or description; `tags` needs any one of them; `labels` needs all of them. | | `update_job` | No; requires dynamic registration | `name`, `script?`, `inputSchema?`, `outputSchema?`, `description?`, `tags?` | `{ success, jobId }`; replaces supplied fields on a dynamic job, subject to `update` permissions. | | `remove_job` | No | `name` | Removes a job registered at run time with `register_job`. For a `@Job` class it fails with `Job "…" is not a dynamic job and cannot be removed`. | `execute_workflow` and `get_workflow_status` come with them; see [`@Workflow`](https://frontmcp.dev/reference/sdk/workflow#built-in-tools). Tools that aren't in `tools/list` can still be called by name. The update tools are exported as `UpdateJobTool` and `UpdateWorkflowTool`. The built-in tool classes are exported from `@frontmcp/sdk` and `@frontmcp/sdk/job/tools`; both paths return the same classes. Changed in 1.11.0: before, the subpath shipped types without loadable JavaScript. Another job tool, `register_job`, registers a job from a script sent by the client. It exists only on servers that set `jobs: { enabled: true, allowDynamicRegistration: true }`, and isn't in `tools/list` there either. It runs code a client sent you, so leave it off unless you know you need it. #### `@FrontMcp({ jobs })` The server's `jobs` option controls the subsystem. You don't need it to use jobs. | Option | Type | Default | Description | | --- | --- | --- | --- | | `enabled` | `boolean` | on when an app declares jobs or workflows | Required when you set `jobs`. `false` leaves the tools out even when apps declare jobs; `true` adds them even when none do. | | `store` | `false \| { redis?, sqlite?, keyPrefix? }` | top-level Redis except Vercel KV, then SQLite, then memory | Storage for runs and dynamic definitions. `false` forces memory. SQLite needs a `path`; Redis takes the server's Redis options. Explicit Redis and SQLite are mutually exclusive. Vercel KV is unsupported for job stores. | | `defaultTimeoutMs` | `number` | `300000` | Deadline per attempt when a job sets no `timeout`. `0` disables it. | | `runner` | `"inline" \| "worker" \| "detached"` | `"inline"` | Default runner. A job may override it. | | `admission` | `{ concurrency?: number; memoryMb?: number; maxWaitMs?: number }` | no cap; `maxWaitMs: 600000` | Bounds concurrent attempts and memory claims per scope, for jobs and workflow steps. An `execute_job` deadline starts at execution; a workflow step's timeout includes its wait for admission. | | `allowDynamicRegistration` | `boolean` | `false` | Adds `register_job`, `register_workflow`, `update_job` and `update_workflow`. | The Playground always uses the memory store: Redis needs Node. The `redis` fields were checked in Node against a Redis that needs a password. Without the right password, the server doesn't start: `NOAUTH Authentication required.` when there's none, `WRONGPASS invalid username-password pair` when it's wrong. A field that contradicts the `url` stops it with a `ZodError` that names the field, like `redis password contradicts redis.url`. #### Run states | State | Meaning | | --- | --- | | `pending` | Created, not started yet. A background call returns this. | | `running` | An attempt is running. | | `retrying` | An attempt failed, and the job is waiting before the next one. | | `completed` | `result` holds the result. | | `timed_out` | The last attempt exceeded its deadline. | | `cancelled` | A caller cancelled the run. | | `interrupted` | The server shut down or its runner disappeared. | | `failed` | Every attempt failed. `error` holds the last error's `message` and `name`. | #### Who can read a run A run belongs to the user who started it, identified by their token's issuer (`iss`) and `sub`: in-process callers of `create()` and `createDirect()` have the issuer `direct`, unless their `authContext.user` sets an `iss`. `get_job_status` and `job://runs/{runId}` answer that user or a caller passing the entry's explicit `read` permission rule. Other callers get `Run "" not found` from the tool, or `Resource not found: job://runs/` from the resource, as if the run did not exist. A run another server or endpoint started isn't reachable from this one, even when they share a store. Changed in 1.12.1: before, the owner was the `sub` alone, and a shared store let any of them reach the run. A run stored before 1.12.1, with no `ownerIss`, now belongs only to a caller whose token has no issuer. A run a workflow's [schedule](https://frontmcp.dev/reference/sdk/workflow#schedule-options) started has no owner, so only a caller passing an explicit `read` rule reads it. An anonymous caller on protocol 2026-07-28 gets a new identity on every request (`anon:` and a random id), so **it cannot prove ownership of its runs** without an explicit `read` rule. That includes the Playground. To let clients poll background runs, [authenticate them](https://frontmcp.dev/learn/authenticating-clients). The examples below poll as a signed-in user, in-process, with `FrontMcpInstance.createDirect()`. #### Caveats - The class **must extend `JobContext`**, and like [`@Tool`](https://frontmcp.dev/reference/sdk/tool#caveats), `@Job` checks when TypeScript compiles that `execute()`'s parameter matches `inputSchema` and its return type matches `outputSchema`. - **Hooks run once per attempt.** A [`JobHook`](https://frontmcp.dev/reference/sdk/job#jobhook) sees every retry and every workflow step as an attempt of its own. Since 1.9.4: before, jobs ran through no flow, so a hook on the `execute_job` tool's call missed retries, background attempts and workflow steps, and a hook on a `@Job` class stopped the server from starting. - A result that **doesn't match `outputSchema` isn't retried**: the run fails at once, whatever `retry` says. - Changed in 1.11.0: before, `execute_job` ignored `timeout`. Every attempt now has a deadline; use `0` for no limit. - Changed in 1.11.3: before, bad input used a generic error code and public errors were retried. Bad input now fails once with `INVALID_INPUT` and the Zod issues, without a stack. A `PublicMcpError` or subclass is not retried. Throw a plain `Error` or `InternalMcpError` for a retryable failure. - Changed in 1.11.0: before, jobs used memory unless `jobs.store` was set. They now inherit top-level Redis (except Vercel KV) or SQLite. Use `jobs.store: false` to keep them in memory. ### Runners and durable run handles `runner: "inline"` is the default. `"worker"` uses the [offload pool](https://frontmcp.dev/reference/sdk/offload), where providers are unavailable. `"detached"` requires a shared job store and a Node server launched from a runnable entry (`bootstrap()`, `runStdio()`, `runUnixSocket()` or `@FrontMcp`); in-process `create()`, `connect()` and the generated CLI cannot start detached runs. On a shared store, runner heartbeats allow a restarting server to reconcile unfinished runs. A run whose runner disappeared becomes `interrupted` and its cleanup runs in the reconciling server; a live detached run is watched. Shutdown interrupts inline runs and waits at most `lifecycle.shutdownHookTimeoutMs`. Read the `uri` returned by `execute_job` (`job://runs/{runId}`) for JSON with `state`, `progress`, `revision`, `updatedAt`, result or error and logs. Revisions advance on writes. Subscribers get resource-update notifications for writes made by that process. Access follows the same owner or explicit `read` rule as status polling; cancellation uses the owner or explicit `delete` rule. `cancel_job` cannot cancel workflows. ### Custom execution managers and stores Most servers use the manager FrontMCP creates. A custom host can construct `new JobExecutionManager(stateStore, logger, notifyFn?, scope?, options?)`. Its new options are: | Option | Type | Default | Description | | --- | --- | --- | --- | | `defaultTimeoutMs` | `number` | `300000` | Attempt deadline; `0` disables it. | | `admission` | `JobAdmission` | none | Admission controller shared by this manager's attempts: `new JobAdmission({ concurrency?, memoryMb?, maxWaitMs? })`, the options of `jobs.admission`. See [below](https://frontmcp.dev/reference/sdk/job#the-helpers-a-custom-host-uses). | | `cancelPollMs` | `number` | no polling | Interval for checking cancellation written by another process. | | `runner` | `JobRunner` | `"inline"` | Default runner. | | `findJob` | `(name: string) => JobEntry \| undefined` | none | Resolve a detached run's job or an orphaned run's cleanup. | | `detachedUnavailable` | `{ why: string; remedy: string }` | none | Refuse detached runs with this explanation. | | `spawnDetached` | `(runId: string) => { pid?: number; once(event: "error", listener: (error: Error) => void): unknown }` | rerun the server's command | Start a detached worker. | `cancel(runId)` returns `Promise` and cancels an unfinished job. `dispose(timeoutMs?)` interrupts this manager's active runs and waits, optionally with a deadline; detached runs keep running. `reconcile()` settles runs whose runner disappeared and watches live detached runs. `runDetached(runId)` executes that run in the current worker process; an unknown or finished run is left alone. Both return `Promise`. Custom `JobStateStore` implementations can add these optional methods: | Method | Returns | Description | | --- | --- | --- | | `requestCancel(runId)` | `Promise` | Keep a cancellation request visible to every process. | | `isCancelRequested(runId)` | `Promise` | Read that cancellation request. Without these methods, the manager checks the run's `cancelled` state. | | `touchRunner(runnerId, ttlSeconds)` | `Promise` | Renew a runner heartbeat with the store's TTL. | | `isRunnerAlive(runnerId)` | `Promise` | Check the heartbeat. Without heartbeat methods, liveness uses the PID on its host. | | `claimRun(runId)` | `Promise` | Atomically let one reconciler settle an orphan and run cleanup. | `createRun()` starts at revision 1; `updateRun()` increments the revision and stamps `updatedAt`. Run records can carry `progress`, `runner` and `scopeId`. A run's resource URI is `job://runs/{runId}`, and [who can read a run](https://frontmcp.dev/reference/sdk/job#who-can-read-a-run) gives the access rules the built-in tools and that resource apply. #### The helpers a custom host uses `@frontmcp/sdk` exports what the built-in job tools use to limit attempts and check access, so a host of your own can do the same. New in 1.11.1: before, none of the three was exported. | Export | What it does | | --- | --- | | `new JobAdmission({ concurrency?, memoryMb?, maxWaitMs? })` | Limits the attempts that run at once, as `jobs.admission` does: `concurrency` attempts, each claiming `memoryMb` of free memory, admitted in the order they arrived. `maxWaitMs` defaults to `600000`. Pass it as the manager's `admission`. `slot()` returns a `JobAdmissionSlot`, a type `@frontmcp/sdk` exports too: `acquire(jobName, signal?)` waits for a place, and rejects with `JobAdmissionTimeoutError` after `maxWaitMs`; `release()` frees it. | | `jobRunUri(runId)` | The run's resource URI, `job://runs/`. | | `mayAccessRun(scope, run, action, authInfo)` | `Promise`: whether the caller in `authInfo` may `"read"` or `"delete"` (cancel) the run, by the rules in [who can read a run](https://frontmcp.dev/reference/sdk/job#who-can-read-a-run): the owner may, and anyone else only through the job's or workflow's `permissions` rule for that action. `scope` is the `ScopeEntry`, `this.scope` in a tool. | Initial call configuration: ```js { tool: "run_handle", arguments: { runId: "run-1" } } ``` ```ts run-handle.tool.ts active import { jobRunUri, mayAccessRun, Tool, ToolContext, z, type JobRunRecord } from "@frontmcp/sdk"; // A run as your host's own store keeps it. const runs = new Map([ ["run-1", { runId: "run-1", jobId: "export-invoices", jobName: "export-invoices", ownerSub: "nour", ownerIss: "direct", state: "completed", input: {}, startedAt: 0, attempt: 1, maxAttempts: 1, logs: [], background: true }], ]); @Tool({ name: "run_handle", description: "Get the resource URI of a run the caller may read", inputSchema: { runId: z.string() } }) export class RunHandle extends ToolContext { async execute({ runId }: { runId: string }) { const run = runs.get(runId); const readable = run !== undefined && (await mayAccessRun(this.scope, run, "read", this.context.authInfo)); return { uri: readable ? jobRunUri(run.runId) : null }; } } ``` ```ts help-desk.app.ts import { App, Job, JobContext, z } from "@frontmcp/sdk"; import { RunHandle } from "./run-handle.tool"; @Job({ name: "export-invoices", description: "Export a month's invoices", inputSchema: { month: z.string() }, outputSchema: { month: z.string(), invoices: z.number() }, permissions: [{ action: "read", roles: ["billing"] }], }) class ExportInvoices extends JobContext { async execute({ month }: { month: string }) { return { month, invoices: 42 }; } } @App({ id: "help-desk", name: "Help Desk", tools: [RunHandle], jobs: [ExportInvoices] }) export class HelpDeskApp {} ``` ```ts host.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance, JobAdmission } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; const callers = { owner: { authContext: { user: { sub: "nour" } } }, billing: { authContext: { user: { sub: "li", roles: ["billing"] } } }, stranger: { authContext: { user: { sub: "sam" } } }, }; test("the owner and the job's read rule may read the run, no one else", async () => { const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); try { for (const [who, expected] of [["owner", "job://runs/run-1"], ["billing", "job://runs/run-1"], ["stranger", null]] as const) { expect((await server.callTool("run_handle", { runId: "run-1" }, callers[who])).structuredContent).toEqual({ uri: expected }); } } finally { await server.dispose(); } }); test("JobAdmission admits one attempt at a time, and refuses one that waits too long", async () => { const admission = new JobAdmission({ concurrency: 1, maxWaitMs: 100 }); const first = admission.slot(); await first.acquire("export-invoices"); await expect(admission.slot().acquire("export-invoices")).rejects.toThrow( 'Job "export-invoices" waited 100 ms to start and was not admitted: 1 of 1 job runs are busy', ); first.release(); await admission.slot().acquire("export-invoices"); }); ``` The Playground's own call is anonymous, so it gets `{ "uri": null }`: an anonymous caller isn't the owner, and has no `billing` role. --- ## Usage ### Cancelling a run and reading its handle This job waits for cancellation. The test uses one signed-in caller so its later requests own the same run. ```ts main.ts active import { App, Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "wait-for-cancel", description: "Wait until the owner cancels the run", inputSchema: {}, outputSchema: { stopped: z.boolean() }, timeout: 5000 }) class WaitForCancel extends JobContext { async execute() { await new Promise((resolve) => { if (this.signal?.aborted) return resolve(); this.signal?.addEventListener("abort", () => resolve(), { once: true }); }); return { stopped: true }; } } @App({ name: "Desk", jobs: [WaitForCancel] }) export class Desk {} ``` ```ts cancel.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { Desk } from "./main"; test("the owner cancels a run and reads its resource", async () => { const server = await FrontMcpInstance.createDirect({ info: { name: "desk", version: "1.0.0" }, apps: [Desk] }); const caller = { authContext: { user: { sub: "nour" } } }; try { const started = await server.callTool("execute_job", { name: "wait-for-cancel", background: true }, caller); const { runId, uri } = started.structuredContent as { runId: string; uri: string }; const cancelled = await server.callTool("cancel_job", { runId }, caller); expect(cancelled.structuredContent).toEqual({ runId, state: "cancelled" }); const resource = await server.readResource(uri, caller); const record = JSON.parse((resource.contents[0] as { text: string }).text); expect(record.state).toBe("cancelled"); expect(record.revision).toBeGreaterThan(0); } finally { await server.dispose(); } }); ``` ### Running a job and reading its result Call `execute_job` with the job's `name` and its `input`. It waits for the job and returns the run: its id, its state, the result, and the lines the job logged. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "count-open-tickets", input: { customer: "Ada" } } } ``` ```ts count-open.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", customer: "Ada", status: "open" }, { id: "T-2", customer: "Grace", status: "closed" }, { id: "T-3", customer: "Ada", status: "open" }, ]; @Job({ name: "count-open-tickets", description: "Count a customer's open tickets", inputSchema: { customer: z.string().min(1) }, outputSchema: { customer: z.string(), open: z.number() }, }) export class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { this.log(`Counting open tickets for ${customer}`); const open = tickets.filter((t) => t.customer === customer && t.status === "open").length; return { customer, open }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CountOpenTickets } from "./count-open.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] }) export class HelpDeskApp {} ``` ```ts count-open.test.ts import { test, expect } from "@frontmcp/testing"; test("the job tools are added to the server", async ({ mcp }) => { const names = (await mcp.tools.list()).map((t) => t.name); expect(names).toEqual(["cancel_job", "execute_job", "execute_workflow", "get_job_status", "get_workflow_status"]); }); test("execute_job returns the result and the logs", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Ada" } }); expect(result).toBeSuccessful(); expect(result.json()).toEqual({ runId: expect.any(String), uri: expect.stringMatching(/^job:\/\/runs\//), state: "completed", result: { customer: "Ada", open: 2 }, logs: [expect.stringMatching(/^\[\d{4}-\d\d-\d\dT[\d:.]+Z\] Counting open tickets for Ada$/)], }); }); test("list_jobs isn't listed, but can be called", async ({ mcp }) => { const result = await mcp.tools.call("list_jobs", {}); expect(result.json()).toMatchObject({ count: 1, jobs: [{ name: "count-open-tickets", description: "Count a customer's open tickets" }] }); }); ``` Open the **Tests** tab. The app declares no tools, yet the server has five: FrontMCP added them for the job. ### Failing A job fails when `execute()` throws, and `execute_job` returns an `isError` result. What the client reads depends on how the job failed: ### Failures ### Example: Bad input Input that doesn't match `inputSchema` fails with `INVALID_INPUT` and `Invalid input for job "…"`, followed by the Zod issues. The message reaches production clients too, and the attempt is not retried. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "count-open-tickets", input: { customer: "" } } } ``` ```ts help-desk.app.ts import { App, Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "count-open-tickets", inputSchema: { customer: z.string().min(1) }, outputSchema: { customer: z.string(), open: z.number() }, }) export class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { return { customer, open: 2 }; } } @App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] }) export class HelpDeskApp {} ``` ```ts bad-input.test.ts import { test, expect } from "@frontmcp/testing"; test("the Zod issues are in the text", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "" } }); expect(result).toBeError("INVALID_INPUT"); expect(result.text()).toMatch(/^Invalid input for job /); expect(result.text()).toMatch(/"path": \[\s*"customer"\s*\]/); }); ``` ### Example: A thrown error A plain `Error` fails with `TOOL_EXECUTION_ERROR`. In development the text has the message and the stack; in production, only "Internal FrontMCP error" and an error ID. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "count-open-tickets", input: { customer: "Ada" } } } ``` ```ts help-desk.app.ts import { App, Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { customer: z.string(), open: z.number() }, }) export class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }): Promise<{ customer: string; open: number }> { throw new Error("The ticket database is down"); } } @App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] }) export class HelpDeskApp {} ``` ```ts thrown.test.ts import { test, expect } from "@frontmcp/testing"; test("the message follows the tool's", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Ada" } }); expect(result).toBeError("TOOL_EXECUTION_ERROR"); expect(result.text()).toMatch(/^Tool "execute_job" execution failed: The ticket database is down\n/); }); ``` ### Example: A public error `this.fail()` with a `PublicMcpError` sends your message and code as they are, in development and in production. Use it for failures the model can act on. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "count-open-tickets", input: { customer: "Zed" } } } ``` ```ts help-desk.app.ts import { App, Job, JobContext, PublicMcpError, z } from "@frontmcp/sdk"; const customers = ["Ada", "Grace"]; @Job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { customer: z.string(), open: z.number() }, }) export class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { if (!customers.includes(customer)) { this.fail(new PublicMcpError(`There's no customer ${customer}.`, "CUSTOMER_NOT_FOUND")); } return { customer, open: 2 }; } } @App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] }) export class HelpDeskApp {} ``` ```ts public.test.ts import { test, expect } from "@frontmcp/testing"; test("the client reads the message and the code", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Zed" } }); expect(result).toBeError("CUSTOMER_NOT_FOUND"); expect(result.text()).toBe("There's no customer Zed."); }); ``` ### Retrying a job that fails With `retry`, a failed attempt is tried again after a wait. Here the mail server is busy two times out of three, so the job succeeds on its third attempt, after waiting 100 and then 200 milliseconds: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "notify-agent", input: { agent: "nour", ticket: "T-1" } } } ``` ```ts notify-agent.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; import { sendEmail } from "./mail"; @Job({ name: "notify-agent", description: "Email a support agent about a ticket", inputSchema: { agent: z.string(), ticket: z.string() }, outputSchema: { sent: z.boolean() }, retry: { maxAttempts: 3, backoffMs: 100 }, }) export class NotifyAgent extends JobContext { async execute({ agent, ticket }: { agent: string; ticket: string }) { this.log(`Attempt ${this.attempt}: emailing ${agent} about ${ticket}`); sendEmail(agent, `${ticket} needs you`); return { sent: true }; } } ``` ```ts mail.ts let calls = 0; // Stands in for a mail server that's busy two times out of three. export function sendEmail(to: string, subject: string) { calls += 1; if (calls % 3 !== 0) throw new Error("Mail server busy"); } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { NotifyAgent } from "./notify-agent.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [NotifyAgent] }) export class HelpDeskApp {} ``` ```ts retry.test.ts import { test, expect } from "@frontmcp/testing"; test("the third attempt succeeds, after two waits", async ({ mcp }) => { const started = Date.now(); const result = await mcp.tools.call("execute_job", { name: "notify-agent", input: { agent: "nour", ticket: "T-1" } }); expect(Date.now() - started).toBeGreaterThanOrEqual(300); expect(result.json()).toMatchObject({ state: "completed", result: { sent: true } }); }); test("only the successful attempt's logs are kept, and it knows it's the third", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "notify-agent", input: { agent: "nour", ticket: "T-2" } }); expect(result.json().logs).toEqual([expect.stringMatching(/\] Attempt 3: emailing nour about T-2$/)]); }); ``` If the last attempt fails too, the call fails with that attempt's error. `this.attempt` says which attempt is running. Only retry work that's safe to repeat: here, a second email is better than none, but a job that charges a card needs to know whether the first attempt went through. ### Running a job in the background With `background: true`, `execute_job` returns a `runId` at once, and the job runs after the call has returned. The caller that started it polls `get_job_status` with the `runId` until the run is `completed` or `failed`. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "export-tickets", input: { customer: "Ada" }, background: true } } ``` ```ts export-tickets.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "export-tickets", description: "Export a customer's tickets as CSV", inputSchema: { customer: z.string() }, outputSchema: { customer: z.string(), csv: z.string() }, }) export class ExportTickets extends JobContext { async execute({ customer }: { customer: string }) { this.log(`Exporting tickets for ${customer}`); await new Promise((resolve) => setTimeout(resolve, 100)); // stands in for a slow query return { customer, csv: "id,title\nT-1,Cannot log in\nT-3,Login link expired" }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { ExportTickets } from "./export-tickets.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [ExportTickets] }) export class HelpDeskApp {} ``` ```ts background.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); test("a background run returns at once", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "export-tickets", input: { customer: "Ada" }, background: true }); expect(result.json()).toEqual({ runId: expect.any(String), state: "pending", uri: expect.stringMatching(/^job:\/\/runs\//) }); }); test("an anonymous caller can't read its own run", async ({ mcp }) => { const { runId } = (await mcp.tools.call("execute_job", { name: "export-tickets", input: { customer: "Ada" }, background: true })).json(); const status = await mcp.tools.call("get_job_status", { runId }); expect(status).toBeError("INVALID_INPUT"); expect(status.text()).toBe(`Run "${runId}" not found`); }); test("a signed-in caller polls until the run completes", async () => { // createDirect() runs the server in-process, as the user you name. const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); const asNour = { authContext: { user: { sub: "nour" } } }; const started = await server.callTool("execute_job", { name: "export-tickets", input: { customer: "Ada" }, background: true }, asNour); const { runId } = started.structuredContent as { runId: string }; const first = await server.callTool("get_job_status", { runId }, asNour); await sleep(250); const last = await server.callTool("get_job_status", { runId }, asNour); const asSam = server.callTool("get_job_status", { runId }, { authContext: { user: { sub: "sam" } } }); await expect(asSam).rejects.toThrow(`Run "${runId}" not found`); await server.dispose(); expect(first.structuredContent).toMatchObject({ runId, jobName: "export-tickets", state: "running", logs: [] }); expect(last.structuredContent).toMatchObject({ state: "completed", result: { customer: "Ada" }, attempt: 1, startedAt: expect.any(Number), completedAt: expect.any(Number), }); }); ``` Without the TC39 `AsyncContext`, FrontMCP's [browser build](https://frontmcp.dev/reference/sdk/create-fetch-handler#in-a-browser) serves one request at a time and runs a background job before the next one, so there the first poll already finds the run `completed`. The Playground provides a minimal `AsyncContext`, so here the run is still `running` at first, as on Node. The Call tab shows the `pending` run. Calling `get_job_status` with its `runId` from the Call tab fails with "not found": the Playground's caller is anonymous, and [nobody can read an anonymous caller's runs](https://frontmcp.dev/reference/sdk/job#who-can-read-a-run), not even that caller. The last test signs in as `nour`, who can, and `sam`, who can't. [Running Jobs in the Background](https://frontmcp.dev/learn/running-jobs-in-the-background) walks through polling. ### Using a provider A job gets providers with `this.get()`, from its app and from the server, as the app's tools do. Both get the same instance, so a tool and a job share data: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "count-open-tickets", input: { customer: "Ada" } } } ``` ```ts count-open.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { customer: z.string(), open: z.number() }, }) export class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { return { customer, open: this.get(TicketStore).openFor(customer).length }; } } ``` ```ts close-ticket.tool.ts import { Tool, ToolContext, z } from "@frontmcp/sdk"; import { TicketStore } from "./ticket-store"; @Tool({ name: "close_ticket", description: "Close a ticket", inputSchema: { id: z.string() } }) export class CloseTicket extends ToolContext { async execute({ id }: { id: string }) { this.get(TicketStore).close(id); return { id, status: "closed" }; } } ``` ```ts ticket-store.ts import { Provider, ProviderScope } from "@frontmcp/sdk"; @Provider({ name: "TicketStore", scope: ProviderScope.GLOBAL }) export class TicketStore { private tickets = [ { id: "T-1", customer: "Ada", status: "open" }, { id: "T-2", customer: "Grace", status: "closed" }, { id: "T-3", customer: "Ada", status: "open" }, ]; openFor(customer: string) { return this.tickets.filter((t) => t.customer === customer && t.status === "open"); } close(id: string) { const ticket = this.tickets.find((t) => t.id === id); if (ticket) ticket.status = "closed"; } } ``` ```ts main.ts import { App, FrontMcp } from "@frontmcp/sdk"; import { CloseTicket } from "./close-ticket.tool"; import { CountOpenTickets } from "./count-open.job"; import { TicketStore } from "./ticket-store"; @App({ id: "help-desk", name: "Help Desk", tools: [CloseTicket], jobs: [CountOpenTickets], providers: [TicketStore], // for the app's tools and its jobs }) export class HelpDeskApp {} @FrontMcp({ info: { name: "Help Desk", version: "1.0.0" }, apps: [HelpDeskApp] }) export default class HelpDeskServer {} ``` ```ts provider.test.ts import { test, expect } from "@frontmcp/testing"; test("the job sees what the tool changed", async ({ mcp }) => { const count = async () => (await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Ada" } })).json().result.open; expect(await count()).toBe(2); await mcp.tools.call("close_ticket", { id: "T-1" }); expect(await count()).toBe(1); }); ``` A provider in `@FrontMcp({ providers })` works too, and is shared with every app. A provider on another app isn't available to the job: see [Troubleshooting](https://frontmcp.dev/reference/sdk/job#provider--is-not-available-in-a-job). (Changed in 1.9.2: before, a job only saw the server's providers.) ### Calling another service from a job `this.fetch()` works in a job as in a tool, and sends the request's tracing headers, so the other service's logs tie its request to the call that started the job. A background run keeps the caller's trace: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "sync-customer", input: { customerId: "C-1" } } } ``` ```ts sync-customer.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "sync-customer", description: "Copy a customer's plan from the CRM", inputSchema: { customerId: z.string() }, outputSchema: { customerId: z.string(), plan: z.string() }, }) export class SyncCustomer extends JobContext { async execute({ customerId }: { customerId: string }) { const response = await this.fetch(`https://crm.example/customers/${customerId}`); const { plan } = await response.json(); return { customerId, plan }; } } ``` ```ts crm.example.ts // Stands in for the CRM, which the Playground can't reach. It answers requests for // crm.example in-process, and keeps the tracing headers of each. A real server // doesn't need this file. export const received: { traceparent: string | null; requestId: string | null }[] = []; const realFetch: typeof fetch = ((globalThis as any).__realFetch ??= globalThis.fetch); globalThis.fetch = async (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input)); if (url.host !== "crm.example") return realFetch(input, init); const headers = new Headers(init?.headers); received.push({ traceparent: headers.get("traceparent"), requestId: headers.get("x-request-id") }); return Response.json({ plan: "business" }); }; ``` ```ts help-desk.app.ts import "./crm.example"; import { App } from "@frontmcp/sdk"; import { SyncCustomer } from "./sync-customer.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [SyncCustomer] }) export class HelpDeskApp {} ``` ```ts fetch.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { received } from "./crm.example"; import { HelpDeskApp } from "./help-desk.app"; const traced = { traceparent: expect.stringMatching(/^00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]$/), requestId: expect.any(String) }; test("the CRM gets the tracing headers", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "sync-customer", input: { customerId: "C-1" } }); expect(result.json().result).toEqual({ customerId: "C-1", plan: "business" }); expect(received.at(-1)).toEqual(traced); }); test("a background run sends them too", async () => { const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); const asNour = { authContext: { user: { sub: "nour" } } }; const before = received.length; await server.callTool("execute_job", { name: "sync-customer", input: { customerId: "C-1" }, background: true }, asNour); await new Promise((resolve) => setTimeout(resolve, 100)); await server.dispose(); expect(received.slice(before)).toEqual([traced]); }); ``` In the background, `this.context` is a copy of the starting call's: the same session, caller and trace, and a request id of its own, since the call it came from has already returned. (Changed in 1.9.2: before, a job had no request context, `this.context` threw, and `this.fetch()` sent no tracing headers.) ### Restricting who can run a job `permissions` limits a job to callers with a role, a scope, or anything a function can check. Anyone else gets the same error as for a job that doesn't exist, and `list_jobs` doesn't show them the job: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "export-invoices", input: { month: "2026-08" } } } ``` ```ts export-invoices.job.ts active import { Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "export-invoices", description: "Export a month's invoices", inputSchema: { month: z.string().regex(/^\d{4}-\d\d$/) }, outputSchema: { month: z.string(), invoices: z.number() }, permissions: [{ action: "execute", roles: ["billing"] }], }) export class ExportInvoices extends JobContext { async execute({ month }: { month: string }) { return { month, invoices: 42 }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { ExportInvoices } from "./export-invoices.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [ExportInvoices] }) export class HelpDeskApp {} ``` ```ts permissions.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { HelpDeskApp } from "./help-desk.app"; test("an anonymous caller is refused, as if the job didn't exist", async ({ mcp }) => { const refused = await mcp.tools.call("execute_job", { name: "export-invoices", input: { month: "2026-08" } }); expect(refused).toBeError("JOB_NOT_AUTHORIZED"); expect(refused.text()).toBe('Job or workflow "export-invoices" not found or not permitted'); const missing = await mcp.tools.call("execute_job", { name: "export-payroll" }); expect(missing.text()).toBe('Job or workflow "export-payroll" not found or not permitted'); }); test("list_jobs doesn't show it to them", async ({ mcp }) => { expect((await mcp.tools.call("list_jobs", {})).json()).toEqual({ jobs: [], count: 0 }); }); test("someone in billing can run it", async () => { const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); const result = await server.callTool( "execute_job", { name: "export-invoices", input: { month: "2026-08" } }, { authContext: { user: { sub: "li", roles: ["billing"] } } }, ); await server.dispose(); expect(result.structuredContent).toMatchObject({ state: "completed", result: { month: "2026-08", invoices: 42 } }); }); ``` ### Hooking every attempt of a job A [`JobHook`](https://frontmcp.dev/reference/sdk/job#jobhook) runs for each attempt of a job, so a plugin can audit, time or cache job runs the way it hooks tool calls. `ctx.state.attempt` tells the attempts apart, and `ctx.state.flowError` is set in the `always` stages when the attempt failed. ### Job hooks ### Example: Seeing each attempt The plugin records how each attempt ended. The mail server is busy two times out of three, so one call makes three attempts: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "notify-agent", input: { agent: "nour", ticket: "T-1" } } } ``` ```ts attempt-log.plugin.ts active import { DynamicPlugin, FlowCtxOf, JobHook, Plugin } from "@frontmcp/sdk"; export const attempts: string[] = []; @Plugin({ name: "attempt-log" }) export class AttemptLogPlugin extends DynamicPlugin { @JobHook.Did("finalize") async record(ctx: FlowCtxOf<"jobs:execute-job">) { const { job, attempt, flowError } = ctx.state; attempts.push(`${job?.name} attempt ${attempt}: ${flowError ? flowError.message : "completed"}`); } } ``` ```ts notify-agent.job.ts import { Job, JobContext, z } from "@frontmcp/sdk"; import { sendEmail } from "./mail"; @Job({ name: "notify-agent", description: "Email a support agent about a ticket", inputSchema: { agent: z.string(), ticket: z.string() }, outputSchema: { sent: z.boolean() }, retry: { maxAttempts: 3, backoffMs: 50 }, }) export class NotifyAgent extends JobContext { async execute({ agent, ticket }: { agent: string; ticket: string }) { sendEmail(agent, `${ticket} needs you`); return { sent: true }; } } ``` ```ts mail.ts let calls = 0; // Stands in for a mail server that's busy two times out of three. export function sendEmail(to: string, subject: string) { calls += 1; if (calls % 3 !== 0) throw new Error("Mail server busy"); } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { AttemptLogPlugin } from "./attempt-log.plugin"; import { NotifyAgent } from "./notify-agent.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [NotifyAgent], plugins: [AttemptLogPlugin] }) export class HelpDeskApp {} ``` ```ts attempts.test.ts import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; import { attempts } from "./attempt-log.plugin"; import { HelpDeskApp } from "./help-desk.app"; test("the hook runs once per attempt", async ({ mcp }) => { attempts.length = 0; await mcp.tools.call("execute_job", { name: "notify-agent", input: { agent: "nour", ticket: "T-2" } }); expect(attempts).toEqual([ "notify-agent attempt 1: Mail server busy", "notify-agent attempt 2: Mail server busy", "notify-agent attempt 3: completed", ]); }); test("a background run's attempts too", async () => { const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); attempts.length = 0; const asNour = { authContext: { user: { sub: "nour" } } }; await server.callTool("execute_job", { name: "notify-agent", input: { agent: "nour", ticket: "T-3" }, background: true }, asNour); await new Promise((resolve) => setTimeout(resolve, 300)); await server.dispose(); expect(attempts).toHaveLength(3); expect(attempts.at(-1)).toBe("notify-agent attempt 3: completed"); }); ``` ### Example: Answering from a cache A hook can answer for the job with `ctx.respond({ result, logs })`. This one saves each report the job builds, and answers the next request for the same day from it, without running `execute()`: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "build-daily-report", input: { day: "2026-09-26" } } } ``` ```ts report-cache.plugin.ts active import { DynamicPlugin, FlowCtxOf, JobHook, Plugin } from "@frontmcp/sdk"; const reports = new Map(); @Plugin({ name: "report-cache" }) export class ReportCachePlugin extends DynamicPlugin { @JobHook.Will("execute", { filter: (ctx) => ctx.state.job?.name === "build-daily-report" }) async answerFromCache(ctx: FlowCtxOf<"jobs:execute-job">) { const { day } = ctx.state.parsedInput as { day: string }; if (reports.has(day)) ctx.respond({ result: reports.get(day), logs: [`Report for ${day} from the cache`] }); } @JobHook.Did("validateOutput", { filter: (ctx) => ctx.state.job?.name === "build-daily-report" }) async save(ctx: FlowCtxOf<"jobs:execute-job">) { const { day } = ctx.state.parsedInput as { day: string }; reports.set(day, ctx.state.answer?.result); } } ``` ```ts build-daily-report.job.ts import { Job, JobContext, z } from "@frontmcp/sdk"; export const built: string[] = []; @Job({ name: "build-daily-report", description: "Count the tickets opened and closed on one day.", inputSchema: { day: z.string() }, outputSchema: { day: z.string(), opened: z.number(), closed: z.number() }, }) export class BuildDailyReport extends JobContext { async execute({ day }: { day: string }) { built.push(day); this.log(`Read every ticket of ${day}`); return { day, opened: 12, closed: 9 }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { BuildDailyReport } from "./build-daily-report.job"; import { ReportCachePlugin } from "./report-cache.plugin"; @App({ id: "help-desk", name: "Help Desk", jobs: [BuildDailyReport], plugins: [ReportCachePlugin] }) export class HelpDeskApp {} ``` ```ts cache.test.ts import { test, expect } from "@frontmcp/testing"; import { built } from "./build-daily-report.job"; test("the second run of a day is answered from the cache", async ({ mcp }) => { built.length = 0; const run = () => mcp.tools.call("execute_job", { name: "build-daily-report", input: { day: "2026-09-25" } }); const first = (await run()).json(); const second = (await run()).json(); expect(built).toEqual(["2026-09-25"]); expect(first.logs).toEqual([expect.stringMatching(/\] Read every ticket of 2026-09-25$/)]); expect(second).toEqual({ runId: expect.any(String), uri: expect.stringMatching(/^job:\/\/runs\//), state: "completed", result: { day: "2026-09-25", opened: 12, closed: 9 }, logs: ["Report for 2026-09-25 from the cache"], }); }); ``` The answer becomes the run's result, which `get_job_status` returns too. It is checked against `outputSchema`, as a result returned by the job is. ### Example: On the job class A `@Job` class can declare hooks for its own attempts. Stages before `createJobContext` run before the job's instance exists, so a hook on them is a `static` method, with the class as `this`. Here a static hook tidies the input before `inputSchema` checks it, and an instance hook adds a line to the run's logs: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "count-open-tickets", input: { customer: " ada " } } } ``` ```ts count-open.job.ts active import { FlowCtxOf, Job, JobContext, JobHook, z } from "@frontmcp/sdk"; const tickets = [ { id: "T-1", customer: "Ada", status: "open" }, { id: "T-3", customer: "Ada", status: "open" }, ]; @Job({ name: "count-open-tickets", inputSchema: { customer: z.enum(["Ada", "Grace"]) }, outputSchema: { customer: z.string(), open: z.number() }, }) export class CountOpenTickets extends JobContext { @JobHook.Will("validateInput") static tidyCustomer(ctx: FlowCtxOf<"jobs:execute-job">) { const { customer } = ctx.state.input as { customer: string }; const name = customer.trim(); ctx.state.set("input", { customer: name.charAt(0).toUpperCase() + name.slice(1).toLowerCase() }); } @JobHook.Did("execute") async noteAttempt() { this.log(`Counted on attempt ${this.attempt}`); } async execute({ customer }: { customer: string }) { return { customer, open: tickets.filter((t) => t.customer === customer && t.status === "open").length }; } } ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CountOpenTickets } from "./count-open.job"; @App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] }) export class HelpDeskApp {} ``` ```ts class-hooks.test.ts import { test, expect } from "@frontmcp/testing"; import { App, FrontMcpInstance, Job, JobContext, JobHook, z } from "@frontmcp/sdk"; test("the static hook tidies the input, and the instance hook logs", async ({ mcp }) => { const run = (await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: " ada " } })).json(); expect(run.result).toEqual({ customer: "Ada", open: 2 }); expect(run.logs).toEqual([expect.stringMatching(/\] Counted on attempt 1$/)]); }); test("an instance hook before `createJobContext` stops the server", async () => { @Job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { open: z.number() } }) class TidyCountJob extends JobContext { @JobHook.Will("validateInput") async tidyCustomer() {} async execute() { return { open: 2 }; } } @App({ id: "help-desk", name: "Help Desk", jobs: [TidyCountJob] }) class HelpDeskApp {} const starting = FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp] }); await expect(starting).rejects.toThrow( "Job \"TidyCountJob\" declares hooks that would never run: tidyCustomer() (will 'validateInput' of jobs:execute-job): runs before 'createJobContext' builds the instance it runs on; declare it as a static method to run it without an instance.", ); }); ``` A plugin or a provider on an app hooks that app's jobs only. To hook every job a server runs, register the plugin on `@FrontMcp`. [Hooks](https://frontmcp.dev/reference/sdk/hooks) covers `Will`, `Did`, `Finally`, `Around` and `Stage`, which work on `JobHook` as on every flow. ### Writing a job as a function For a small job that doesn't log, the function form is shorter. The handler gets the `JobContext` as its second argument, for `ctx.get()` and `ctx.auth`. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "shout", input: { text: "your ticket is solved" } } } ``` ```ts help-desk.app.ts import { App, job, z } from "@frontmcp/sdk"; export const shout = job({ name: "shout", inputSchema: { text: z.string() }, outputSchema: { text: z.string() }, })(async ({ text }) => { return { text: text.toUpperCase() }; }); @App({ id: "help-desk", name: "Help Desk", jobs: [shout] }) export class HelpDeskApp {} ``` --- ### Checking a hook's cached result A cache can return stale data whose shape no longer matches the job. Hook answers go through `outputSchema` too: a mismatch fails with `INVALID_OUTPUT`, without retrying. Initial call configuration: ```js { tool: "execute_job", arguments: { name: "cached-count" } } ``` ```ts cached-count.job.ts active import { Job, JobContext, JobHook, z } from "@frontmcp/sdk"; export let cacheReads = 0; @Job({ name: "cached-count", inputSchema: {}, outputSchema: { open: z.number() }, retry: { maxAttempts: 3, backoffMs: 1 } }) export class CachedCount extends JobContext { @JobHook.Will("execute") cached(ctx: any) { cacheReads += 1; ctx.respond({ result: { open: "twelve" }, logs: [] }); } async execute() { return { open: 12 }; } } ``` ```ts cached-count.test.ts import { test, expect } from "@frontmcp/testing"; import { cacheReads } from "./cached-count.job"; test("a mismatched cache result fails without retrying", async ({ mcp }) => { const before = cacheReads; const result = await mcp.tools.call("execute_job", { name: "cached-count" }); expect(result).toBeError("INVALID_OUTPUT"); expect(cacheReads - before).toBe(1); }); ``` ### Updating a runtime job With `jobs.allowDynamicRegistration`, `update_job` replaces only the fields supplied. The same option serves `update_workflow` for dynamic workflows. Neither changes a class declared in code. **Hidden fixture/test file (runs with the example):** ```ts app.ts hidden import { App } from "@frontmcp/sdk"; @App({ name: "Help Desk" }) export class HelpDesk {} ``` ```ts update.test.ts active import { test, expect } from "@frontmcp/testing"; import { FrontMcpInstance } from "@frontmcp/sdk"; test("update_job replaces the description and keeps its tags", async () => { const server = await FrontMcpInstance.createDirect({ info: { name: "help-desk", version: "1.0.0" }, apps: [], jobs: { enabled: true, allowDynamicRegistration: true }, }); try { await server.callTool("register_job", { name: "count-tickets", script: "return { count: 2 };", description: "Old description", tags: ["tickets"] }); const result = await server.callTool("update_job", { name: "count-tickets", description: "Count open tickets" }); expect(result.structuredContent).toEqual({ success: true, jobId: "count-tickets" }); const listed = await server.callTool("list_jobs", {}); expect((listed.structuredContent as any).jobs).toContainEqual(expect.objectContaining({ name: "count-tickets", description: "Count open tickets", tags: ["tickets"], })); } finally { await server.dispose(); } }); ``` ## Troubleshooting ### `Job "…" is declared in code and cannot be updated` `update_job` only changes jobs made with `register_job`. Edit a declared class and restart the server instead. The error code is `INVALID_INPUT`. ### `Job or workflow "…" not found or not permitted` `execute_job` found no job by that name that the caller may run. Check, in order: 1. The name is spelled as in `@Job({ name })`. If the job also sets `id`, use the `id`. 2. The class is in an app's `jobs` array, and the app is in `@FrontMcp({ apps })`. 3. The job's `permissions` let this caller run it. The error is the same on purpose, so a caller can't tell a job they may not run from one that doesn't exist. Call `list_jobs` as that caller to see what they can run. ### `Run "…" not found` `get_job_status` answers the owner or a caller passing the job's explicit `read` rule, and says "not found" to everyone else. An anonymous caller on protocol 2026-07-28, like the Playground's, can't read its own runs either, because each of its requests has a new identity. See [who can read a run](https://frontmcp.dev/reference/sdk/job#who-can-read-a-run). Also check that the `runId` is from this server since its last restart: runs use memory when no shared backend is configured. ### `Provider "…" is not available` in a job A job resolves providers from its own app and from the server, so a provider registered on another app is missing: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "count-open-tickets", input: { customer: "Ada" } } } ``` ```ts help-desk.app.ts import { App, FrontMcp, Job, JobContext, Provider, z } from "@frontmcp/sdk"; @Provider({ name: "TicketStore" }) export class TicketStore { openFor(customer: string) { return customer === "Ada" ? ["T-1", "T-3"] : []; } } @Job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { customer: z.string(), open: z.number() }, }) export class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { return { customer, open: this.get(TicketStore).openFor(customer).length }; } } @App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] }) export class HelpDeskApp {} // 🚩 TicketStore is on another app @App({ id: "tickets", name: "Tickets", providers: [TicketStore] }) export class TicketsApp {} @FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDeskApp, TicketsApp] }) export default class Server {} ``` ```ts provider.test.ts import { test, expect } from "@frontmcp/testing"; test("the job can't find the other app's provider", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Ada" } }); expect(result).toBeError("TOOL_EXECUTION_ERROR"); expect(result.text()).toContain('Provider "TicketStore" is not available: not found in local or parent registries'); }); ``` Register the provider on the job's app, or on the server with `@FrontMcp({ providers })` to share it between apps, as in [Using a provider](https://frontmcp.dev/reference/sdk/job#using-a-provider). Before 1.9.2, a job didn't see its own app's providers either, so servers written for 1.9.1 often have them on `@FrontMcp`, where they still work. ### `Invalid input for job "…"` The input didn't match the job's `inputSchema`. Each entry in the list has the field's `path` and a `message`. See [Bad input](https://frontmcp.dev/reference/sdk/job#failing). Bad input is not retried, whatever the retry policy. ### A job runs past its `timeout` `execute_job` enforces the job's `timeout`, or `jobs.defaultTimeoutMs` (300000 ms). Changed in 1.11.0: before, only workflow steps enforced a timeout. Set `timeout: 0` on a job for unlimited attempts, or `jobs.defaultTimeoutMs: 0` to make that the default for jobs that set no `timeout`. When a deadline passes, the attempt fails with `JOB_TIMEOUT` and its signal aborts: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "export-tickets", input: {} } } ``` ```ts help-desk.app.ts import { App, Job, JobContext, z } from "@frontmcp/sdk"; @Job({ name: "export-tickets", inputSchema: {}, outputSchema: { rows: z.number() }, timeout: 50 }) export class ExportTickets extends JobContext { async execute() { await new Promise((resolve) => setTimeout(resolve, 150)); return { rows: 3 }; } } @App({ id: "help-desk", name: "Help Desk", jobs: [ExportTickets] }) export class HelpDeskApp {} ``` ```ts timeout.test.ts import { test, expect } from "@frontmcp/testing"; test("the job fails at its timeout", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "export-tickets", input: {} }); expect(result).toBeError("JOB_TIMEOUT"); }); ``` Pass `this.signal` to cancellable work, or check it inside a loop. A timeout ends the attempt immediately; JavaScript that ignores the signal can keep running beside its retry. ### `Tool output validation failed (output does not match outputSchema at …)` The job returned something `outputSchema` doesn't describe, and the text names the first field that doesn't match. `execute_job` fails with `INVALID_OUTPUT`, a background run fails with `InvalidOutputError` in its `error`, and the job isn't retried, even with `retry`. Fields the schema doesn't declare are dropped instead: Initial call configuration: ```js { tool: "execute_job", arguments: { name: "count-open-tickets", input: { customer: "Ada" } } } ``` ```ts help-desk.app.ts import { App, Job, JobContext, z } from "@frontmcp/sdk"; export let attempts = 0; // Stands in for rows from a database you don't control: "open" comes back as text. const rows: Record> = { Ada: { open: "2", internalNote: "VIP" }, Grace: { open: 0, internalNote: "Prefers email" }, }; @Job({ name: "count-open-tickets", inputSchema: { customer: z.string() }, outputSchema: { open: z.number() }, retry: { maxAttempts: 3, backoffMs: 10 } }) export class CountOpenTickets extends JobContext { async execute({ customer }: { customer: string }) { attempts += 1; return rows[customer] as { open: number }; } } @App({ id: "help-desk", name: "Help Desk", jobs: [CountOpenTickets] }) export class HelpDeskApp {} ``` ```ts output.test.ts import { test, expect } from "@frontmcp/testing"; import { attempts } from "./help-desk.app"; test("a value of the wrong type fails the run, without a retry", async ({ mcp }) => { const before = attempts; const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Ada" } }); expect(result).toBeError("INVALID_OUTPUT"); expect(result.text()).toBe("Tool output validation failed (output does not match outputSchema at open)"); expect(attempts - before).toBe(1); }); test("a field the schema doesn't declare is dropped", async ({ mcp }) => { const result = await mcp.tools.call("execute_job", { name: "count-open-tickets", input: { customer: "Grace" } }); expect(result.json().result).toEqual({ open: 0 }); }); ``` TypeScript catches most mismatches when `execute()` returns a typed value. For data you don't control, build the result from the fields you mean to send, or parse it with the schema yourself, `z.object({ open: z.number() }).parse(row)`, and fail with a [`PublicMcpError`](https://frontmcp.dev/reference/sdk/job#failing) when it doesn't parse. (Changed in 1.9.2: before, FrontMCP didn't check the result, and sent it as it was.) ### `Job "…" declares hooks that would never run` The server doesn't start, with `InvalidHookFlowError`: a `@Job` class has an instance method hook on a stage before `createJobContext`, where the job's instance doesn't exist yet. The message names the method and the stage, and says to `declare it as a static method`. Make it `static`, and read what it needs from its `ctx` argument instead of `this`, as [On the job class](https://frontmcp.dev/reference/sdk/job#hooking-every-attempt-of-a-job) does. `Job "…" has hooks for unsupported flows` means a hook on the class is for another flow, like a `ToolHook`: move it to a plugin or a provider. ### TypeScript says `Unable to resolve signature of class decorator` `@Job` checks the class against its options, like [`@Tool`](https://frontmcp.dev/reference/sdk/tool#typescript-says-unable-to-resolve-signature-of-class-decorator). Error `TS1238` on the decorator line says which check failed: - `'execute() parameter error': "Parameter type does not match the input schema."`: `execute()`'s parameter type disagrees with `inputSchema`. - `'execute() return type error': "The method's return type is not assignable to the expected output schema type."`: `execute()` returns something `outputSchema` doesn't describe. - `'Job class error': "Class must extend JobContext"`: the class doesn't extend `JobContext`. A `@Job` without `outputSchema` doesn't compile either, and fails when the class is loaded with a Zod issue at the path `outputSchema`. --- # @Workflow > Chain jobs into steps that run in order or in parallel, each step's input built from the results of the steps before it. Source: https://frontmcp.dev/reference/sdk/workflow [Checked against FrontMCP 1.12.2](https://frontmcp.dev/versions#how-pages-are-checked) on November 14, 2026 `@Workflow` declares a [workflow](https://frontmcp.dev/learn/chaining-jobs-into-workflows): a set of steps, each of which runs a [job](https://frontmcp.dev/reference/sdk/job). A step starts once the steps it depends on have finished, steps that don't depend on each other run in parallel, and a step's input can be built from the results of the steps before it. A client runs a workflow by name with the built-in `execute_workflow` tool, and a workflow can also start by itself: from a signed webhook, from an event, or on a cron schedule. ```ts @Workflow(options) class MyWorkflow {} ``` --- ## Reference ### `@Workflow(options)` Apply `@Workflow` to an empty class: everything is in the options. List the class in an app's `workflows` array, and the jobs its steps run in the app's `jobs`. ```ts nightly-report.workflow.ts import { Workflow } from "@frontmcp/sdk"; @Workflow({ name: "nightly-report", description: "Collect one day's tickets, find the SLA breaches, and write a report", steps: [ { id: "collect", jobName: "collect-tickets", input: { day: "2026-09-26" } }, { id: "breaches", jobName: "find-sla-breaches", dependsOn: ["collect"], input: (steps) => ({ tickets: steps.get("collect").outputs.tickets }), }, { id: "report", jobName: "write-report", dependsOn: ["collect", "breaches"], input: (steps) => ({ tickets: steps.get("collect").outputs.tickets, breaches: steps.get("breaches").outputs.breaches }), }, ], }) export class NightlyReport {} ``` ```ts help-desk.app.ts import { App } from "@frontmcp/sdk"; import { CollectTickets, FindSlaBreaches, WriteReport } from "./jobs"; import { NightlyReport } from "./nightly-report.workflow"; @App({ id: "help-desk", name: "Help Desk", jobs: [CollectTickets, FindSlaBreaches, WriteReport], workflows: [NightlyReport], }) export class HelpDeskApp {} ``` [See more examples below](https://frontmcp.dev/reference/sdk/workflow#usage), and the whole server in the [Nightly Ticket Report](https://frontmcp.dev/examples/nightly-ticket-report) example. #### Options Required: | Option | Type | Description | | --- | --- | --- | | `name` | `string` | What clients pass to `execute_workflow`. Unique within the server. If you also set `id`, the id replaces it. | | `steps` | `WorkflowStep[]` | The steps, at least one. See [steps](https://frontmcp.dev/reference/sdk/workflow#steps). Their order in the array doesn't matter: `dependsOn` decides the order they run in. | Optional: | Option | Type | Default | Description | | --- | --- | --- | --- | | `description` | `string` | | What the workflow does. `list_workflows` shows it. | | `id` | `string` | `name` | A stable identifier. When set, it **replaces** `name`: clients and `list_workflows` use the id. | | `maxConcurrency` | `number` | `5` | How many steps may run at the same time. | | `timeout` | `number` | `600000` (10 minutes) | How long the whole workflow may run, in milliseconds. Checked each time a batch of steps finishes, so it doesn't interrupt a step that's running. | | `inputSchema` | object of Zod types | | Describes the input a client passes to `execute_workflow`. Checked before a run starts; defaults are applied and undeclared keys are dropped. | | `outputSchema` | an output schema | | Accepted, and not used by FrontMCP. | | `trigger` | `"manual" \| "webhook" \| "event" \| "schedule"` | `"manual"` | What starts a run besides `execute_workflow`, which runs every workflow: nothing else, a signed HTTP webhook, an event, or the times of a cron expression. `"schedule"` is new in 1.12.0. | | `webhook` | `{ path?, secret?, methods?, maxBodyBytes? }` | | Required secret for a webhook trigger; see [triggers](https://frontmcp.dev/reference/sdk/workflow#workflow-triggers). | | `event` | `string` | the workflow name | Event to listen for with `trigger: "event"`. Refused with another trigger. | | `schedule` | `{ cron, timezone?, input? }` | | When a `trigger: "schedule"` workflow runs; see [`schedule` options](https://frontmcp.dev/reference/sdk/workflow#schedule-options). Refused with another trigger. New in 1.12.0. | | `tags` | `string[]` | `[]` | Labels to filter `list_workflows` by. | | `labels` | `Record` | `{}` | Key-value labels to filter `list_workflows` by. | | `hideFromDiscovery` | `boolean` | `false` | Leave the workflow out of `list_workflows`. It still runs by name. | | `permissions` | `JobPermission[]` | none: anyone may run it | Who may run and list the workflow. The rules work as [for jobs](https://frontmcp.dev/reference/sdk/job#permissions). | #### Workflow triggers A `trigger: "webhook"` workflow serves `webhook.path`, default `/workflows/webhook/{name}`, for `webhook.methods` (default `["POST"]`; accepts `GET` and `POST`). It requires a unique `webhook.secret` of at least 32 characters. `webhook.maxBodyBytes` defaults to `1048576`. Send a JSON object with `X-FrontMCP-Timestamp` (Unix seconds within five minutes of the server's clock) and `X-FrontMCP-Signature: v1=.">`, signing the body's bytes as sent. A GET signs an empty body and passes `{}` as input. A valid request starts a background run and answers `202 { runId, state: "pending" }`. Bad, expired or replayed signatures answer `401`; permission denials `403`; invalid JSON or input `400`; an oversized body `413`; and a POST without `application/json` `415`. Replay tracking is in memory per server process: each workflow remembers up to 10,000 signatures, each until its five minutes are up, and while it holds that many, a new request gets `429` `{"error":"Too many requests; retry later"}`. Changed in 1.12.1: before, the oldest signature was forgotten to make room, so it could be sent again. The trigger principal has role `webhook:` for permission rules. A `trigger: "event"` workflow listens for `event` (default its name) on the scope's channel event bus. Emit with `this.scope.channelEventBus?.emit("user.signup", { userId })`. The payload is the workflow input, and its caller has role `event:`. Event workflows create the bus even without channels enabled. A refused run logs `Event "" did not start workflow "": `. Published [events](https://frontmcp.dev/reference/sdk/event) arrive on the same bus. New in 1.12.0. A server that declares an event emits each occurrence it publishes on the bus under the event's name, with `{ eventId, name, timestamp, data }` as the payload. A workflow with `event: "ticket.closed"` therefore starts for every publish of `ticket.closed`, from a tool, a [duty](https://frontmcp.dev/reference/sdk/duty#publishing-an-event-from-a-duty) or a [worker](https://frontmcp.dev/reference/sdk/worker#publishing-events-from-a-worker), with the occurrence as its input: declare those four fields in its `inputSchema`. An occurrence published with an `audience` or a `subscriptionId` starts the workflow too: it runs inside the server as `event:`, not as one of the subscribers the occurrence is for. `events: { bridge: false }` on the server turns this off. See [starting from a published event](https://frontmcp.dev/reference/sdk/workflow#starting-from-a-published-event). A `trigger: "schedule"` workflow starts one background run at each time of `schedule.cron`, with `schedule.input` as its input, among all the processes of the server. Its caller has role `schedule:`. New in 1.12.0. See [`schedule` options](https://frontmcp.dev/reference/sdk/workflow#schedule-options). Changed in 1.11.3: before, `trigger` and `webhook` registered nothing. Webhook options now require a valid secret and a route that does not collide with another route. Workflows registered at runtime support only manual triggers. `workflowTriggerOf(authInfo)` returns the run’s `WorkflowTriggerPrincipal`, or `undefined` for an ordinary caller. The principal has `kind` (`"webhook"`, `"event"` or `"schedule"`), `name`, `role` and `toAuthInfo()`. Both are exported from `@frontmcp/sdk`. In a step's job, [`this.auth`](https://frontmcp.dev/reference/sdk/auth) of a run a trigger started is anonymous, with no roles: read the trigger with `workflowTriggerOf(this.context.authInfo)`. #### `webhook` options | Option | Type | Default | Description | | --- | --- | --- | --- | | `path` | `string` | `/workflows/webhook/{name}` | Route path; cannot collide with an existing or reserved route. | | `methods` | `("GET" \| "POST")[]` | `["POST"]` | Allowed methods. | | `secret` | `string` | required | Unique secret of at least 32 characters, used to verify the request signature. | | `maxBodyBytes` | `number` | `1048576` | Largest JSON request body. | #### `schedule` options New in 1.12.0. | Option | Type | Default | Description | | --- | --- | --- | --- | | `cron` | `string` | required | A cron expression: `minute hour day-of-month month day-of-week`, or six fields with seconds first. The one [`@Duty({ cron })`](https://frontmcp.dev/reference/sdk/duty#cron-schedules) takes, read the same way. | | `timezone` | `string` | `"UTC"` | The IANA time zone `cron` is read in, such as `"Europe/Berlin"`. | | `input` | `object` | `{}` | The input of each scheduled run, checked against the workflow's `inputSchema`. | - **One run for each scheduled time**, whatever the number of server processes. Each schedule has a lease that one process holds, as a [duty](https://frontmcp.dev/reference/sdk/duty#scopes-and-leases) has. With a top-level `redis` that is a Redis server, the lease is shared by every machine on that Redis, under `frontmcp:cluster:schedule::`, with both names percent-encoded. Without one, or with Vercel KV, it is shared by the processes of one machine that run from the same project root, in the SQLite file `duties.sqlite` under `~/.frontmcp` or `FRONTMCP_HOME`, which needs `@frontmcp/storage-sqlite`. The lease lasts 60 seconds and is checked every 20: a process takes over from a holder that shut down at its next check, and from one that died within 80 seconds. - **Nothing runs at startup.** The lease store keeps the time the schedule was last taken. A process that gets the lease after a restart or a takeover starts one run if a scheduled time passed since, however many were missed, then continues on schedule. - **The run's id comes from the schedule and the scheduled time**: `schedule-