# @frontmcp/testing

> Test a FrontMCP server end to end, with a connected MCP client in every test and matchers that understand MCP results.

Source: https://frontmcp.dev/reference/testing

[Checked against FrontMCP 1.15.2](https://frontmcp.dev/versions#how-pages-are-checked) on December 4, 2026

`@frontmcp/testing` runs end-to-end tests against your server. It starts the server, gives every test `mcp`, an MCP client connected to it, and adds matchers like `toBeSuccessful()` to `expect`. Tests run under Jest with `frontmcp test`. The Playground's **Tests** tab runs the same test files in your browser. For a guided introduction, see [Testing Your Server](https://frontmcp.dev/learn/testing-your-server).

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

test.use({ server: "./src/main.ts" });

test("name", async ({ mcp }) => {
  expect(await mcp.tools.call("search_tickets", { query: "log" })).toBeSuccessful();
});
```



---

<a id="reference"></a>

## Reference

<a id="testname-fn"></a>

### `test(name, fn)`

Registers a test. `fn` receives the [fixtures](https://frontmcp.dev/reference/testing#fixtures) and is usually `async`. Before each test, the library connects a new `mcp` client. The server starts when the first test that needs it runs, and the tests with the same `test.use()` options share it: by default, every test in the file.

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

test.use({ server: "./src/main.ts" });

test("finds tickets by title", async ({ mcp }) => {
  const result = await mcp.tools.call("search_tickets", { query: "log" });
  expect(result).toBeSuccessful();
  expect(result.json()).toEqual({ tickets: [{ id: "T-1", title: "Cannot log in" }] });
});
```

[See more examples below.](https://frontmcp.dev/reference/testing#usage)

`test` also has:

| Member | Description | In the Playground |
| --- | --- | --- |
| `test.describe(name, body)` | Groups tests. Their names are shown under the group's. `test.describe.only` and `test.describe.skip` focus or skip the group. | Yes |
| `test.each(table)(name, fn)` | One test for each row of `table`. `fn` receives the fixtures, then the row's values: `test.each([["log", 2]])("%s finds %i", async ({ mcp }, query, count) => …)`. It takes a tagged template too. `test.describe.each(table)(name, body)` passes each row to `body`. | No |
| `test.only(name, fn)` | Runs only the focused tests in the file. | Yes |
| `test.skip(name, fn)` | Skips a test. | Yes |
| `test.skip(condition, reason?)` | When `condition` is true, skips every test registered after it in the same `describe` block. | No |
| `test.todo(name)` | A placeholder for a test you haven't written. | No |
| `test.use(options)` | Configures the server and client for the file, or for the `describe` block it's called in. See [below](https://frontmcp.dev/reference/testing#testuseoptions). | Accepted, and ignored |
| `test.beforeEach(fn)`, `test.afterEach(fn)` | Run `fn` before, or after, each test. A function that takes a parameter receives the test's [fixtures](https://frontmcp.dev/reference/testing/fixtures#hooks), the same `mcp` the test gets; one without is Jest's own hook. | No |
| `test.beforeAll(fn)`, `test.afterAll(fn)` | Jest's hooks, without fixtures. `beforeAll` runs before the server starts. | No |

<a id="testuseoptions"></a>

### `test.use(options)`

Configures how the server is started and how clients connect. Call it at the top of the file to configure every test in it, or inside a `test.describe` to configure that block: the block's options are added to the file's, and a block with a configuration of its own starts a server of its own, which stops when the block ends. Calling it again in the same place merges the new options in. [Fixtures](https://frontmcp.dev/reference/testing/fixtures) has every option, how calls combine, and the pitfalls.

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `server` | `string` | | The server's entry file, like `"./src/main.ts"`, run with `npx tsx`. A value with a space is run as a command. Required, unless you set `baseUrl`. |
| `baseUrl` | `string` | | Test a server that's already running, at this URL. With `server`, it overrides the URL the client connects to. |
| `port` | `number` | a free port | The port to start the server on. `0`, like leaving it out, means any free port from the project's range. Test files claim ports in a lock folder of the system's temporary folder, one for each user: `frontmcp-testing-ports-<uid>`. |
| `project` | `string` | | An E2E project name, to take a port from that project's range. |
| `entryPath` | `string` | `"/"` | Where the server serves MCP, if it sets `http.entryPath`. |
| `transport` | `"streamable-http" \| "sse"` | `"streamable-http"` | The client's transport. `"sse"` is the older HTTP+SSE transport (`GET /sse`, then `POST /message`), for servers that still serve it: see [Fixtures](https://frontmcp.dev/reference/testing/fixtures#options). It posts only to the origin it connected to: a stream that names a message endpoint elsewhere fails with `SSE server at … named a message endpoint on another origin (…); the legacy SSE transport only posts to the origin it connected to.` |
| `protocolVersion` | `string` | `"2025-06-18"` | MCP revision. `"2026-07-28"` connects with discovery and no session; it requires Streamable HTTP. |
| `mcpLogLevel` | MCP logging level or `false` | `"debug"` | Log messages to request from the server. `false` disables the automatic request. |
| `publicMode` | `boolean` | `false` | Don't ask the server for an anonymous token, so `mcp` sends no `Authorization` header, for servers with `auth: { mode: "public" }`. A client made with a token of its own still sends it. |
| `env` | `Record<string, string>` | | Environment variables for the server, read when it starts. A `JWT_SECRET` here also signs the `auth` fixture's tokens. |
| `startupTimeout` | `number` | `30000` | How long to wait for the server to start, in milliseconds. |
| `logLevel` | `"debug" \| "info" \| "warn" \| "error"` | | The server's [log level](https://frontmcp.dev/reference/server/logging#choosing-a-level), passed to it as `FRONTMCP_LOG_LEVEL`, unless its `logging.level` is set. `"debug"` also prints the server's command and startup. It doesn't set the level of the log messages the server sends the client; see [Notifications](https://frontmcp.dev/reference/testing#notifications). |
| `auth` | `{ mode?, type? }` | | Says what the server's auth is; it doesn't change it. `mode: "public"` keeps `mcp` anonymous, like `publicMode`. `mode` and `type` also reach the server as `FRONTMCP_TEST_AUTH_MODE` and `FRONTMCP_TEST_AUTH_TYPE`, which only code of your own reads. |

<a id="fixtures"></a>

### Fixtures

The test function receives an object with three fixtures, and so does a `test.beforeEach()` or `test.afterEach()` hook that takes a parameter. [Fixtures](https://frontmcp.dev/reference/testing/fixtures) covers each in full, and when each is created and torn down; [Testing authentication](https://frontmcp.dev/reference/testing/auth) covers `auth`.

| Fixture | Type | Description |
| --- | --- | --- |
| `mcp` | `McpTestClient` | A client connected to the server. A new one for each test. |
| `server` | `ServerFixture` | The running server: `info` (`baseUrl`, `port`, `pid`), `createClient({ token, transport, clientInfo, entryPath })` for more clients, `createClientBuilder()`, `restart()`, `getLogs()` and `clearLogs()`. |
| `auth` | `AuthFixture` | Makes JWTs: `createToken({ sub, scopes, email, name, claims, expiresIn })`, `createExpiredToken({ sub })`, `createInvalidToken({ sub })`, `users` (`admin`, `user` and `readOnly`), `getJwks()`, `getIssuer()` and `getAudience()`. |

> **Note**
>
> The Playground's Tests tab only has `mcp`, connected to the example's server in your browser. `server` and `auth` are `undefined` there. Its `mcp` has no `events`, and its requests carry no `Mcp-Name` header for the events methods, so a test in a Playground reads events with `mcp.raw.request()` for `events/list`, or through a [`connect()`](https://frontmcp.dev/reference/sdk/connect#events) client.

<a id="the-mcp-client"></a>

### The `mcp` client

<a id="tools-resources-and-prompts"></a>

#### Tools, resources and prompts

| Method | Returns | Description |
| --- | --- | --- |
| `mcp.tools.list()` | `Promise<Tool[]>` | Every tool. It follows `nextCursor` through the pages of `tools/list`, which hold 40 tools by default ([Listing a server with many tools](https://frontmcp.dev/reference/testing#listing-a-server-with-many-tools)). Throws if a request fails, if the server sends the same cursor twice, or if it doesn't finish within 1000 pages. |
| `mcp.tools.call(name, args?, options?)` | `Promise<ToolResultWrapper>` | Calls a tool. Doesn't throw when the call fails; check the [wrapper](https://frontmcp.dev/reference/testing#toolresultwrapper). `options.progressToken` is sent as `_meta.progressToken` (the Playground ignores `options`). |
| `mcp.resources.list()` | `Promise<Resource[]>` | The resources in `resources/list`, paged like `tools.list()`. Throws if a request fails. |
| `mcp.resources.listTemplates()` | `Promise<ResourceTemplate[]>` | The templates in `resources/templates/list`, paged like `tools.list()`. Throws if a request fails. |
| `mcp.resources.read(uri)` | `Promise<ResourceContentWrapper>` | Reads a resource. Doesn't throw when the read fails. |
| `mcp.prompts.list()` | `Promise<Prompt[]>` | The prompts in `prompts/list`, paged like `tools.list()`. Throws if a request fails. |
| `mcp.prompts.get(name, args?)` | `Promise<PromptResultWrapper>` | Gets a prompt. `args` values are strings. |

<a id="skills"></a>

#### Skills

The Node fixture's `mcp.skills` uses the [MCP Skills extension](https://frontmcp.dev/reference/sdk/skill#skillslist). In a Playground, send the skills requests with `mcp.raw.request()` or use the SDK's [`DirectClient`](https://frontmcp.dev/reference/sdk/connect#reading-a-skill-and-checking-its-manifest).

| Method | Returns | Description |
| --- | --- | --- |
| `mcp.skills.list({ cursor? })` | `Promise<SkillsPage>` | Lists skill entries. Omit the options to follow every page, or pass a cursor for a specific page. |
| `mcp.skills.get(uri)` | `Promise<SkillsExtensionEntry>` | Gets the entry at its published `SKILL.md` URI. |
| `mcp.skills.read(skill, ref?)` | `Promise<SkillFile>` | Checks a file against the entry. The default file is `SKILL.md`. |
| `mcp.skills.readDirectory(uri)` | `Promise<SkillDirectoryResource[]>` | Reads every page of a directory's direct children. |

A server error rejects with `McpProtocolError`. A failed entry or file check rejects with [`SkillVerificationError`](https://frontmcp.dev/reference/errors#skills-errors).

<a id="raw-requests"></a>

#### Raw requests

| Method | Returns | Description |
| --- | --- | --- |
| `mcp.raw.request(message)` | `Promise<JSONRPCResponse>` | Sends a JSON-RPC request as you wrote it (`jsonrpc`, `id`, `method`, `params`) and returns the response, `error` included. |
| `mcp.raw.notify(message)` | `Promise<void>` | Sends a notification. Not in the Playground. |
| `mcp.raw.sendRaw(data)` | `Promise<JSONRPCResponse>` | Sends a string as the request body, to test parse errors. Not in the Playground. |

<a id="elicitation"></a>

#### Elicitation

| Method | Description |
| --- | --- |
| `mcp.onElicitation(handler)` | Answers the server's [elicitation](https://frontmcp.dev/reference/sdk/elicit) requests. `handler(request)` receives the `message` and `requestedSchema`, and returns `{ action, content? }` or a promise of one. `action` is `"accept"`, `"decline"` or `"cancel"`. |
| `mcp.clearElicitationHandler()` | Removes the handler. |

Without a handler, `frontmcp test`'s client answers every question with `decline`. The Playground's test client fails the test instead, and says which question was asked. If the handler throws, `frontmcp test`'s client answers `cancel`.

<a id="notifications"></a>

#### Notifications

| Method | Description |
| --- | --- |
| `mcp.resources.subscribe(uri)`, `unsubscribe(uri)` | Send `resources/subscribe` and `resources/unsubscribe`; reject when the server refuses. Not in the Playground. |
| `mcp.notifications.collect()` | A collector with `received` (every notification the client has received, before and after the collector was made: `method`, `params`, `timestamp`), `has(method)` and `waitFor(method, timeoutMs)`. |
| `mcp.notifications.collectProgress()` | A collector with `all` (`progress`, `total`, `progressToken`, `message?`, `timestamp`) and `waitForComplete(timeoutMs)`. Later tool calls send a progress token. |
| `mcp.notifications.send(method, params?)` | Sends a notification to the server. Not in the Playground. |

> **Pitfall: Collect progress before the call**
>
> Call `collectProgress()` before the call so it sends a progress token. The client requests debug log messages by default (`mcpLogLevel` changes this). Log and progress notifications for the call arrive before its result.
> 
> The Playground asks for progress and debug logs on every tool call. Under `frontmcp test`, start collecting progress before the call.

<a id="events"></a>

#### Events

`mcp.events` is the [events client](https://frontmcp.dev/reference/sdk/connect#events) that `connect()` clients have, over the test client's connection. Not in the Playground.

| Method | Description |
| --- | --- |
| `mcp.events.list()` | The [events](https://frontmcp.dev/reference/sdk/event) the caller may subscribe to, every page of `events/list`. |
| `mcp.events.subscribe(name, args?, options?)` | Subscribes, and resolves to an async iterable of occurrences with `mode`, `cursor` and `cancel()`. A refusal rejects with `EventRequestError`. `options.delivery` forces `"push"`, `"poll"` or `"webhook"`. |
| `mcp.events.close()` | Ends every subscription. `mcp.disconnect()` does too, and so does the end of the test. |

The client subscribes by push, holding an `events/stream` open, over Streamable HTTP; by poll over `transport: "sse"`; and by webhook when it was built with `withEvents({ webhook })` and the event offers it, which needs a [`WebhookReceiver`](https://frontmcp.dev/reference/testing#webhookreceiver) and a server whose auth signs callers in. Under `protocolVersion: "2026-07-28"` it sends the event's name in the `Mcp-Name` header of `events/poll`, `events/stream`, `events/subscribe` and `events/unsubscribe`, which the server requires. [Testing events](https://frontmcp.dev/reference/testing#testing-events) shows push and webhook.

<a id="everything-else"></a>

#### Everything else

| Member | Description |
| --- | --- |
| `mcp.protocolVersion` | The MCP revision in use: `2025-06-18` by default, or the configured `protocolVersion`. The Playground speaks `2026-07-28`. |
| `mcp.discover()` | Returns server discovery, including `supportedVersions`, on every protocol revision. |
| `mcp.isConnected()` | Whether the client is connected. |
| `mcp.serverInfo`, `mcp.capabilities`, `mcp.hasCapability(name)`, `mcp.instructions` | What the server said about itself when the client connected. Not in the Playground. |
| `mcp.sessionId`, `mcp.session`, `mcp.auth`, `mcp.authenticate(token)`, `mcp.disconnect()`, `mcp.reconnect()` | The session and credentials. `authenticate(token)` opens a new session as that token's user, and rejects when the server refuses the token, leaving the old session as it was: see [Testing authentication](https://frontmcp.dev/reference/testing/auth#the-auth-fixture). Not in the Playground. |
| `mcp.logs`, `mcp.trace` | The client's own log and a trace of every request. Not in the Playground. |
| `mcp.mock`, `mcp.intercept` | Canned responses and request interceptors. Not in the Playground. |
| `mcp.setTimeout(ms)` | The request timeout. Default `30000`. Not in the Playground. |

<a id="result-wrappers"></a>

### Result wrappers

<a id="toolresultwrapper"></a>

#### `ToolResultWrapper`

What `mcp.tools.call()` returns.

| Member | Type | Description |
| --- | --- | --- |
| `isSuccess` | `boolean` | `true` unless the call failed. |
| `isError` | `boolean` | `true` for a JSON-RPC error, or a result with `isError: true`. |
| `error` | `{ code, message, data? }` or `undefined` | The JSON-RPC error. `undefined` for tool errors, which arrive as results. |
| `raw` | `CallToolResult` | The result as received: `content`, `structuredContent`, `isError` and `_meta`. |
| `durationMs` | `number` | How long the call took. |
| `json()` | `unknown` | Parses the first text block as JSON. For a result with a tool UI, returns `structuredContent`. Throws "No text content to parse as JSON" when there's no text block. |
| `text()` | `string \| undefined` | The first text block's text. |
| `hasTextContent()`, `hasImageContent()`, `hasResourceContent()` | `boolean` | Whether any content block has that type. |
| `hasToolUI()` | `boolean` | Whether `_meta` carries a rendered tool UI. |

<a id="resourcecontentwrapper"></a>

#### `ResourceContentWrapper`

What `mcp.resources.read()` returns.

| Member | Type | Description |
| --- | --- | --- |
| `isSuccess`, `isError` | `boolean` | Whether the read worked. |
| `error` | `{ code, message, data? }` or `undefined` | The JSON-RPC error, when the read failed. |
| `raw` | `ReadResourceResult` | The result as received, with its `contents`. |
| `durationMs` | `number` | How long the read took. |
| `json()` | `unknown` | Parses the first content block's `text` as JSON. |
| `text()` | `string \| undefined` | The first content block's `text`. |
| `mimeType()` | `string \| undefined` | The first content block's `mimeType`. It's a method. |
| `hasMimeType(type)` | `boolean` | Whether the first content block has that MIME type. |

<a id="promptresultwrapper"></a>

#### `PromptResultWrapper`

What `mcp.prompts.get()` returns.

| Member | Type | Description |
| --- | --- | --- |
| `isSuccess`, `isError`, `error`, `raw`, `durationMs` | | As for resources. |
| `messages` | `PromptMessage[]` | The prompt's messages, each with a `role` and `content`. |
| `description` | `string \| undefined` | The prompt's description. |

<a id="expect"></a>

### `expect`

`expect` is Jest's, with the MCP matchers added: `toBeSuccessful()`, `toContainTool()` and the rest. See [Matchers](https://frontmcp.dev/reference/testing/matchers) for every one, and for the Jest matchers the Playground supports.

<a id="caveats"></a>

#### Caveats

- **Tool errors are results, not JSON-RPC errors.** For a tool that fails, `isError` is `true` and `error` is `undefined`, so a JSON-RPC code like `toBeError(-32602)` can't match. Pass the FrontMCP code as a string instead: `toBeError("INVALID_INPUT")` checks `result.raw._meta?.code`.
- **`json()` parses the text FrontMCP sent.** A tool that returns a plain value, like `12`, sends `{"value":12}`, so `json()` returns `{ value: 12 }`.
- **The list helpers follow `nextCursor`.** `tools.list()`, `resources.list()`, `resources.listTemplates()` and `prompts.list()` read every page, and throw if the server returns the same cursor twice or doesn't finish within 1000 pages. [Listing a server with many tools](https://frontmcp.dev/reference/testing#listing-a-server-with-many-tools) shows how to read one page at a time with `mcp.raw.request()`.
- **Tests with the same `test.use()` options share one server.** By default that's every test in the file, so anything a tool keeps in memory carries over from test to test. Don't depend on the order tests run in.
- **The protocol version changes some answers.** The default test client speaks `2025-06-18`; set `test.use({ protocolVersion: "2026-07-28" })` to test the revision the Playground uses. Reading an unknown resource returns `-32002` in the former and `-32602` in the latter. Elicitation answers are validated under both.

<a id="webhookreceiver"></a>

### `WebhookReceiver`

An HTTP server on `127.0.0.1` that stands in for the callback of a webhook subscription to an [event](https://frontmcp.dev/reference/sdk/event). It answers the server's verification challenge, checks each delivery's signature, records every request, and can be told to fail. It isn't a fixture: create one in the test file, and stop it when the tests are done.

```ts
import { WebhookReceiver } from "@frontmcp/testing";

const receiver = new WebhookReceiver();
const { url } = await receiver.start(); // http://127.0.0.1:<port>/hooks/mcp
```

| Option | Default | Description |
| --- | --- | --- |
| `secrets` | none | Secrets that sign deliveries of any subscription, for a test that sends `events/subscribe` itself. A request none of them signed is answered `401`. A client built with `withEvents()` registers its own secret, so it needs none here. |
| `receivers` | none | Path prefixes for `/.well-known/mcp-webhook-receiver.json`, like `["/hooks/"]`, which lets the server accept the callback without a challenge. Without it the document is a `404`, and the server sends the challenge. |
| `path` | `"/hooks/mcp"` | The path deliveries are sent to. |
| `port` | a free port | The port to listen on. |

| Member | Description |
| --- | --- |
| `start()` | Listens, and resolves to `{ url, origin, port }`. |
| `stop()` | Stops listening. |
| `url` | The callback URL. Throws `WebhookReceiver is not started: call start() first` before `start()`. |
| `eventReceiver` | The receiver to pass as `webhook.receiver` to `withEvents()`, with `url`. |
| `requests` | Every request received, oldest first: `{ kind, path, body, json, webhookId, webhookTimestamp, webhookSignature, subscriptionId, signatureCheck, answeredStatus, receivedAt }`. `kind` is `"verification"`, `"event"`, `"gap"` or `"terminated"`; `signatureCheck` is `"valid"`, `"missing"`, `"stale"` or `"mismatch"`, or `"unchecked"` when the receiver has no secret for the subscription. |
| `verifications()`, `deliveries()` | The verification challenges, and the event deliveries, retries included. |
| `waitForDeliveries(count, timeoutMs?)` | Resolves to the deliveries once `count` have arrived, retries included. Rejects after `timeoutMs`, `5000` by default, with `WebhookReceiver: 1 of 2 deliveries arrived in 5000 ms`. |
| `failNext(count, status?)` | Answers the next `count` deliveries with `status`, `500` by default, so the server retries them. Challenges aren't affected. |
| `echoChallenges(false)` | Answers challenges without the challenge, so the server refuses the subscription with `-32027`, `The callback endpoint could not be verified (challenge_failed)`. |
| `addSecret(secret)` | Accepts deliveries signed with one more secret, as after a rotation. |
| `clear()` | Forgets the requests received so far. |

The receiver listens over `http` on a loopback address, which a server refuses as a callback, with `Invalid delivery.url: it must use https`, unless it sets `events.webhook.unsafeAllowLocalCallbacks: true`. Set it for the tests' server only.

<a id="recording-and-replaying-client-calls"></a>

### Recording and replaying client calls

`CallRecorderPlugin` from `@frontmcp/sdk` appends client `tools/call`, `resources/read` and `prompts/get` requests and their answers to JSONL. Register `CallRecorderPlugin.init(options)` on the server or app.

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `path` | `string` | `".frontmcp/calls.jsonl"` | Recording file. |
| `methods` | `("tools/call" \| "resources/read" \| "prompts/get")[]` | all three | Nonempty list of methods to record. |
| `redactFields` | `string[]` | `[]` | Additional case-insensitive fields to redact. Credential-like names are already redacted, including keys and page tokens. |
| `keepFields` | `string[]` | `[]` | Safe fields to keep despite matching credential names. |
| `maxBytes` | `number` | `10485760` | Positive whole file-size limit. Later calls are skipped when it is reached. |

```ts replay.spec.ts
import { test, expect, replaySession, formatReplayReport } from "@frontmcp/testing";

test("recorded calls keep their answers", async ({ server }) => {
  const report = await replaySession(".frontmcp/calls.jsonl", server, { ignore: ["**.timestamp"] });
  expect(report).toMatchRecording();
  console.log(formatReplayReport(report));
});
```

`replaySession(file, serverOrBaseUrl, { client?, ignore? })` returns a report with `calls` and `differences`; each call's outcome is `same`, `changed`, `new-error` or `gone-error`. `client` supplies connection options such as authentication. The matcher fails when `differences` is nonempty. `ReplayRecordingError` identifies invalid recording lines. The CLI equivalent is `frontmcp test --replay .frontmcp/calls.jsonl --replay-ignore '**.timestamp'`.

> **Note**
>
> Recording writes a Node file and replay connects to a running server. The Playground cannot run this example. Review recordings before sharing them: redaction replaces matching field values and recognized credential text, but cannot identify every secret.

The recorder uses the `@frontmcp/utils` redaction and file helpers:

| Helper | Returns | Description |
| --- | --- | --- |
| `redactFields(object, fields, maxDepth?)` | `Record<string, unknown>` | Replaces matching field values, including in nested lists. Depth defaults to 5. `fields` is a case-insensitive list or `(key: string) => boolean`. |
| `redactJson(value, fields)` | `unknown` | Redacts a JSON value at any depth, including JSON inside strings and recognized credential text. |
| `appendFile(path, content, options?)` | `Promise<void>` | Appends UTF-8 text on Node; `options.mode?: number` sets permissions on a new file. |
| `writeFile(path, content, options?)` | `Promise<void>` | Writes UTF-8 text on Node. Takes `mode?: number` and `flag?: string`, such as `"a"` for appending. |

<a id="testing-an-http-host"></a>

### Testing an HTTP host

Use `describeHostConformance(name, options)` in a Jest test file for a custom [`http.hostFactory`](https://frontmcp.dev/reference/sdk/frontmcp#using-your-own-http-server). For another runner, call `hostConformanceSuite(options)`, await `start()`, run the cases in order, and await `stop()` in cleanup. Each case exposes `id`, `group`, `title`, `run()` and an optional `skipReason`. Mark cases with a `skipReason` as skipped in your runner.

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `host` | `(options: HostAdapterOptions) => FrontMcpServer` | required | Build the host with the resolved options the suite passes. |
| `unsupported` | `Partial<Record<HostCapability, string>>` | none | Skip an optional group with a reason. The optional groups are `form-bodies`, `compressed-bodies`, `conditional-requests` and `request-listener`; naming another group fails setup. |
| `deviations` | `Record<string, string>` | none | Skip known differences by case ID, with reasons. Unknown IDs fail setup. |
| `timeout` | number | `15000` | Per-case Jest timeout in milliseconds. Other runners set their own deadlines. |

> **Note**
>
> The conformance suite opens a real Node listener, so run it in Jest or another Node test runner. The Playground does not run it.

```ts built-in-host.spec.ts
import { hostKit } from "@frontmcp/sdk";
import { describeHostConformance } from "@frontmcp/testing";

describeHostConformance("built-in host", {
  host: (options) => hostKit().createBuiltInHost(options),
});
```

---

<a id="testing-across-runtimes"></a>

### Testing across runtimes

`describeRuntimes(runtimes, options, define)` from `@frontmcp/testing` defines the same Jest suite under each `runtime: <name>` group. Each group starts its server before the tests, makes `runtime.client` available to them and closes clients and the runtime afterward.

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `path` | `string` | `"/"` | MCP path for HTTP-based runtimes. Use an app's full path for a split or standalone app. |
| `inProcess` | `{ server: RuntimeServer }` | required for `"in-process"` | Builds from a configuration or decorated class and passes requests through a fetch handler without opening a port. |
| `stdio` | `{ command: string, args?: string[], cwd?: string, env?: Record<string, string> }` | required for `"stdio"` | Starts a process per client with `FRONTMCP_STDIO=1`. |
| `http` | `{ command?: string, url?: string, cwd?: string, env?: Record<string, string> }` | required for `"http"` | Connects to `url` when supplied, or runs `command` with a free `PORT`. |
| `workers` | `{ cwd: string, command?: string, env?: Record<string, string> }` | required for `"workers"` | Runs `wrangler dev` on a free port in `cwd`. Build the Worker before the suite. |
| `startupTimeout` | `number` | `120000` | Milliseconds a server may take to start. |
| `client` | `RuntimeConnectOptions \| false \| ((runtime: TestRuntime) => RuntimeConnectOptions \| false \| Promise<RuntimeConnectOptions \| false>)` | anonymous client | Set `false` to connect from the test with `runtime.connect()`. A function can choose credentials per runtime. |

Use `{ token?, clientInfo? }` with `runtime.connect()` or `options.client`. Supply `token` when the HTTP-based server requires a bearer token. In-process tests run the server's HTTP auth flow too. Stdio refuses a bearer token.

For another test runner, use `await startRuntime(name, options)`. The result exposes `connect()` and `stop()`. Call `stop()` in teardown to close every client and stop the server. `wranglerDevCommand(command?)` returns a supplied command or the default command configured to listen on loopback and use `PORT`.

A `RuntimeStartError` begins with `[runtime: <name>] failed to start` and has the original error as its cause. Check the command, Worker directory or initial client options for the runtime named in the error.

<a id="usage"></a>

## Usage

<a id="running-the-same-checks-against-node-and-a-worker"></a>

### Running the same checks against Node and a Worker

Build the Worker with [`frontmcp build --target cloudflare`](https://frontmcp.dev/reference/cli#the-targets) before running this Jest suite. The first three runtime options point at the same server configuration or entry file.

```ts runtimes.spec.ts
import { describeRuntimes } from "@frontmcp/testing";
import { serverConfig } from "../src/config";

describeRuntimes(["in-process", "stdio", "http", "workers"], {
  path: "/mcp",
  inProcess: { server: serverConfig },
  stdio: { command: "npx", args: ["tsx", "src/main.ts"] },
  http: { command: "npx tsx src/main.ts" },
  workers: { cwd: "." },
}, (runtime) => {
  it("lists the echo tool", async () => {
    const { tools } = await runtime.client.listTools();
    expect(tools.map((tool) => tool.name)).toContain("echo");
  });
});
```

> **Note**
>
> This suite uses Jest, Node child processes and Wrangler when it starts the Worker. Run it from your project in Node.

<a id="writing-a-test-file"></a>

### Writing a test file

Name test files `*.test.ts` or `*.spec.ts` in a Playground, and `*.e2e.spec.ts` in a project. A visible test file adds a **Tests** tab, which runs the tests against a fresh copy of the example.

```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: "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: tickets.filter((t) => t.title.toLowerCase().includes(query.toLowerCase())) };
  }
}
```

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

test("search_tickets is listed", async ({ mcp }) => {
  expect(await mcp.tools.list()).toContainTool("search_tickets");
});

test("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("rejects a query shorter than 3 characters", async ({ mcp }) => {
  const result = await mcp.tools.call("search_tickets", { query: "a" });
  expect(result).toBeError();
  expect(result.raw._meta?.code).toBe("INVALID_INPUT");
});
```

<a id="checking-a-tools-result"></a>

### Checking a tool's result

The wrapper gives you the parsed result, the raw one, and whether the call failed. A tool error sets `isError` but not `error`, because it arrives as a result.

```ts get-ticket.tool.ts
import { PublicMcpError, 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 }) {
    if (id !== "T-1") this.fail(new PublicMcpError(`There's no ticket ${id}.`));
    return { id, title: "Cannot log in", status: "open" };
  }
}

@Tool({ name: "count_open", description: "How many tickets are open", inputSchema: {} })
export class CountOpen extends ToolContext {
  async execute() {
    return 12;
  }
}
```

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

test("json() parses the result", async ({ mcp }) => {
  const result = await mcp.tools.call("get_ticket", { id: "T-1" });
  expect(result.isSuccess).toBe(true);
  expect(result.json()).toEqual({ id: "T-1", title: "Cannot log in", status: "open" });
  expect(result.raw.structuredContent).toEqual(result.json());
});

test("a plain value arrives wrapped", async ({ mcp }) => {
  const result = await mcp.tools.call("count_open");
  expect(result.json()).toEqual({ value: 12 });
});

test("a tool error is a result with isError", async ({ mcp }) => {
  const result = await mcp.tools.call("get_ticket", { id: "T-9" });
  expect(result.isError).toBe(true);
  expect(result.error).toBeUndefined();
  expect(result.text()).toBe("There's no ticket T-9.");
  expect(result.raw._meta?.code).toBe("PUBLIC_ERROR");
});
```

<a id="testing-resources-and-prompts"></a>

### Testing resources and prompts

`resources.read()` and `prompts.get()` return wrappers too. Templates have their own list.

```ts help-desk.ts
import { Prompt, PromptContext, Resource, ResourceContext, ResourceTemplate } from "@frontmcp/sdk";

@Resource({ name: "sla", uri: "policy://sla", mimeType: "application/json", description: "Reply times by priority" })
export class SlaPolicy extends ResourceContext {
  async execute() {
    return { high: "4 hours", normal: "1 business day" };
  }
}

@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({ id, title: "Cannot log in" }) }] };
  }
}

@Prompt({ name: "triage", description: "Triage a ticket", arguments: [{ name: "id", required: true }] })
export class TriagePrompt extends PromptContext {
  async execute(args: Record<string, string>) {
    return { messages: [{ role: "user" as const, content: { type: "text" as const, text: `Read ticket://${args.id} and suggest a priority.` } }] };
  }
}
```

```ts help-desk.test.ts active
import { test, expect } from "@frontmcp/testing";

test("the SLA policy is listed and reads as JSON", async ({ mcp }) => {
  expect(await mcp.resources.list()).toContainResource("policy://sla");
  const content = await mcp.resources.read("policy://sla");
  expect(content.mimeType()).toBe("application/json");
  expect(content.json()).toEqual({ high: "4 hours", normal: "1 business day" });
});

test("tickets are read through the template", async ({ mcp }) => {
  expect(await mcp.resources.listTemplates()).toContainResourceTemplate("ticket://{id}");
  const content = await mcp.resources.read("ticket://T-1");
  expect(content.json()).toEqual({ id: "T-1", title: "Cannot log in" });
});

test("reading an unknown URI fails", async ({ mcp }) => {
  const content = await mcp.resources.read("policy://refunds");
  expect(content.isError).toBe(true);
  expect(content.error?.message).toContain("Resource not found");
});

test("the triage prompt names the ticket", async ({ mcp }) => {
  const prompt = await mcp.prompts.get("triage", { id: "T-1" });
  expect(prompt.messages).toHaveLength(1);
  expect(prompt.messages[0].role).toBe("user");
  expect(prompt.messages[0].content).toMatchObject({ type: "text", text: expect.stringContaining("ticket://T-1") });
});
```

<a id="answering-elicitation"></a>

### Answering elicitation

Register a handler before calling a tool that asks the user something. It plays the user: return what they would choose.

```ts close-ticket.tool.ts
import { Tool, ToolContext, z } from "@frontmcp/sdk";

@Tool({ name: "close_ticket", description: "Close a ticket after the user confirms", inputSchema: { id: z.string() } })
export class CloseTicket extends ToolContext {
  async execute({ id }: { id: string }) {
    const answer = await this.elicit(`Close ticket ${id}?`, z.object({ confirm: z.boolean() }));
    return { closed: answer.status === "accept" && answer.content?.confirm === true };
  }
}
```

```ts close-ticket.test.ts active
import { test, expect } from "@frontmcp/testing";

test("closes when the user confirms", async ({ mcp }) => {
  mcp.onElicitation(() => ({ action: "accept", content: { confirm: true } }));
  expect((await mcp.tools.call("close_ticket", { id: "T-1" })).json()).toEqual({ closed: true });
});

test("stays open when the user declines", async ({ mcp }) => {
  mcp.onElicitation(() => ({ action: "decline" }));
  expect((await mcp.tools.call("close_ticket", { id: "T-1" })).json()).toEqual({ closed: false });
});

test("the question names the ticket", async ({ mcp }) => {
  const questions: string[] = [];
  mcp.onElicitation((request) => {
    questions.push(request.message);
    return { action: "cancel" };
  });
  await mcp.tools.call("close_ticket", { id: "T-7" });
  expect(questions).toEqual(["Close ticket T-7?"]);
});
```

<a id="checking-notifications"></a>

### Checking notifications

The collectors hold log messages and progress updates. Start collecting progress before the call; the notifications are available when it returns:

```ts bulk-close.tool.ts
import { Tool, ToolContext, z } from "@frontmcp/sdk";

@Tool({ name: "bulk_close", description: "Close several tickets", inputSchema: { ids: z.array(z.string()) } })
export class BulkClose extends ToolContext {
  async execute({ ids }: { ids: string[] }) {
    await this.notify(`Closing ${ids.length} tickets`);
    for (const [i, id] of ids.entries()) await this.progress(i + 1, ids.length, `Closed ${id}`);
    return { closed: ids };
  }
}
```

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

test("logs once and reports progress per ticket", async ({ mcp }) => {
  // Ask for progress; the client already requests logs.
  const progress = mcp.notifications.collectProgress();

  await mcp.tools.call("bulk_close", { ids: ["T-1", "T-2"] });

  expect(progress.all.map((p) => p.progress)).toEqual([1, 2]);

  const received = mcp.notifications.collect();
  expect(received.has("notifications/message")).toBe(true);
  expect(received.received.map((n) => n.method)).toEqual([
    "notifications/message",
    "notifications/progress",
    "notifications/progress",
  ]);
});
```

The client requests logs automatically: with `logging/setLevel` on older revisions and per-request metadata on 2026-07-28. Set `mcpLogLevel: false` to disable that behavior.

<a id="sending-raw-requests"></a>

### Sending raw requests

`mcp.raw.request()` sends any JSON-RPC request and returns the whole response, which is how you test protocol errors.

```ts ping.tool.ts
import { Tool, ToolContext } from "@frontmcp/sdk";

@Tool({ name: "ping", description: "Reply with pong", inputSchema: {} })
export class Ping extends ToolContext {
  async execute() {
    return { reply: "pong" };
  }
}
```

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

test("tools/list answers with the tools", async ({ mcp }) => {
  const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} });
  expect(response).toBeValidJsonRpc();
  expect(response.result.tools.map((t: { name: string }) => t.name)).toEqual(["ping"]);
});

test("an unknown method is a -32601 error", async ({ mcp }) => {
  const response = await mcp.raw.request({ jsonrpc: "2.0", id: 2, method: "tickets/list", params: {} });
  expect(response).toHaveErrorCode(-32601);
});
```

<a id="listing-a-server-with-many-tools"></a>

### Listing a server with many tools

Past 40 tools, a server answers `tools/list` a page at a time, with a `nextCursor` for the next one ([`pagination`](https://frontmcp.dev/reference/sdk/frontmcp#paging-long-tool-lists)). `mcp.tools.list()` follows the cursors and returns every tool. To look at the pages themselves, ask for each one with `mcp.raw.request()`. Here a page holds two of the server's five tools:

```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 active
import { test, expect } from "@frontmcp/testing";

test("tools/list comes in pages, and following the cursor finds every tool", async ({ mcp }) => {
  const names: string[] = [];
  const pageSizes: number[] = [];
  let cursor: string | undefined;

  do {
    const response = await mcp.raw.request({ jsonrpc: "2.0", id: 1, method: "tools/list", params: cursor ? { cursor } : {} });
    pageSizes.push(response.result.tools.length);
    names.push(...response.result.tools.map((tool: { name: string }) => tool.name));
    cursor = response.result.nextCursor;
  } while (cursor);

  expect(pageSizes).toEqual([2, 2, 1]);
  expect(names).toHaveLength(5);
  expect(names).toContain("search_tickets");
});
```

The loop stops when a page has no `nextCursor`. `await mcp.tools.list()` alone returns all five, and `toContainTool("search_tickets")` passes on it.

<a id="testing-events"></a>

### Testing events

A test subscribes with `client.events`, makes the server publish, and reads the occurrence. Webhook delivery needs a server whose auth signs callers in and a callback the server can reach, so this file runs the server in the test's process with a static key, as [the in-process setup](https://frontmcp.dev/reference/testing/interceptors#running-the-server-in-the-test-process) does, and gives it a [`WebhookReceiver`](https://frontmcp.dev/reference/testing#webhookreceiver):

```ts e2e/events.e2e.spec.ts
import { createServer, type Server } from "node:http";
import { FrontMcpInstance, LogLevel } from "@frontmcp/sdk";
import { test, expect, WebhookReceiver } from "@frontmcp/testing";
import { HelpDeskApp } from "../src/help-desk.app";

let listener: Server;
const receiver = new WebhookReceiver();

test.use({ baseUrl: "http://localhost:50925", protocolVersion: "2026-07-28" });

test.beforeAll(async () => {
  const handler = await FrontMcpInstance.createHandler({
    info: { name: "help-desk", version: "1.0.0" },
    apps: [HelpDeskApp],
    auth: { mode: "static", tokens: ["desk-key-1"] }, // webhook delivery needs a signed-in caller
    events: { webhook: { unsafeAllowLocalCallbacks: true, delivery: { backoffMs: 100 } } }, // the receiver is on 127.0.0.1
    logging: { level: LogLevel.Warn },
  });
  listener = createServer(handler as Parameters<typeof createServer>[1]).listen(50925);
  await receiver.start();
});

test.afterAll(async () => {
  await receiver.stop();
  await new Promise<void>((resolve) => {
    listener.closeAllConnections();
    listener.close(() => resolve());
  });
});

test.afterEach(() => receiver.clear());

test("a subscription over the test client's connection", async ({ server }) => {
  const client = await server.createClient({ token: "desk-key-1" });
  expect(await client.events.list()).toMatchObject([{ name: "ticket.closed", delivery: ["poll", "push", "webhook"] }]);

  const subscription = await client.events.subscribe("ticket.closed");
  expect(subscription.mode).toBe("push");

  await client.tools.call("close_ticket", { id: "T-1" });
  for await (const occurrence of subscription) {
    expect(occurrence).toMatchObject({ name: "ticket.closed", data: { id: "T-1" } });
    break;
  }
});

test("a signed webhook delivery, retried after a failure", async ({ server }) => {
  const client = await server
    .createClientBuilder()
    .withToken("desk-key-1")
    .withEvents({ webhook: { url: receiver.url, receiver: receiver.eventReceiver } })
    .buildAndConnect();
  try {
    const subscription = await client.events.subscribe("ticket.closed");
    expect(subscription.mode).toBe("webhook");
    expect(receiver.verifications()).toHaveLength(1);

    receiver.failNext(1, 503);
    await client.tools.call("close_ticket", { id: "T-2" });

    const [failed, retried] = await receiver.waitForDeliveries(2);
    expect(failed).toMatchObject({ kind: "event", answeredStatus: 503, signatureCheck: "valid" });
    expect(retried).toMatchObject({ answeredStatus: 200, webhookId: failed.webhookId, json: { name: "ticket.closed", data: { id: "T-2" } } });

    for await (const occurrence of subscription) {
      expect(occurrence.data).toEqual({ id: "T-2" });
      break;
    }
  } finally {
    await client.disconnect();
  }
});
```

The first client has no webhook configured, so it holds a stream. The second one's builder names the receiver, so `subscribe()` chooses webhook: the server verifies the callback once, the first delivery is answered `503`, and the retry carries the same `webhook-id` and is delivered. Leaving the `for await` loop ends a subscription, and the library disconnects the clients it made. The `mcp` fixture isn't used here, because a static-key server refuses its anonymous connection, with [the fixture's warning](https://frontmcp.dev/reference/testing/fixtures#mcp).

This file ran under Jest with the `@frontmcp/testing` preset, with the app in `src/help-desk.app.ts` declaring `ticket.closed` and a `close_ticket` tool that publishes it. The Playground can't run it: it has no `server` fixture, no `WebhookReceiver` and no `mcp.events`.

<a id="grouping-and-skipping-tests"></a>

### Grouping and skipping tests

`test.describe` groups tests under a name, and `test.skip` keeps a test in the file without running it. Skipped tests show as skipped in the Tests tab.

```ts search.tool.ts
import { Tool, ToolContext, z } from "@frontmcp/sdk";

@Tool({ name: "search_tickets", description: "Search tickets by title", inputSchema: { query: z.string() } })
export class SearchTickets extends ToolContext {
  async execute({ query }: { query: string }) {
    const titles = ["Cannot log in", "Login link expired"];
    return { titles: titles.filter((t) => t.toLowerCase().includes(query.toLowerCase())) };
  }
}
```

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

test.describe("search_tickets", () => {
  test("matches any part of the title", async ({ mcp }) => {
    const result = await mcp.tools.call("search_tickets", { query: "link" });
    expect(result.json()).toEqual({ titles: ["Login link expired"] });
  });

  test("ignores case", async ({ mcp }) => {
    const result = await mcp.tools.call("search_tickets", { query: "LOG" });
    expect(result.json().titles).toHaveLength(2);
  });

  test.skip("filters by customer", async ({ mcp }) => {
    // Not built yet.
  });
});
```

<a id="running-tests-with-frontmcp-test"></a>

### Running tests with `frontmcp test`

In a project, install the package, then run `frontmcp test` ([the command](https://frontmcp.dev/reference/cli#frontmcp-test) lists its options and the ES modules it transpiles by default). It runs your spec files with Jest, using a configuration it generates: `src/**/*.spec.ts`, `__tests__/**/*.spec.ts` and `e2e/**/*.e2e.spec.ts` (and their `.tsx` versions). That configuration compiles with `@swc/jest`, which `@frontmcp/testing` installs, and the library starts your server with `tsx`, so a project needs Jest and `tsx` besides the package. `frontmcp create` installs them all, with Jest 30; Jest 29 works too. A `jest.config.*` file in the project root replaces the generated configuration: `preset: "@frontmcp/testing"` gives it the same settings. The generated one transpiles `jose`, `@noble/hashes` and `@noble/ciphers`, the ES-only packages the SDK and CodeCall load, so a test file can import an app that uses CodeCall with nothing else set. A test that starts FrontMCP in its own process, like [a server in the test process](https://frontmcp.dev/reference/testing/interceptors#running-the-server-in-the-test-process), needs nothing more either.

```bash
npm install -D @frontmcp/testing jest tsx
npx frontmcp test
```

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

test.use({ server: "./src/main.ts" });

test("search_tickets is listed", async ({ mcp }) => {
  expect(await mcp.tools.list()).toContainTool("search_tickets");
});
```

| Option | Description |
| --- | --- |
| `-i`, `--runInBand` | Run test files one at a time. Recommended for E2E tests, which each start a server. |
| `-w`, `--watch` | Re-run tests when files change. |
| `-v`, `--verbose` | Show every test's result. |
| `-t`, `--timeout <ms>` | The timeout for each test. Default `60000`. |
| `-c`, `--coverage` | Collect coverage. |
| `--no-env` | Don't load `.env` and `.env.local`, which `frontmcp test` loads by default. |

<a id="evaluating-model-tool-use"></a>

### Evaluating model tool use

Use [`frontmcp eval`](https://frontmcp.dev/reference/cli#frontmcp-eval-file) to check which tools a model chooses and what arguments it sends. Each YAML or JSON case sends a `prompt` and checks `expect`, a single expectation or a nonempty list. Each expectation needs a `tool` and can specify `args` or `resultContains`. Every expectation must match a call in the run. `resultContains` matches case-insensitively against the response text and serialized structured content.

An argument object matches the keys you specify. Arrays match in order and must have the same length. Use `{ $contains: "text" }` for a case-insensitive substring in a string argument, or `{ $regex: "pattern" }` for a regular expression.

| Suite field | Type | Default | Description |
| --- | --- | --- | --- |
| `cases` | array of `{ name, prompt, expect }` | required | At least one case. |
| `provider`, `model` | `"openai" \| "anthropic"`, string | none | Name the provider and model here or on the command line. |
| `system` | string | none | System message for every run. |
| `runs` | positive integer | `1` | Runs per case. |
| `maxSteps` | positive integer | `5` | Maximum model turns per run. |
| `timeoutMs` | positive integer | `60000` | Per-run timeout. |
| `minPassRate` | number from `0` to `1` | `1` | Minimum overall pass rate. |

For a calculator server with an `add` tool that returns `{ sum }`, this case checks the arguments and looks for the sum in the tool response.

```yaml calculator.eval.yaml
provider: openai
model: gpt-4.1
cases:
  - name: Add two numbers
    prompt: Use the add tool to add 2 and 3.
    expect:
      tool: add
      args: { a: 2, b: 3 }
      resultContains: '"sum":5'
```

Run `npx frontmcp eval calculator.eval.yaml` with the provider key in the environment. A match is based on the calls and results. A result can match even when the tool returns an error, so expect text specific to the intended outcome when it matters.

<a id="running-unit-tests-in-a-commonjs-project"></a>

### Running unit tests in a CommonJS project

Use the unit preset for tests that import server code without starting an E2E server:

```js jest.config.cjs
module.exports = {
  preset: "@frontmcp/testing/jest-preset-unit",
};
```

The preset compiles TypeScript, TSX and the SDK's ESM-only dependencies (`jose`, `@noble/hashes`, `@noble/ciphers`) with `@swc/jest`. It runs `*.spec.ts` and `*.spec.tsx`, excluding `.e2e.spec`, `.perf.spec` and `.pw.spec`. It keeps Jest's default timeout and registers no setup file. The existing `@frontmcp/testing` preset keeps the E2E settings used by `frontmcp test`.

To register the MCP matchers with the unit preset, add `setupFilesAfterEnv: ["@frontmcp/testing/setup"]` to your configuration.

To keep `ts-jest` for TypeScript, override only its extension pattern. The preset still transforms the dependencies' JavaScript:

```js jest.config.cjs
module.exports = {
  preset: "@frontmcp/testing/jest-preset-unit",
  transform: { "^.+\\.tsx?$": "ts-jest" },
};
```

> **Note**
>
> A Jest configuration runs in your project's Node process. The Playground uses its own runner, so it can't run a Jest preset.

---

<a id="troubleshooting"></a>

## Troubleshooting

<a id="testuse-requires-either-server-entry-file-path-or-baseurl-for-external-server-option"></a>

### "test.use() requires either "server" (entry file path) or "baseUrl" (for external server) option"

The file never called `test.use()`, or called it without `server` or `baseUrl`, so the library doesn't know what to test. Add `test.use({ server: "./src/main.ts" })` at the top of the file. `server` is a path, not the server class.

<a id="failed-to-start-test-server"></a>

### "Failed to start test server."

The message lists the entry file and command, and the reason after `Error:`. "Server did not become ready within 30000ms" means the server never answered on its port: run the command yourself to see why, check that it reads the port from `PORT`, or raise `startupTimeout`.

<a id="frontmcp-test-needs-swcjest-which-comes-with-frontmcptesting"></a>

### "frontmcp test needs @swc/jest, which comes with @frontmcp/testing."

`frontmcp test` found neither `@frontmcp/testing` nor `@swc/jest` in the project. Install the package and Jest: `npm install -D @frontmcp/testing jest`. Install `tsx` too, or `npx` downloads it each time a test starts the server.

<a id="module-swcjest-in-the-transform-option-was-not-found"></a>

### "Module @swc/jest in the transform option was not found"

A Jest configuration names `@swc/jest`, and Jest can't find it from the project's root. With a `jest.config.*` of your own, use `preset: "@frontmcp/testing"`, which finds the `@swc/jest` that `@frontmcp/testing` installs, or install `@swc/jest`, `@swc/core` and `@swc/helpers` yourself.

<a id="syntaxerror-unexpected-token-export-from-josedistwebapiindexjs"></a>

### `SyntaxError: Unexpected token 'export'` from `jose/dist/webapi/index.js`

A CommonJS Jest project loaded an ESM-only SDK dependency without transforming its JavaScript. Use [`@frontmcp/testing/jest-preset-unit`](https://frontmcp.dev/reference/testing#running-unit-tests-in-a-commonjs-project), available in 1.10.16. If keeping `ts-jest`, match only `.ts` and `.tsx` with your override so the preset's JavaScript transform stays active.

<a id="no-text-content-to-parse-as-json"></a>

### "No text content to parse as JSON"

`json()` found no text block. The call may have failed with a JSON-RPC error (check `result.error`), or the tool returned only images or resources.

<a id="tobeerror-32602-fails-with-expected-error-code--32602-but-got-undefined"></a>

### `toBeError(-32602)` fails with "Expected error code -32602, but got undefined"

The tool failed with a tool error, which arrives as a result with `isError: true` and no JSON-RPC code. Pass its FrontMCP code as a string: with a string, `toBeError` compares `result.raw._meta?.code`.

```ts
// 🚩 Tool errors have no JSON-RPC code
expect(result).toBeError(-32602);

// ✅ Check that it failed, and why
expect(result).toBeError("INVALID_INPUT");
```

<a id="a-notification-test-passes-in-the-playground-but-collect-or-collectprogress-is-empty-under-frontmcp-test"></a>

### A notification test passes in the Playground but `collect()` or `collectProgress()` is empty under `frontmcp test`

Call `collectProgress()` before the tool call, and check that `mcpLogLevel` is not `false` for logs. The server must send the notifications too. See [Checking notifications](https://frontmcp.dev/reference/testing#checking-notifications).

<a id="a-test-passes-alone-but-fails-with-the-others"></a>

### A test passes alone but fails with the others

Tests in a file share one server, so an earlier test can leave data behind, like a closed ticket. Make each test set up what it needs, or check the change it made instead of the absolute state.

<a id="an-elicitation-test-gets-decline-or-fails-with-the-tool-asked-the-user-for-input"></a>

### An elicitation test gets `decline`, or fails with "The tool asked the user for input"

No handler was registered when the tool asked. Call `mcp.onElicitation()` before `mcp.tools.call()`. `frontmcp test`'s client answers `decline` by itself; the Playground fails the test and names the question.

<a id="expected-an-array-of-tools-but-received-object"></a>

### "Expected an array of tools, but received object"

`expect()` got a promise. Put `await` before `mcp.tools.list()`.

<a id="failed-to-list-tools-toolslist-returned-the-cursor--twice"></a>

### `Failed to list tools: tools/list returned the cursor "…" twice`

The server sent a `nextCursor` it had already sent, and the helper stopped instead of looping. A server that never stops paging ends with `tools/list did not finish within 1000 pages`. Check what the server's `tools/list` returns with `mcp.raw.request()`.

<a id="frontmcptestingplaywright-is-not-implemented"></a>

### `@frontmcp/testing/playwright is not implemented`

The `@frontmcp/testing/playwright` subpath is a placeholder: importing it works, but calling `test` or `expect`, or reading an integration member such as `test.describe`, throws:

```text
@frontmcp/testing/playwright is not implemented. For browser tests, use `test` and `expect` from `@playwright/test` against a server started with `TestServer.start()` from `@frontmcp/testing`. For OAuth flows without a browser, use `MockOAuthServer` and `TestTokenFactory` from `@frontmcp/testing`.
```

Use those alternatives. [Auth testing](https://frontmcp.dev/reference/testing/auth) covers the OAuth helpers.

> **Note**
>
> The Playground cannot import `@playwright/test` or the Playwright subpath. Run browser tests in your own project against `TestServer.start()`.

<a id="header-mismatch-the-mcp-name-header-is-required-for-eventspoll"></a>

### `Header mismatch: the mcp-name header is required for events/poll`

A 2026-07-28 request that names an event has to repeat the name in the `Mcp-Name` header. `mcp.events` sends it. A request written by hand, with `mcp.raw.request()` or `fetch`, has to add it, and the Playground's test client can't: there, read events with `events/list`, or through a `connect()` client's [`events`](https://frontmcp.dev/reference/sdk/connect#events). JSON-RPC `-32020`, HTTP `400`.

<a id="event--is-offered-by-poll-push-and-this-client-can-use-push-poll"></a>

### `Event "…" is offered by poll, push, and this client can use push, poll`

`subscribe()` was asked for `delivery: "webhook"` on a client without a receiver, or on a server that performs no webhook mode, as one with `public` auth. Build the client with `server.createClientBuilder().withEvents({ webhook: { url: receiver.url, receiver: receiver.eventReceiver } })`, and give the server an auth mode that signs callers in.

<a id="eventssubscribe-failed--32602-invalid-deliveryurl-it-must-use-https"></a>

### `events/subscribe failed (-32602): Invalid delivery.url: it must use https`

The server refused the `WebhookReceiver`'s URL as a callback: it's `http`, on `127.0.0.1`. Set `events.webhook.unsafeAllowLocalCallbacks: true` on the server the tests start, and nowhere else. With it set, `The callback endpoint could not be verified (challenge_failed)` means the receiver didn't echo the server's challenge, which `echoChallenges(false)` causes on purpose.
