FrontMcpInstance

Checked against FrontMCP 1.12.2 on

FrontMcpInstance builds a server from the configuration you give @FrontMcp and runs it. You rarely call it: importing a class decorated with @FrontMcp calls FrontMcpInstance.bootstrap(), which builds the server and starts an HTTP server. Its other static methods run the same configuration in other ways: over stdio, on a Unix socket, as a handler for a serverless platform or a Worker, or in your own process.

await FrontMcpInstance.bootstrap(config)

Reference

FrontMcpInstance.bootstrap(config)

Call bootstrap() to start the HTTP server yourself, for example after connecting to a database. Set serve: false on @FrontMcp, so importing the class doesn't start a second server, and pass the same configuration:

main.ts
import "reflect-metadata";
import { FrontMcp, FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "./config";
import { connectToDatabase } from "./db";

@FrontMcp({ ...config, serve: false })
export default class HelpDeskServer {}

await connectToDatabase();
await FrontMcpInstance.bootstrap(config);

See more examples below.

Starting a server needs a real port and a Node process, so the Playground can't run bootstrap(), createHandler(), runStdio() or runUnixSocket(). What this page says about them was checked by running them in Node.

Parameters

ParameterTypeDescription
configFrontMcpConfigInputThe object you'd pass to @FrontMcp: info, apps and the rest. Not the decorated class: a class fails with a ZodError, Invalid input: expected object, received undefined.

Returns

A promise that resolves once the server is listening, and logs MCP HTTP (Express) on 127.0.0.1:3000. It rejects when the configuration is invalid or the server can't listen, for example listen EADDRINUSE: address already in use 127.0.0.1:3000 when the port is taken.

bootstrap() returns nothing to stop the server with. The process ends it.

What @FrontMcp does on import

When the decorated class is defined, @FrontMcp checks the configuration, records it on the class, and then, depending on the environment:

EnvironmentWhat happens
FRONTMCP_SCHEMA_EXTRACT setNothing more. The configuration is only recorded.
FRONTMCP_STDIO setrunStdio(config): serve one client over stdin and stdout. Nothing, with serve: false.
FRONTMCP_SERVERLESS setcreateHandler(config), or createFetchHandler(config) if FRONTMCP_WORKER is set too. The handler is kept for getServerlessHandler().
None of thosebootstrap(config), unless the configuration has serve: false.

A flag counts as set when its value is 1 or true; yes or on don't count. frontmcp build relies on these: its Vercel and Lambda entry files set FRONTMCP_SERVERLESS=1 before importing your server and export the handler from getServerlessHandlerAsync(), and its Cloudflare entry sets FRONTMCP_WORKER=1 as well.

If starting fails, for example because the port is taken, nothing catches the error: Node reports it and the process exits with code 1.

FRONTMCP_SCHEMA_EXTRACT is for tools that need your configuration without running your server. frontmcp build uses it, and so does this site's Playground, which is why importing an example's @FrontMcp class here never opens a port. Read the recorded configuration with getDecoratorConfig():

import { getDecoratorConfig } from "@frontmcp/sdk";
import HelpDeskServer from "./main";

const config = getDecoratorConfig(HelpDeskServer); // the parsed configuration, or undefined

Static methods

MethodReturnsUse it to
bootstrap(config)Promise<void>Start the HTTP server. See above.
createFetchHandler(config)Promise<(request, ctx?, env?) => Promise<Response>>Serve MCP from a runtime that hands you a web Request: Cloudflare Workers, Deno, Bun, a framework's route. See createFetchHandler().
createHandler(config)Promise<unknown>, an Express appServe MCP from a platform that calls a Node (req, res) handler, like Vercel or AWS Lambda. See below.
createDirect(config, { app }?)Promise<DirectMcpServer>Call tools, resources and prompts from your own code, with no transport. app picks an app's own endpoint, and a workerEnv in config sets the bindings its calls read (since 1.9.4). See create() and createDirect().
runStdio(configOrClass)Promise<void>Serve one local client over stdin and stdout. See below.
runShared(configOrClass, options)Promise<void>Let several stdio sessions share one local server. See below.
runUnixSocket(options)Promise<{ close }>Serve over a Unix socket instead of a TCP port. See below.
createForGraph(config)Promise<FrontMcpInstance>Build the server without serving it, to inspect it. See below.
createForCli(config)Promise<FrontMcpInstance>The same, for the frontmcp CLI's own commands: it skips widget compilation and the event and elicitation stores to start faster.

To connect an MCP client in memory instead, use connect(). It isn't a method of FrontMcpInstance.

Every method except runStdio() and runShared() needs the configuration object. connect(), runStdio() and runShared() also accept the decorated class.

FrontMcpInstance.createHandler(config)

Builds the server without listening, and returns the Express app that would have listened, a Node (req, res) handler. Export it from the entry file of a platform that calls one:

api/mcp.ts
import { FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "../src/config";

export default await FrontMcpInstance.createHandler(config);

It serves the same paths as bootstrap(), and works with http.createServer(handler) too. With serve: false in the configuration there's no Express app to return, and the promise resolves to undefined.

FrontMcpInstance.runStdio(configOrClass)

Serves one client over stdin and stdout, for clients that start your server as a subprocess, like Claude Desktop. It opens no port.

stdio.ts
import { FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "./config";

FrontMcpInstance.runStdio(config);
  • stdout carries the protocol, so from the moment you call it, runStdio() sends console.log, console.info and console.debug to stderr. A console.log before the call still writes to stdout and breaks the client.
  • The promise resolves once the client is connected, not when it disconnects.
  • On SIGINT or SIGTERM it shuts down and disposes every scope, awaits their onDispose() callbacks, then closes the MCP server. It exits 0 on success or 1 on failure, within the 5-second stdio deadline.
  • Changed in 1.11.0: before, stdio did not shut down when stdin ended or its parent disappeared. When stdin ends, it now drains replies for up to 2 seconds, runs graceful shutdown and exits 0. It also watches for its parent disappearing, within about a second. lifecycle.exitWhenOrphaned: false keeps the old behavior. HTTP and Unix-socket servers opt in with true.
  • Callers over stdio are anonymous: this.auth.isAnonymous is true and this.auth.user.sub is "".

One connection serves all five MCP revisions: initialize opens an older session, while a request naming 2026-07-28 is served statelessly, without HTTP header checks. Until initialize, calls that name no revision follow transport.defaultProtocolVersion ("legacy" by default); afterwards they stay in the session. Callers stay anonymous, but the connection owns the tasks it starts.

A server with channels is the exception. Over stdio it answers every 2026-07-28 request with -32022, so its client opens a session with initialize, and it sends channel events to that session though the client declared no channel capability. That is what a Claude Code session needs: see Channels in Claude Code. Changed in 1.12.0: before, such a server served 2026-07-28 over stdio, and sent channel events only to a session that declared the capability.

Changed in 1.10.16: before, stdio signal shutdown skipped scope disposal and onDispose() callbacks. It now awaits them within the 5-second signal deadline. If stdio startup fails after scope initialization, releasing the instance waits up to 5 seconds; initialization failures use the 10-second cleanup deadline described below. A startup cleanup deadline bounds the wait, not the unfinished cleanup or the process's lifetime.

Changed in 1.10.5: before, server/discover returned -32601 over stdio and a 2026-07-28 call received an older-revision result. It now returns discovery and resultType results, including input_required, and supports request-scoped notifications and subscriptions/listen. notifications/cancelled aborts a matching inline call's this.signal while its request is in flight, or ends its listen stream.

It accepts the decorated class as well as the configuration. The class must be imported with FRONTMCP_STDIO=1 already set, or importing it starts an HTTP server first.

FrontMcpInstance.runShared(configOrClass, options)

Several MCP clients can start the same command and attach their stdio sessions to one server process: the shared local server. New in 1.11.0. The first session finds no server and starts one, detached; every later session of the same key attaches to it. It runs over an owner-only Unix socket, or authenticated loopback HTTP on Windows. Each session verifies the server's identity before sending it credentials or MCP messages.

shared.ts
import { FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "./config";

await FrontMcpInstance.runShared(config, { key: "help-desk" });

Starting the server takes a start lock in a SQLite file, so install @frontmcp/storage-sqlite next to @frontmcp/sdk. Without it the first session can't start the server, and runShared() rejects with the sqlite type needs @frontmcp/storage-sqlite.

OptionTypeDefaultDescription
keystringrequired1–64 lowercase letters, digits, ., _ or -; begins and ends with a letter or digit. Windows device names are refused.
transport"unix" | "http""unix"; "http" on WindowsUnix socket or loopback HTTP. Unix transport is refused on Windows.
attachBudgetMsnumber15000Whole milliseconds, 1–600000, to reach a shared server before falling back to a server in this process.
replaceOlderbooleantrueDrain and replace a server whose version is older than this session's info.version.
idleTimeoutMsnumber | false600000The server exits after this many milliseconds with no request and no attached session; 1–604800000, or false to stay running. Changed in 1.12.0: before, attached sessions didn't count.
checkoutstring | falseentry file's folderExisting folder to watch. Exit when it is removed; false turns that watch off. Relative paths resolve from the working folder.

A session attaches only to the same info.name. An older shared server is replaced when versions can be ordered; another name, an unordered version, replaceOlder: false or an attach failure makes the session run its own server instead. A lost upstream reconnects, replays initialize and sends list-change notifications. The key's files live under ~/.frontmcp/shared/ (or FRONTMCP_HOME); keep that directory writable only by its owner.

Each session is a bridge: it reads its client's messages on stdin and sends them to the server in an HTTP session of its own:

  • The server stays up while a session is attached. A session holds its notification stream open, and that counts as activity. So the server exits idleTimeoutMs after the last session left, not idleTimeoutMs after the last request. Changed in 1.12.0: before, a session that stayed quiet longer than idleTimeoutMs found its server gone. Background work is not activity: the framework's source says the server exits idle while a @Worker or a duty runs, once no session is attached, so pass idleTimeoutMs: false for a server that must keep one running.
  • What the server sends on its own reaches the client. After initialize, the session opens its notification stream on the server and writes each message on it to stdout: notifications/tools/list_changed, log messages, resource updates, channel events. A stream that drops is opened again, and what the server sent in between is lost: see Through the stdio bridge. Changed in 1.12.0: before, a shared session's client got only the answers to its own requests.
  • Channels reach every attached session. For a server with channels, the session answers its client's MCP 2026-07-28 requests with -32022, so that a client like Claude Code falls back to initialize, and declares experimental["claude/channel"] on the initialize it forwards. Each event goes to every session of the server. See Through the stdio bridge. For a server without channels, a 2026-07-28 request still gets -32099 dev_server_unreachable: the stdio bridge doesn't speak that revision. Changed in 1.12.0: before, a server with channels got that answer too, and no channel event reached a shared session.
  • A quiet session follows a server that took its key over. When another server replaces a session's own, like a newer version started by another session, the session moves to it by itself, about 8 seconds after its stream was cut: it replays initialize, sends its client notifications/tools/list_changed, and opens a new stream, so it gets the new server's events. Changed in 1.12.0: before, it moved only at its client's next request. A server that was stopped, or whose checkout was removed, leaves none to follow: the session starts no server by itself, moves at its next request, and gets no notification until then. What the old server kept for the session, like its subscriptions, isn't carried over.
  • A session that runs the server in its own process gets no notification stream. It says so once on stderr, [frontmcp shared] warn running the shared server "help-desk" in this process: <reason>. Its client gets the answers to its requests, and no list_changed, log message or channel event that the server sends on its own.

On 1.12.0-rc.1 (macOS, over the Unix socket and over loopback HTTP), with idleTimeoutMs: 4000: two sessions of one key answered from one server process, and both got a channel event one of them caused. After nine quiet seconds under both sessions the server was still running, and it exited 4.8 seconds after the last session closed. A session of version 1.0.0 that sent nothing got list_changed 8.2 seconds after a session of version 1.1.0 started, then the newer server's channel event, and answered its next call from the newer server. A session of version 2.0.0 with replaceOlder: false ran the server in its own process, and got no event. A resource update reached a session that had subscribed to the resource. That a session reads its key's record every second while it waits to move, and the worker rule above, are from the framework's source.

With channels, runShared() relays server-initiated notifications to its stdio sessions and refuses MCP 2026-07-28 with -32022. Attached sessions keep the local server alive; it exits idleTimeoutMs after the last session leaves. A session follows a replacement shared server without needing to send another request. See channel delivery.

createHttpUpstream(options) from @frontmcp/utils supports custom stdio bridges:

OptionTypeDefaultDescription
claudeCodeChannelsbooleanfalseAdd the channel capability to forwarded initialize and decline 2026-07-28 for a server advertising channels.
onNotificationStreamLost() => voidnoneCalled once when the session notification stream is given up.

Its leaveSession(): void closes the notification stream and forgets a vanished server's session without sending it a request. endSession(): Promise<void> sends DELETE to end a live session. These helpers need a host connection; the Playground uses an in-memory client.

FrontMcpInstance.runUnixSocket(options)

Serves over a Unix socket file instead of a TCP port, so only processes on the same machine that can open the file can connect:

const handle = await FrontMcpInstance.runUnixSocket({ ...config, socketPath: "/tmp/help-desk.sock" });

options is the configuration plus socketPath and an optional sqlite. bootstrap() does the same when the FRONTMCP_DAEMON_SOCKET environment variable names a socket path. On SIGINT or SIGTERM it shuts down like bootstrap(): it deletes the socket file, so new clients can't connect, lets requests in flight finish for up to 5 seconds, and exits with code 0.

The socket uses 0600 on POSIX. Startup refuses unsafe directories and occupied or conflicting paths; see socket safety.

handle.close() runs the same shutdown without exiting: it resolves once requests in flight have finished and the socket file is gone. (Before 1.9.3, SIGTERM exited at once and close() only deleted the socket file.)

getServerlessHandler() and getServerlessHandlerAsync()

With FRONTMCP_SERVERLESS=1, @FrontMcp builds a handler instead of listening. Import the decorated class, then get the handler:

import { getServerlessHandlerAsync } from "@frontmcp/sdk";
import "./main"; // defines the @FrontMcp class

const handler = await getServerlessHandlerAsync();

getServerlessHandlerAsync() waits until the handler is ready. getServerlessHandler() returns it at once, or null while it's still being built. Both throw what building threw. Without FRONTMCP_SERVERLESS, getServerlessHandlerAsync() throws Serverless handler is not initialized.

Instance members

bootstrap() builds an instance and starts it. createForGraph() returns one that's built and not started.

MemberDescription
configThe parsed configuration, with defaults filled in.
getConfig()Returns config.
emitProvidersReady()Promise<void>. Runs provider onReady() for a custom host assembled with createForGraph(). Built-in entry points call it themselves.
readyA promise that resolves once the server is built: its apps, tools, resources and the rest. On failure, waits for cleanup of the partial server for at most 10 seconds before rejecting with the startup error. Cleanup can still be pending after that deadline.
shutdown()Promise<void>. Waits for initialization to finish or fail, then shuts down and disposes every scope and stops the HTTP host. Repeated calls share the same promise.
getScopes()The server's scopes: one for the whole server, or one per app with splitByApp: true.
getPrimaryScope()The scope that runStdio() serves, and createDirect() and connect() without an app: the one holding every app that isn't standalone, root. With splitByApp: true, or when every app is standalone, the first scope.
getAppScope(app)The scope an app has of its own, served at <entryPath>/<app id>: each app's with splitByApp: true, a standalone app's otherwise. createDirect() and connect() serve it when given that app. Throws ScopeConfigurationError, No endpoint serves app "…" on its own, for an app without one, naming the apps that have one. New in 1.9.3.
start()Starts the HTTP server of a built instance, then runs the callbacks registered with scope.onServerStarted().
initialize()Builds the server. The constructor calls it and keeps the promise in ready; don't call it again.

The constructor, new FrontMcpInstance(config), takes a configuration that has already been parsed. Use the static methods, which parse it for you.

Ports and the entry path

SettingWhere it comes from
Porthttp.port, else the PORT environment variable, else 3000. PORT is read when the server's options are parsed, so setting process.env.PORT in code before bootstrap() works. (Changed in 1.9: before, it was read when @frontmcp/sdk was first imported, and a later change had no effect.)
Address127.0.0.1 unless http.security.bindAddress or FRONTMCP_BIND_ADDRESS says otherwise. See http.
MCP endpointhttp.entryPath, else the FRONTMCP_HTTP_ENTRY_PATH environment variable, else the root, /.
Health checks/healthz, /health and /readyz, whatever the entry path.
With splitByApp: trueEach app at /<app id> under the entry path. The root answers 404.

frontmcp dev sets FRONTMCP_HTTP_ENTRY_PATH to the path in its own configuration.

Lifecycle and shutdown

bootstrap() goes through these steps:

  1. Parses the configuration, and fails on anything invalid.
  2. Builds the server: its providers, its logger, then its scopes, which build the apps and their tools, resources, prompts, jobs and plugins. This is ready.
  3. Starts the HTTP server and waits until it listens.
  4. Runs every scope's onServerStarted() callbacks, then logs FrontMCP bootstrap complete.

On SIGINT or SIGTERM it shuts the server down: it stops taking new connections, lets requests in flight finish for up to 5 seconds, closes what the server holds (its Redis connections, and a distributed instance's heartbeat), and exits 0, or 1 when a step fails or the whole shutdown takes more than 10 seconds. See stopping a Node server. A server on a Unix socket removes the socket file before draining requests, as described above. (Changed in 1.9.2: before, bootstrap() installed no signal handlers, and SIGTERM ended the process at once.)

Changed in 1.10.16: bootstrap() and runUnixSocket() also shut down the instance they built when listening fails, then rethrow the startup error, within the 10-second cleanup deadline. ExpressHostAdapter.start(port) without an address now falls back to 127.0.0.1, matching the server default (previously 0.0.0.0).

Changed in 1.9.7: before, a failed initialization left the scopes it built alive. Now ready awaits shutdown before rejecting. This applies to the creation methods above and to connect*(). Cleanup failures are logged as Graceful shutdown: … failed and never replace the startup error. If cleanup does not settle within 10 seconds, FrontMCP logs Releasing a server that failed to start did not finish within 10000 ms and rejects with the startup error; the deadline bounds the wait, not the unfinished cleanup.

Changed in 1.9.7: shutdown() called during initialization waits for it to settle before collecting scopes. Before, it could finish with an incomplete scope list and leave scopes alive, on either a successful or a failed start.

Caveats

  • Importing a decorated class starts a server. Keep the configuration in a module of its own, and decorate a class with it only in the entry file, so scripts, tests and workers can import the configuration without starting anything.
  • Only runStdio() and connect() accept the decorated class. The other methods need the configuration object. Pass getDecoratorConfig(Server) if all you have is the class.
  • With splitByApp: true, or a standalone app, only bootstrap(), createHandler() and createFetchHandler() serve every app. runStdio() serves the primary scope only: the apps that aren't standalone, or with splitByApp: true the first app. createDirect() and connect() do too, unless they're given an app, which serves that app's own scope. See Apps, discovery and splitting. (Changed in 1.9.3: before, createDirect() and connect() had no app option. Changed in 1.9.2: createFetchHandler() serves them all; see its entry paths.)
  • Declare one @FrontMcp per process. Each bootstrap() starts another server, and a second one on the same port fails with EADDRINUSE.

Low-level transport exports

@frontmcp/sdk/transport and the SDK root export the same transports and event stores. Changed in 1.11.0: before, the transport subpath had declarations without loadable JavaScript; the root now also exports createEventStore, MemoryEventStore, RedisEventStore, RecreateableStreamableHTTPServerTransport and RecreateableSSEServerTransport.

createEventStore(config, logger?) returns { eventStore, type }; without config.enabled, the store is undefined and type is "disabled". The config takes provider ("memory" by default, "redis" or "sqlite"), maxEvents (10000), ttlMs (300000), and that backend's redis or sqlite settings. Most servers configure transport.eventStore instead.

createEventStore configTypeDefaultDescription
enabledbooleanoffKeep messages for SSE resumability.
provider"memory" | "redis" | "sqlite""memory"Storage backend.
maxEventsnumber10000Maximum retained events.
ttlMsnumber300000Event lifetime in milliseconds.
redisRedisOptionsInputnoneRequired for Redis.
sqliteSqliteOptionsInputnoneRequired for SQLite, including a file path.

Supervising child processes

The Node-only @frontmcp/utils process helpers are also available to server code:

FunctionOptions and result
spawnOwned(command, args, options)Spawn options plus required marker (up to 64 letters, digits, ., _, -, beginning with a letter or digit). Returns { child, stop(signal?, graceMs?) }; stop defaults to SIGTERM, 5000 ms. Adds FRONTMCP_OWNER and a trailing --frontmcp-owner=<marker>:<pid> argument.
reapOrphans(marker, options?)Reap only marked children whose owner died; graceMs defaults to 2000 ms before forcing exit. POSIX only: lists processes through ps; failures throw OwnedProcessError. On Windows, resolves with [] without reaping.
watchParent(options)Required onGone(reason), optional stdin and intervalMs (1000). Reasons: "parent-exited" or "stdin-ended". Returns { close() }.
watchPath(path, options)Required onGone(), optional intervalMs (1000). Missing path triggers once; other filesystem failures do not mean the path was removed. Returns { close() }.
processTreeSpawnOptions(), signalProcessTree(), isProcessTreeAlive(), stopProcessTree()Process-tree operations exported from utils for supervisors.

TASK_WORKER_MARKER and JOB_WORKER_MARKER from the SDK identify its worker kinds. Commands passed to a task runner must accept the added owner argument. The Playground cannot spawn Node processes, so these helpers are described from source.


Usage

Starting the server after setup

A server whose tools need a database connection, or secrets fetched at startup, shouldn't accept calls before they're ready. Keep the configuration in its own module, turn off serve, and call bootstrap() when you're ready:

config.ts
import { HelpDesk } from "./help-desk.app";

export const config = {
  info: { name: "help-desk", version: "1.0.0" },
  apps: [HelpDesk],
  http: { port: 8080, entryPath: "/mcp" },
};
main.ts
import "reflect-metadata";
import { FrontMcp, FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "./config";
import { connectToDatabase } from "./db";

@FrontMcp({ ...config, serve: false })
export default class HelpDeskServer {}

try {
  await connectToDatabase();
  await FrontMcpInstance.bootstrap(config);
} catch (err) {
  console.error("help-desk didn't start:", err);
  process.exit(1);
}

Clients connect to http://localhost:8080/mcp. This needs a real port, so run it locally.

Reading a server's configuration

@FrontMcp records the configuration on the class, with every default filled in. getDecoratorConfig() reads it back, and it's what to pass to the methods that don't take the class. In the Playground, FRONTMCP_SCHEMA_EXTRACT is set, so defining HelpDeskServer records the configuration and starts nothing; the Playground then serves it with createFetchHandler().

Open
import { FrontMcp } from "@frontmcp/sdk";
import { HelpDesk } from "./help-desk.app";

@FrontMcp({ info: { name: "help-desk", version: "1.0.0" }, apps: [HelpDesk] })
export default class HelpDeskServer {}

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

Inspecting a server without serving it

createForGraph() builds the whole server, apps, tools and all, and doesn't serve it. Use it to check what a configuration produces: in a test, or in a script that lists every tool. A server has one scope, root, holding every app's tools. With splitByApp: true it has one scope per app, each at its own path, and a standalone app always gets one of its own.

Open
import { test, expect } from "@frontmcp/testing";
import { FrontMcpInstance } from "@frontmcp/sdk";
import { Billing, BillingApi, HelpDesk } from "./apps";

const info = { name: "help-desk", version: "1.0.0" };

function describe(instance: FrontMcpInstance) {
  return instance.getScopes().map((scope) => ({
    id: scope.id,
    path: scope.routeBase,
    tools: scope.tools.getTools().map((tool) => tool.metadata.name),
  }));
}

test("one scope holds every app's tools", async () => {
  const instance = await FrontMcpInstance.createForGraph({ info, apps: [HelpDesk, Billing] });
  expect(describe(instance)).toEqual([{ id: "root", path: "", tools: ["get_ticket", "refund_invoice"] }]);
});

test("with splitByApp, each app is a scope at its own path", async () => {
  const instance = await FrontMcpInstance.createForGraph({ info, apps: [HelpDesk, Billing], splitByApp: true });
  expect(describe(instance)).toEqual([
    { id: "help-desk", path: "/help-desk", tools: ["get_ticket"] },
    { id: "billing", path: "/billing", tools: ["refund_invoice"] },
  ]);
  expect(instance.getPrimaryScope()?.id).toBe("help-desk");
});

test("a standalone app gets a scope of its own; createDirect() serves the primary one, or that one with `app`", async () => {
  const config = { info, apps: [BillingApi, HelpDesk] };
  const instance = await FrontMcpInstance.createForGraph(config);
  expect(describe(instance)).toEqual([
    { id: "billing-api", path: "/billing-api", tools: ["refund_invoice"] },
    { id: "root", path: "", tools: ["get_ticket"] },
  ]);
  expect(instance.getPrimaryScope()?.id).toBe("root");
  expect(instance.getAppScope("billing-api").routeBase).toBe("/billing-api");
  expect(() => instance.getAppScope("help-desk")).toThrow('No endpoint serves app "help-desk" on its own');

  const server = await FrontMcpInstance.createDirect(config);
  const { tools } = await server.listTools();
  await server.dispose();
  expect(tools.map((tool) => tool.name)).toEqual(["get_ticket"]);

  const billing = await FrontMcpInstance.createDirect(config, { app: "billing-api" });
  const billingTools = await billing.listTools();
  await billing.dispose();
  expect(billingTools.tools.map((tool) => tool.name)).toEqual(["refund_invoice"]);
});

Starting FrontMCP in your browser…

FrontMCP starts when this example comes into view.

A scope's registries are described in Scope and registries.

Serving over stdio

Local clients like Claude Desktop and Cursor can start your server as a subprocess and talk to it over stdin and stdout. Give them an entry file that calls runStdio() with the configuration, and never imports the decorated class:

stdio.ts
import "reflect-metadata";
import { FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "./config";

FrontMcpInstance.runStdio(config);
claude_desktop_config.json
{
  "mcpServers": {
    "help-desk": { "command": "node", "args": ["/abs/path/dist/stdio.js"] }
  }
}

Or keep one entry file and set FRONTMCP_STDIO=1 in the client's configuration ("env": { "FRONTMCP_STDIO": "1" }): @FrontMcp then calls runStdio() instead of starting an HTTP server. Anything the server writes to stdout that isn't a protocol message breaks the client, so log to stderr.

A stdio server is also how a channel reaches a Claude Code session.

Sharing one server between stdio sessions

A client starts a stdio server per session, so three windows of one client run three copies of your server, each with its own caches and connections. With runShared() in the entry file, each of those processes is a session of one server process per key:

shared.ts
import "reflect-metadata";
import { FrontMcpInstance } from "@frontmcp/sdk";
import { config } from "./config";

FrontMcpInstance.runShared(config, { key: "help-desk" }).catch((error) => {
  console.error(error);
  process.exit(1);
});
{
  "mcpServers": {
    "help-desk": { "command": "node", "args": ["/abs/path/dist/shared.js"] }
  }
}

The client's entry is the same as for any stdio server. Install @frontmcp/storage-sqlite beside @frontmcp/sdk. The server keeps running while a session is attached, and exits ten minutes after the last one left; a session of a newer info.version replaces it, and the other sessions follow. This starts processes and opens a socket, so it was run in Node, not in the Playground: see what was run.


Troubleshooting

Invalid input: expected object, received undefined

The error is a ZodError with invalid_union, whose issues are at info and at apps (expected array, received undefined). You passed the decorated class to a method that takes the configuration object: bootstrap(), createFetchHandler(), createDirect() or createForGraph(). The class has no info or apps of its own: they're recorded on it. (Changed in 1.9: before, the issue was expected object, received function.)

// 🚩 The class
await FrontMcpInstance.createDirect(HelpDeskServer);

// ✅ Its configuration
await FrontMcpInstance.createDirect(getDecoratorConfig(HelpDeskServer)!);

Better, export the configuration from a module of its own and pass that. The first Playground shows both.

listen EADDRINUSE: address already in use 127.0.0.1:3000

Something already listens on the port: another copy of your server, or a second bootstrap() in the same process, often because a script imported the decorated class and then called bootstrap() too. Stop the other process, or choose another port with http.port or the PORT environment variable. Set PORT in the environment that starts the process, or in code before the server starts.

A script that imports my server starts listening

Importing a class decorated with @FrontMcp starts a server. Import the configuration module instead, or set serve: false on the decorator and start the server where you want it with bootstrap().

Serverless handler is not initialized

getServerlessHandlerAsync() found no handler, because FRONTMCP_SERVERLESS wasn't set to 1 or true when the decorated class was defined. Without it, @FrontMcp called bootstrap() and started an HTTP server instead. Set the variable in the platform's environment, or skip the decorator and call createHandler(config) or createFetchHandler(config) yourself.

My client gets 404 or Cannot POST /mcp

The MCP endpoint is at the root unless http.entryPath is set. See the @FrontMcp entry.

Only my first app is reachable

The server uses splitByApp: true and is served by runStdio(), or by createDirect() or connect() without an app, which use the first scope only. Pass { app } to createDirect() or connect() for another app's scope, serve the server with bootstrap(), createHandler() or createFetchHandler(), which give each app its path, or turn splitByApp off.

the sqlite type needs @frontmcp/storage-sqlite

runShared() rejected with Invalid sqlite configuration: the sqlite type needs @frontmcp/storage-sqlite. Install it with: npm install @frontmcp/storage-sqlite, and the client's first request got -32097 dev_reload_deadline with the same text in data.error. The session that starts the shared server takes a start lock in a SQLite file. Install the package beside @frontmcp/sdk.

running the shared server "…" in this process: …

A runShared() session couldn't use the shared server, and runs the server itself: the reason follows the colon, like the shared server runs version 1.1.0, older than this session's 2.0.0, and replaceOlder is off. Its tools work, but it gets nothing the server sends on its own, channel events included. It stays that way until its client starts it again.

A shared session didn't get an event the server sent

Either the session runs the server in its own process (the entry above), or its server went away and nothing took the key over, so the session has no stream until its client's next request. A session attached to a running shared server gets what the server sends, and follows a server that replaced its own after about 8 seconds. Changed in 1.12.0: before, no shared session got what its server sends on its own.

Releasing a server that failed to start did not finish within 10000 ms

Initialization failed, and cleanup is still pending after its 10-second deadline. ready rejects with the original startup error, so fix that error first. Check provider disposal, disconnect hooks and storage shutdown for work that never settles. The deadline stops waiting; it does not cancel the unfinished cleanup. New in 1.9.7.

Report a docs issue · Report a security concern privately