@Tool

Checked against FrontMCP 1.15.2 on

Use @Tool to give an assistant an action it can take, such as opening a support ticket. The client lists the tool’s name, description, and accepted arguments. When the assistant asks to use it, FrontMCP validates the arguments and calls your execute() method. The client gets the result or an error explaining why the call failed.

For a walkthrough of registration and your first call, see Your First Tool.

@Tool(options)
class MyTool extends ToolContext {
  async execute(input) { /* ... */ }
}

Reference

@Tool(options)

Extend ToolContext, decorate the class, and register it in an app’s tools array. Here get_weather requires a city. A caller can omit units because the schema supplies "celsius" before execute() runs.

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 };
  }
}

For a runnable example with both required and optional arguments, see Validating input.

Options

Required options

OptionTypeDescription
namestringThe name callers use, such as create_ticket. Choose a distinct verb and noun. If two apps register the same name, FrontMCP lists both with their app IDs. See name conflicts.
inputSchemaobject of Zod typesDeclare one Zod field per argument, such as { city: z.string() }. Clients see these fields as JSON Schema in tools/list.

Optional settings

OptionTypeDescription
aliasesstring[]Optional; defaults to none. Old names that remain callable but never listed. Aliases win over dotted owner.name lookup. Conflicts stop startup with ToolAliasConflictError.
enabledEnabledOptionOptional; 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.
descriptionstringExplain when the model should choose this tool and what it will get back. For example, “Search support tickets by words in their title” distinguishes a search from a lookup by ID.
titlestringA display name for people, like "Search tickets". Sent in tools/list only when set.
outputSchemaZod schema, or one of "string", "number", "boolean", "date", "image", "audio", "resource", "resource_link"Declare the shape execute() returns. FrontMCP checks the result and reports INVALID_OUTPUT if it fails validation. The schema also determines what clients can discover before a call. See which schemas are listed and declaring the result shape.
outputOutputPolicyHow results are validated and their schema is advertised. Overrides app and server defaults. See Output policy.
inputInputPolicyWhat a call does with arguments inputSchema doesn't declare: { undeclaredKeys: "strip" | "warn" | "fail" }. Overrides app and server defaults. See Input policy.
_metaRecord<string, unknown>Sent as the tool's _meta in tools/list. With ui: { visibility: ["app"] } in it, the tool is for its MCP Apps page only: see Tools for the app page only.
annotationsToolAnnotationsHints for clients: title, readOnlyHint, destructiveHint, idempotentHint, openWorldHint. See describing side effects.
examplesToolExample[]Sample calls: description, input and optionally output.
tagsstring[]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.
rateLimitRateLimitConfigPer-tool rate limit: maxRequests, windowMs, partitionBy. See Guard options.
concurrencyConcurrencyConfigCap on simultaneous executions: maxConcurrent, optional queue. See Guard options.
timeoutTimeoutConfigExecution timeout: executeMs. See Guard options.
authProvidersToolAuthProviderRef[]Name the credentials the tool needs, such as { name: "github", scopes: ["repo"] }. Entries are required by default. FrontMCP checks server credential providers first, then the caller’s vault, before execute(). If neither system is configured, this check is skipped. See credential providers and the caller’s vault.
availableWhenEntryAvailabilityOnly 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 only. surface holds for agents and jobs too. See Environment awareness.
execution{ taskSupport }Whether the tool can run as a background task: "required", "optional" or "forbidden". See Background tasks.
uiToolUIConfigAttach a widget for clients that can render MCP Apps. The widget’s data follows the same output policy as other tool results. See fields outside the schema.

Plugins add options of their own, which only take effect where the plugin is installed: cache (Cache), approval (Approval), featureFlag (Feature flags) and codecall (CodeCall). A server whose tool sets approval or featureFlag, with no plugin that enforces it, doesn't start: see Unenforced metadata.

Input policy

Use input.undeclaredKeys to decide what happens when a caller misspells an argument or sends one the tool never declared. FrontMCP uses the tool’s setting first, then the app’s, then the server’s. The default is "warn".

undeclaredKeysResult
"strip"Discard extra arguments silently.
"warn"Discard the extra arguments and continue. The final text block names the ignored keys and suggests a close match when available. The server logs each unknown key once per tool. A valid call can succeed with this warning.
"fail"Reject the call with INVALID_INPUT before execute() runs. The error names the unknown arguments and can suggest the intended key.

If a caller sends timeoutMs to a tool that expects timeoutSec, the tool cannot use that timeout. With "warn", the caller sees what went wrong and can retry with seconds. Use "fail" when running with the default would be a mistake.

  • Nested keys count, as paths like 'filter.owner', except below a field whose schema has a transform or a .catch(), where the parsed value can differ in shape from what was sent.
  • Spelling suggestions look for a close match among keys declared in the same object, without regard to case. For example, filter.stauts can get filter.status when that key is declared.
  • A message names at most 20 keys and counts the rest, and cuts a key longer than 64 characters.
  • The line is the answer's last text block, after the tool's own content, on a cache hit too. structuredContent doesn't change. An in-process call through this.callTool() runs the same check and gets the same line.
  • Tools whose input is a JSON Schema, from a remote app or the OpenAPI adapter, keep every argument, so the policy doesn't apply to them.

The SDK exports the types InputPolicy and InputUndeclaredKeysPolicy. See Telling the model about arguments it got wrong.

Output policy

Use output to choose what clients see about a result before a call and how FrontMCP checks the value afterward. Set a server default, override it for an app, or override it for a single tool. This order applies to schemaMode, schemaDescriptionFormat, undeclaredKeys, and allowNonFinite.

Tools supplied by an app’s plugins and adapters also inherit its settings for schema display and extra result fields.

OptionTypeDefaultDescription
budgetfalse | { maxBytes: number; lists?: "keep-newest" | "keep-oldest" }offLimit each copy of answer data; tool overrides app, then server. maxBytes is a whole number of at least 1024. See fitting an answer.
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.
allowNonFinitebooleanfalseAllow NaN and infinities to serialize as null instead of failing, with tool > app > server precedence.
undeclaredKeys"strip" | "warn" | "keep" | "fail""warn" in development; "strip" otherwiseWhat happens to keys dropped by parsing the Zod output schema. See Choosing what happens to undeclared keys.
validateStructuredContent"enforce" | "warn""enforce"What happens to a CallToolResult the tool returns itself whose structuredContent doesn't match an object outputSchema: "enforce" refuses it with INVALID_OUTPUT; "warn" sends it as returned and logs one warning per tool.
undeclaredKeysResult
"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.

The default warns when NODE_ENV=development too; set "strip" for silent stripping.

A widget receives the same filtered result as the model. Under "keep", the widget, text, and structuredContent all retain extra fields. Under "fail", the call fails. The policy also covers a tool that builds its own whole result.

A Zod schema can determine the outcome itself. A strict object rejects extra keys. A loose object keeps them. A transform, preprocess, pipe, codec, or .catch() supplies the parsed result directly. Tools using raw JSON Schema skip Zod parsing.

Clients can discover an object result or a union in which every possible result is an object. A listed union has top-level type: "object" and retains its anyOf or oneOf alternatives. Nested unions and $ref members registered with .meta({ id }) work too. z.union() and z.discriminatedUnion() need no cast. When elicitation adds a fallback wrapper, $defs stays at the root so references still resolve.

An array, nullable object, mixed union, or schema without a JSON Schema representation can still describe a tool’s output. FrontMCP omits it from the listing and logs the reason once at startup. It also omits recursive union references. Choose schemaMode: "none" to suppress the listing and warning.

Primitive Zod schemas, media, and multi-content arrays are intentionally unlisted and silent. The literal shortcuts "string", "number", "boolean", and "date" advertise a wrapper object.

Output parsing helpers

Call ToolEntry.getOutputJsonSchema() for the cached schema a client can read, or null if there is none. getUnlistedOutputSchemaReason() explains an unexpected omission. It returns undefined for a listed schema or an intentional omission. getRawOutputSchema() includes the elicitation fallback wrapper when present.

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 cache path. They also take validateStructuredContent and onInvalidStructuredContent?: () => void, called when a mismatched CallToolResult is sent under "warn". A tool given no validateStructuredContent uses its own policy (tool, app, server), so a plugin that parses a tool's output agrees with tools/call. The SDK exports the StructuredContentValidation type.

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) returns dropped key paths; hasTransform(schema) from @frontmcp/lazy-zod detects schemas where comparing those paths is inappropriate.

execute(input)

FrontMCP calls execute(input) after validation. The method receives the parsed values, including any defaults supplied by the schema. See Context classes for the members available on this.

  • input: the validated arguments. Its TypeScript type must match inputSchema.
  • Result. Return an object for structured data. With the default client profile, clients also receive that data as text. A plain number or string with no declared output schema is wrapped in { "value": ... }. A literal "string", "number", or "boolean" output schema puts the value itself in the text block. To control the content blocks yourself, return a whole CallToolResult.

Use this.get() for a provider, this.fetch() for an HTTP request, this.notify() or this.progress() for updates, this.elicit() for a question, and this.fail() for an error. For a call from a CodeCall script, use this.idempotencyKey to identify that call and this.reportRecordsChanged(n) to count writes against its budget. See CodeCall context members.

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).
  • Arguments that aren't in inputSchema are dropped before execute() runs. The answer then ends with a line that names them, unless input.undeclaredKeys says otherwise: see Input policy.
  • If execute() throws a plain Error, development clients get the message in the result text and the stack in result metadata. In production the result gives a generic "Internal FrontMCP error" with an error ID. Use PublicMcpError for messages the model should read.
  • The class can declare hooks that run for this tool's calls only: instance methods from Did("createToolCallContext") on, and static methods on any stage, like parseInput. An instance method on an earlier stage stops the server from starting.

fileSignal(path, key, options?)

On Node, use fileSignal() to control a tool’s availability with a boolean in a JSON file. It returns an EnabledSource for the tool’s enabled option. It watches the parent folder and also rereads the file every pollIntervalMs. If the file is missing or the key has no boolean, the source uses defaultValue. If a read catches a partial write containing invalid JSON, it keeps the last value.

Supply a nonempty path and key and a positive, finite polling interval. Invalid arguments throw InvalidFileSignalError (INVALID_FILE_SIGNAL) at declaration. See live availability.

OptionTypeDefaultDescription
defaultValuebooleanfalseUsed while the file is missing or its key has no boolean.
pollIntervalMsnumber2000Positive finite milliseconds between reads, alongside file watching.
remedyErrorRemedyTurn on the "<key>" feature, then try again.Next step sent with the FEATURE_OFF refusal.
logger{ warn(message: string): void }consoleReports 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 describes.


Usage

Validating input

A ticket title must contain 5 to 120 characters. Try a shorter title and the client gets an isError result naming the invalid field before the tool creates anything. Omit priority and the call succeeds with "normal". Both rules live in inputSchema, so clients can discover them before making a call.

Open
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 };
  }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

Telling the model about arguments it got wrong

Call search_tickets with timeoutMs: 500. The tool expects seconds in timeoutSec, so the search runs with its five-second default. The answer ends with a warning suggesting timeoutSec. The tests also send filter.stauts and get a warning suggesting filter.status. The strict version, search_archive, rejects the extra argument. search_drafts accepts it and silently drops the extra argument.

Open
import { Tool, ToolContext, z } from "@frontmcp/sdk";

const inputSchema = {
  query: z.string().describe("Words to look for in ticket titles"),
  timeoutSec: z.number().int().min(1).max(30).default(5).describe("How long to search, in seconds"),
  filter: z.object({ status: z.enum(["open", "closed"]).optional() }).optional(),
};
type Input = { query: string; timeoutSec: number; filter?: { status?: "open" | "closed" } };

@Tool({ name: "search_tickets", description: "Search tickets by words in their title", inputSchema })
export class SearchTickets extends ToolContext {
  async execute({ query, timeoutSec }: Input) {
    return { query, timeoutSec, tickets: ["T-1"] };
  }
}

@Tool({ name: "search_archive", description: "Search archived tickets", inputSchema, input: { undeclaredKeys: "fail" } })
export class SearchArchive extends ToolContext {
  async execute({ query, timeoutSec }: Input) {
    return { query, timeoutSec, tickets: [] };
  }
}

@Tool({ name: "search_drafts", description: "Search draft replies", inputSchema, input: { undeclaredKeys: "strip" } })
export class SearchDrafts extends ToolContext {
  async execute({ query, timeoutSec }: Input) {
    return { query, timeoutSec, tickets: [] };
  }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

The warning appears in the last text block. Clients that read structuredContent still get the search result in its usual shape. Configure input on the app to change the default for its tools or on @FrontMcp to change it across the server. A tool’s setting takes precedence.

Returning results

Choose an object when callers need named fields. Return a plain value for a simple count or label. The examples show what each choice puts in content (for text readers) and structuredContent (for clients that use the fields directly).

Return values

Example 1 of 4

Plain value

count_open returns the number 12. With no output schema, the client receives { "value": 12 } and a text copy.

Open
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;
  }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

Link to this example

Listing a union result

When a lookup can find a ticket or report it missing, declare both outcomes. The example uses kind so clients know which fields to read. A "found" result has a title. A "missing" result carries the ID that was requested. Both appear in the tool listing.

Open
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 };
  }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

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

These tools return the same two fields, id and category, but declare only id. The app chooses "keep", so its plugin tool sends both fields. Call the other tools to see "strip" drop category, "warn" drop it and log why, and "fail" reject the result.

Open
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(); } }

const caught = { id: z.string(), priority: z.enum(["low", "high"]).catch("low") };

@Tool({ name: "caught_ticket", inputSchema: {}, outputSchema: caught, output: { undeclaredKeys: "fail" } })
class CaughtTicket extends ToolContext { async execute() { return { ...answer(), priority: "urgent" }; } }

@Plugin({ name: "ticket-export", tools: [KeepTicket] })
class TicketExport extends DynamicPlugin<object> {}

@App({
  name: "Help Desk",
  plugins: [TicketExport],
  tools: [StripTicket, WarnTicket, FailTicket, CaughtTicket],
  output: { undeclaredKeys: "keep" },
})
export class HelpDeskApp {}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

"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().

Returning a whole CallToolResult

Return a full CallToolResult when you want to send your own text alongside structured data. Here get_ticket returns a ticket record plus a sentence describing its status. FrontMCP checks structuredContent against the tool’s declared object schema. The undeclared-key policy applies to the record, and FrontMCP rebuilds a text block that repeats the record as JSON. The separate status sentence stays as written.

Ticket T-2 has a status outside the allowed values. By default the client gets INVALID_OUTPUT. Set output.validateStructuredContent to "warn" to pass the mismatched result through and log a warning once for that tool.

Open
import { Tool, ToolContext, z, type CallToolResult } from "@frontmcp/sdk";

const outputSchema = { id: z.string(), status: z.enum(["open", "closed"]) };
const rows: Record<string, { id: string; status: string; internalNotes: string }> = {
  "T-1": { id: "T-1", status: "open", internalNotes: "VIP customer" },
  "T-2": { id: "T-2", status: "on hold", internalNotes: "" }, // not a status the schema allows
};

function answer(id: string): CallToolResult {
  const row = rows[id];
  return {
    content: [{ type: "text", text: JSON.stringify(row) }, { type: "text", text: `Ticket ${id} is ${row.status}.` }],
    structuredContent: row,
  };
}

@Tool({ name: "get_ticket", description: "Get one ticket by id", inputSchema: { id: z.string() }, outputSchema })
export class GetTicket extends ToolContext {
  async execute({ id }: { id: string }): Promise<any> {
    return answer(id);
  }
}

@Tool({
  name: "get_ticket_unchecked",
  description: "Get one ticket by id",
  inputSchema: { id: z.string() },
  outputSchema,
  output: { validateStructuredContent: "warn" },
})
export class GetTicketUnchecked extends ToolContext {
  async execute({ id }: { id: string }): Promise<any> {
    return answer(id);
  }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

A successful result from a tool with a declared object schema must include structuredContent. If it is missing, validation reports Tool output validation failed (missing structuredContent). Use "warn" on the tool, app, or server to send the response while you correct a mismatch.

Error results (isError: true) and FrontMCP’s elicitation fallback pass through. So do complete results from tools with a non-object output schema, such as a list or "string", and from remote apps or OpenAPI adapters using raw JSON Schema. See the elicitation fallback, remote apps, and the OpenAPI adapter.

Returning an error the model can read

Ask for T-404 and the tool replies “There’s no ticket T-404.” Use this.fail() with a PublicMcpError when knowing the cause will help the model correct its next call. The client receives your message in an isError result in development and production.

Open
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" };
  }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

Describing side effects with annotations

Mark a deletion with destructiveHint: true so the client can decide whether to ask the user before proceeding. These annotations describe the tool’s behavior. The client chooses how to use them, and the tool remains responsible for its own checks.

AnnotationMeaning when true
readOnlyHintThe tool doesn't change anything.
destructiveHintThe tool may delete or overwrite things. Only meaningful when it isn't read-only.
idempotentHintCalling it again with the same arguments has no further effect.
openWorldHintThe tool reaches outside systems, like the web, rather than a closed set of data.
Open
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 };
  }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

Using a provider

Register Directory in the app’s providers array and retrieve it inside the tool with this.get(Directory). Here whoami asks the directory who is on duty and returns the EMEA support team and its lead, Nour.

Open
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();
  }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

Writing a tool as a function

Use tool() to declare a small operation as a function. It takes the same options as the decorator. Here the handler only needs its text argument, so it can turn "hello" into "HELLO" without a class.

Open
import { tool, z } from "@frontmcp/sdk";

export const shout = tool({
  name: "shout",
  description: "Uppercase some text",
  inputSchema: { text: z.string() },
})(async ({ text }) => text.toUpperCase());

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

Keeping an old tool name callable

If you rename find_ticket to get_ticket, add find_ticket to aliases. New clients discover only get_ticket. An older client can still call find_ticket with the same arguments, authorization, and availability checks.

Open
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 }; }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

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.

Open
import { Tool, ToolContext } from "@frontmcp/sdk";

@Tool({ name: "export_tickets", inputSchema: {}, enabled: false })
export class ExportTickets extends ToolContext {
  async execute() { return { rows: 12 }; }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

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. The source’s optional remedy goes with the FEATURE_OFF refusal. fileSignal() is a source backed by a JSON file on Node.

When availability changes, FrontMCP sends connected clients one notifications/tools/list_changed per burst. Each tools/list response includes _meta["frontmcp/surface"], a hash of the listed names.

Set EnabledSource.onError: "on" to keep an entry available when the source’s get() fails. The default is "off". A server-wide enabled resolver can also switch an entry off. Both switches must allow the entry for it to be listed and callable.

A session client that calls a tool removed since its last listing gets STALE_TOOL_LIST once and another list-change notification. A client that sends the frontmcp/surface value from tools/list in the call’s _meta can also detect a stale list across processes, including for sessionless clients. FrontMCP’s clients don’t send this metadata automatically. If it retries while the tool is off, it gets FEATURE_OFF. A sessionless MCP 2026-07-28 client that omits the hash gets FEATURE_OFF for a disabled tool. See in-memory clients.

Open
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] };

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

Fitting an answer to a budget

A ticket history can grow long enough to overwhelm a client. Set output.budget.maxBytes to a whole number of at least 1024. Here the tool returns 100 events and the budget keeps the most recent ones. FrontMCP can omit entire items or shorten the end of a string. It describes the omissions in a text note and _meta["frontmcp/budget"]. The text and structured copies each get their own byte allowance.

The default is no limit. A tool overrides its app, which overrides the server. Use false to turn off an inherited budget. "keep-newest" keeps the last list items, and "keep-oldest" keeps the first.

When a client receives an advertised object schema (schemaMode: "definition" or "both"), FrontMCP keeps the full answer if shortening it would violate that schema. It warns once per tool. A text-only client profile can receive the shortened answer. Budgeting applies to client requests. In-process calls such as this.callTool() receive the full result. See client profiles and calling another tool.

Open
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)}`) }; }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

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.

Open
import { Tool, ToolContext } from "@frontmcp/sdk";

@Tool({ name: "bad_count", inputSchema: {}, outputSchema: "number" })
export class BadCount extends ToolContext {
  async execute(): Promise<any> { 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 }; }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.


Troubleshooting

Tool alias conflict

The startup error names the conflicting alias. Give an old name to just one tool and choose an alias distinct from every tool’s current name. The error class is ToolAliasConflictError and the code is TOOL_ALIAS_CONFLICT.

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.

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. A call that renders a UI follows the same policy; transform schemas keep their parsing rules; see 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.
  5. The tool isn't for the app page only, with _meta.ui.visibility that leaves out "model": only a client that renders MCP Apps pages is listed it.

TypeScript says Unable to resolve signature of class decorator

Read past TS1238 on the decorator line. The next part of the message identifies which contract failed.

  • '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. TypeScript doesn't check its structuredContent; the server does, against an object outputSchema: see Returning a whole CallToolResult.
  • 'Tool class error': "Class must extend ToolContext": the class doesn't extend ToolContext.

Use the type shown in expected_input_type or expected_output_type to correct the method signature. In particular, a field with a schema default already has a value when execute() receives it.

// 🚩 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

Use the error ID from the client to find the original message and stack in the server log. Production masks ordinary errors thrown from execute(). When the message is safe for the model and would help it recover, end the call with this.fail(new PublicMcpError("...")).

Calls fail with INVALID_OUTPUT

Check the returned value against outputSchema. In development, the error identifies the first mismatched field. Production returns “Output validation failed. Please contact support.” With the default allowNonFinite: false, NaN and Infinity also fail, even without a schema, because JSON cannot represent them.

Open
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<string, number> = { open: 12, pending: 3 }; // no "closed" today
    return { open: counts.open, closed: counts.closed };
  }
}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

Fix the result, or change outputSchema if the result is right. Here, counts.closed ?? 0 would do.

A tool that returns a whole CallToolResult fails the same way when its structuredContent doesn't match an object outputSchema, or when it has none: Tool output validation failed (missing structuredContent). Add structuredContent that matches, or set output: { validateStructuredContent: "warn" } to send it while you fix it: see Returning a whole CallToolResult.

Tool "…" returned a CallToolResult whose structuredContent is missing or does not match its outputSchema

The server's log, once per tool, under output.validateStructuredContent: "warn": the tool's CallToolResult was sent as it was returned, though "enforce", the default, would have refused it with INVALID_OUTPUT. Fix the tool's structuredContent, then remove "warn".

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 Unknown arguments: '…'

The caller sent a field missing from inputSchema, and the effective input.undeclaredKeys policy is "fail". FrontMCP returns INVALID_INPUT before execute() runs. For Unknown arguments: 'timeoutMs' (did you mean 'timeoutSec'?), send timeoutSec with a value in seconds. If the tool really accepts the original argument, declare it in the schema. See Input policy.

An answer ends with These arguments are not declared and were ignored: …

The call ran with the declared arguments. The default "warn" policy appends that message when it drops an extra argument. The server also logs each ignored key once per tool. Correct the spelling or add the argument to inputSchema if the tool should use it. Choose "strip" to restore silent dropping. See the example with a misspelled timeout.

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.

Report a docs issue · Report a security concern privately