AgentStack
Browse Sign in
Browse Why AgentStack Sell Docs
Sign in
MCP verified MIT Self-run

Mcp Vitest

mcp-nixrajput-mcp-vitest · by nixrajput

Vitest-native testing for Model Context Protocol (MCP) servers - matchers, snapshots, interaction doubles, and real external servers, on both SDK majors.

No reviews yet
0 installs
24 views
0.0% view→install

Install

$ agentstack add mcp-nixrajput-mcp-vitest

✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution Used
  • Environment & secrets No
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

View the full security report →

Verified badge

Passed review? Show it. Paste this badge into your README, it links to the public security report.

AgentStack Verified badge Links to your public security report.
[![AgentStack Verified](https://agentstack.voostack.com/badges/verified.svg)](https://agentstack.voostack.com/security/report/mcp-nixrajput-mcp-vitest)

Reliability & compatibility

Security review passed
0 installs to date
no reviews yet
1mo ago

Declared compatibility

Claude CodeClaude DesktopCursorWindsurf

Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.

Preview Execution monitoring

We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.

How agent discovery & health will work →
Are you the author of Mcp Vitest? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

mcp-vitest

Test your MCP server the way you test everything else.

[][ci] [][npm] [][repo] [][contributors] [][license] [][repo] [][issues] [][pulls]

In-process · both SDK majors · both protocol revisions · seven typed matchers · one runtime dependency A fresh server plus a full initialize handshake, per test, costs 0.24ms on SDK v1 and 0.47ms on v2 - means across 8,270 and 4,284 samples at ±2.3% and ±3.6%, reproducible with npm run bench. There is no subprocess and no socket to pay for. Also checkable: 160 tests across the two SDK lanes, which connect over different transports and so are covered separately rather than assumed equivalent; the v2 lane pins the 2026-07-28 revision, which is what makes the two lanes cover different protocol eras instead of the same one twice; and every build is verified with publint and @arethetypeswrong/cli. See the runs.

[Documentation][docs] · [Getting started][docs-start] · [API reference][docs-api] · [Lifecycles][docs-lifecycles]

AI agents / LLMs: the documentation is machine-readable at llms.txt, or as one blob at llms-full.txt.


Contents

  • [mcp-vitest](#mcp-vitest)
  • [Contents](#contents)
  • [Before and after](#before-and-after)
  • [Overview](#overview)
  • [Features](#features)
  • [Getting started](#getting-started)
  • [Prerequisites](#prerequisites)
  • [Install](#install)
  • [Quickstart](#quickstart)
  • [Works with both SDK majors](#works-with-both-sdk-majors)
  • [Testing OAuth-protected servers](#testing-oauth-protected-servers)
  • [API](#api)
  • [Is this for you](#is-this-for-you)
  • [Compared to](#compared-to)
  • [FAQ](#faq)
  • [Contributing](#contributing)
  • [Contributors](#contributors)
  • [License](#license)
  • [Support the project](#support-the-project)
  • [Connect](#connect)

Before and after

Driving an MCP server from a test without a harness means wiring the SDK yourself. This is a trimmed version of what [src/connect/v1.ts](src/connect/v1.ts) does for you - a linked transport pair, a client with the right capabilities advertised before initialize, and a request handler per interaction type:

const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();

const client = new Client(
  { name: "my-test", version: "1.0.0" },
  { capabilities: { sampling: {}, elicitation: {}, roots: {} } },
);

client.setRequestHandler(CreateMessageRequestSchema, async (req) =>
  mySampling(req.params),
);
client.setRequestHandler(ElicitRequestSchema, async (req) =>
  myElicitation(req.params),
);
client.setRequestHandler(ListRootsRequestSchema, async () => ({
  roots: myRoots,
}));

await Promise.all([
  server.connect(serverTransport),
  client.connect(clientTransport),
]);

const { tools } = await client.listTools();
if (!tools.some((t) => t.name === "search")) throw new Error("no search tool");

And that is only the v1 path. A v2 server does not use InMemoryTransport at all - it connects over the SDK's in-process handler.fetch route - so supporting both means writing it twice and keeping them in step.

With the harness:

const test = createMcpTest(() => createServer());

test("search tool works", async ({ mcp }) => {
  await expect(mcp).toHaveTool("search");
});

mcpTest() detects which SDK your server came from and routes to the matching transport. Capabilities are advertised before initialize because a server decides what to request during it, which is a detail that is easy to get wrong by hand and impossible to notice until a double never fires.

Overview

Testing an MCP server usually means spawning a subprocess, picking a port, or hand-rolling JSON-RPC frames. By default mcp-vitest does none of that: your server runs in-process, driven by a real SDK Client over the SDK's own in-process transport, and you get a small harness plus typed matchers on top. When a server cannot be imported, the same harness drives it over stdio or a URL instead. The protocol is never reimplemented, so what your tests exercise is what a real client would.

   your test ──▶ mcp.callTool() ──▶ real SDK Client ──┬─▶ v1: InMemoryTransport pair
   expect(mcp) ─▶ seven matchers                      ├─▶ v2: handler.fetch route
                                                      └─▶ external: stdio or URL

Features

  • In-process by default - no ports, no spawn, no teardown races. Both SDK majors, detected automatically.
  • Typed matchers - seven of them, with TypeScript augmentation and did-you-mean suggestions on typos.
  • A small harness - tools, resources, and prompts with pagination followed for you, plus the raw SDK client as an escape hatch.
  • Interaction doubles - answer a server's sampling, elicitation, and roots requests from your test.
  • External servers - spawn one over stdio or point at a running URL; everything above works unchanged.
  • OAuth test doubles - send a bearer token or headers with auth, and drive the other side of the handshake with a fake authorization server backed by a real RS256 keypair.
  • Lifecycle coverage - run the same tests against the 2025 and 2026-07-28 protocol revisions.
  • Regression safety - snapshot manifests normalized so key order and absent optionals never churn them.
  • Real call ergonomics - progress callbacks, AbortSignal cancellation, per-call timeouts, and a notification collector with waitFor.
  • One runtime dependency - @cfworker/json-schema (MIT, no transitive deps). Your MCP SDK is an optional peer, so you install only the major you use.

Getting started

Prerequisites

  • Node.js >=20
  • vitest >=3.2 in your project
  • An MCP server built on either SDK major - @modelcontextprotocol/sdk >=1.10, or @modelcontextprotocol/server + /client ^2.0. Both are optional peers, so you install only the one you use.
  • ESM only, with no CJS build

Install

npm i -D mcp-vitest vitest

Plus the SDK your server uses:

# SDK v1
npm i -D @modelcontextprotocol/sdk

# SDK v2
npm i -D @modelcontextprotocol/server @modelcontextprotocol/client

Quickstart

Register the matchers in your vitest config:

// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: { setupFiles: ["mcp-vitest/setup"] },
});

Then test your server:

import { expect } from "vitest";
import { createMcpTest } from "mcp-vitest";
import { createServer } from "./src/server.js";

const test = createMcpTest(() => createServer());

test("search tool works", async ({ mcp }) => {
  await expect(mcp).toHaveTool("search");
  const result = await mcp.callTool("search", { query: "foo" });
  expect(result).toHaveTextContent(/results/);
});

(Set globals: true in your vitest config if you would rather skip the expect import.)

Works with both SDK majors

  • v1 (@modelcontextprotocol/sdk) connects over the SDK's InMemoryTransport linked pair.
  • v2 (@modelcontextprotocol/server) connects over the SDK's in-process handler.fetch route.

You do not pick. mcpTest() detects which SDK your server came from and routes to the matching transport; mcp.kind reports what it found. The same tests, matchers, and fixture work either way - including against external servers, which report 'external'. Which protocol revision each lane speaks is covered under lifecycles.

Testing OAuth-protected servers

Pass auth: { token } or auth: { headers } to send credentials on every request, and reach for mcp-vitest/auth to test the other side of the handshake: a fake authorization server with a real RS256 keypair, plus assertions for the 401 challenge and PRM discovery a protected server has to get right. Details at [auth test doubles][docs-auth].

Pass fakeAuthServer({ audience }) when your server should refuse a token minted for a different resource - MCP's confused-deputy defence. Without it the verifier accepts any audience, reporting a URL-shaped one as AuthInfo.resource for a server that reads it, because requireBearerAuth checks only scopes and expiry. auth throws on a stdio or in-process server, which cannot send a credential at all.

API

The full reference lives at mcp-vitest.nixrajput.com/en/docs/api/mcp-test - mcpTest, the harness, all seven matchers, interaction doubles, notification collectors, snapshots, external servers, and the lifecycle matrix.

Migrating from an earlier version? See the migration notes.

Is this for you

Good fit if you…

  • maintain an MCP server and want tests that run in your existing vitest suite
  • need to assert on tools, resources, prompts and results without hand-rolling JSON-RPC
  • have to answer a server's sampling, elicitation or roots requests from a test
  • support both SDK majors, or are migrating between them
  • care which protocol revision your server actually negotiates

Skip it if you…

  • want an interactive debugger rather than automated tests. MCP Inspector is the right tool for poking at a server by hand.
  • are not on vitest. The matchers and fixture are vitest-native; nothing here ports to jest without rewriting.
  • only need to check that a process starts. A shell script is cheaper.
  • are on SDK v1 below 1.10, or need a CJS build. This is ESM only.

Compared to

| | SDK majors | Protocol revisions | Interaction doubles | Snapshots | Schema validation | | ------------------------------------------------------------------ | --------------------------------------------- | ------------------------- | ---------------------------- | -------------------- | --------------------- | | mcp-vitest | v1 and v2, auto-detected | 2025-11-25 and 2026-07-28 | sampling, elicitation, roots | Normalized manifests | toMatchOutputSchema | | vitest-mcp | v1 only, per its own peer range `>=1.10.0

License

Licensed under the MIT license - see [LICENSE](LICENSE).

Support the project

mcp-vitest is MIT licensed and free to use, always. If it earns a place in your test suite, sponsorship is welcome.

Connect

Nikhil Rajput

[ci]: https://github.com/nixrajput/mcp-vitest/actions/workflows/ci.yml [docs]: https://mcp-vitest.nixrajput.com [docs-start]: https://mcp-vitest.nixrajput.com/en/docs/getting-started [docs-api]: https://mcp-vitest.nixrajput.com/en/docs/api/mcp-test [docs-lifecycles]: https://mcp-vitest.nixrajput.com/en/docs/api/lifecycles [docs-external]: https://mcp-vitest.nixrajput.com/en/docs/api/external-servers [docs-auth]: https://mcp-vitest.nixrajput.com/en/docs/api/auth [npm]: https://www.npmjs.com/package/mcp-vitest [repo]: https://github.com/nixrajput/mcp-vitest [issues]: https://github.com/nixrajput/mcp-vitest/issues [pulls]: https://github.com/nixrajput/mcp-vitest/pulls [discussions]: https://github.com/nixrajput/mcp-vitest/discussions [contributors]: https://github.com/nixrajput/mcp-vitest/graphs/contributors [license]: https://github.com/nixrajput/mcp-vitest/blob/main/LICENSE

Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet, be the first.

Versions

  • v0.1.0 Imported from the upstream source.