Verified SOP & TutorialAudited Score 98/100

The Complete Production SOP: How to Deploy and Run Mock Service Worker (MSW) Network-Level API Mocking in Autonomous AI Agents

Step-by-step SOP to install and run Mock Service Worker (MSW 2.0) in Codex, Claude Code, and Cursor. Includes verified prompts, sandbox rules, and troubleshooting.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

Technical Overview & Architectural Context

Autonomous coding agents frequently make critical architectural mistakes when writing API integration tests. Without strict procedural guardrails, LLMs default to monkey-patching global `fetch` or overriding Axios prototypes using `vi.spyOn(global, 'fetch')` or `jest.mock()`. This violates network-level fidelity, fails to test real serialization/deserialization code paths, obscures request headers, and frequently introduces state leakage across parallel test runners. Furthermore, LLMs regularly hallucinate deprecated MSW 1.x syntax (such as `rest.get` and `res(ctx.json(...))`) inside modern MSW 2.0 codebases, causing catastrophic test runner crashes due to incompatible interceptor bindings. This creates breaking circular loops where the agent continuously attempts invalid polyfills instead of migrating to standard `http.get` and `HttpResponse.json()`. The `msw-mock-service-worker-api-tests` skill enforces strict MSW 2.0 patterns across test suites and development environments. It constrains the agent to initialize non-destructive interception via `setupServer` for Node.js/Vitest or `setupWorker` for browser runtimes, mandating clean lifecycle hooks (`server.listen({ onUnhandledRequest: 'error' })`, `server.resetHandlers()`, and `server.close()`) to guarantee deterministic, isolated unit and integration tests.

Prerequisites & Environment Requirements

Codex Desktop, Claude Code CLI, Cursor, or Windsurf installed with skill execution enabled
Node.js 20+ LTS or Bun runtime with package manager (pnpm, npm, or yarn)
MSW >= 2.0.0 installed in workspace devDependencies
Git 2.40+ with initialized workspace repository

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install msw-mock-service-worker-api-tests in cursor ide#claude code msw-mock-service-worker-api-tests rules#setup msw 2.0 handlers vitest codex agent#how to fix msw unhandled request agent execution error#deterministic fullstack agent SOP msw mocking#msw-mock-service-worker-api-tests sandbox permissions and security score#mock http request msw 2.0 cursor windsurf prompt

Step-by-Step Execution Playbook

1

Local Environment Setup & SKILL.md Mounting

Mount the skill manifest into your agent's configuration directory to register MSW 2.0 triggers and lifecycle rules.

Autonomous agents inspect workspace and user configuration roots to load capability boundaries. We mount the skill into `.agents/skills` or `.claude/skills` so the runtime monitors declared triggers (`setup msw 2.0 handlers`, `mock http request msw`, `msw in vitest`) and enforces workspace-scoped file mutations.

Terminal Command
mkdir -p ~/.agents/skills/msw-mock-service-worker-api-tests && curl -fsSL https://askills.dev/api/skills/msw-mock-service-worker-api-tests/raw -o ~/.agents/skills/msw-mock-service-worker-api-tests/SKILL.md
SKILL.md
---
name: "msw-mock-service-worker-api-tests"
description: "Mock REST and GraphQL APIs at the network level for tests, storybook, and development with MSW."
metadata:
  author: "Artem Zakharchenko"
  version: "1.0.0"
  runtime_compatibility:
    - "codex"
    - "claude-code"
    - "cursor"
    - "windsurf"
triggers:
  - "setup msw 2.0 handlers"
  - "mock http request msw"
  - "msw in vitest"
permissions:
  fs_read: true
  fs_write: "workspace"
  shell_exec: false
  net_access: false
---

# Mock Service Worker (MSW) Network-Level API Mocking

Implements Mock Service Worker (MSW 2.0): http and graphql handlers (http.get, http.post), HttpResponse.json, setting up setupServer for Node.js tests, setupWorker for browsers, and intercepting fetch requests seamlessly.

## Execution SOP & Rules
1. Define handlers in src/mocks/handlers.ts using `http.*` and `HttpResponse.json()`.
2. Configure Node server in src/mocks/node.ts via `setupServer(...handlers)`.
3. Hook server lifecycle in vitest.setup.ts: listen, resetHandlers after each test, close.
4. Fail fast on unhandled requests with `server.listen({ onUnhandledRequest: 'error' })`.
5. When simulating errors per test, use `server.use()` overrides, never mutate production endpoints.
Production Pro-Tip

Setting `shell_exec: false` and `net_access: false` prevents agents from downloading arbitrary mocking packages or running unreviewed install scripts behind proxy barriers.

Sandbox Gotcha

Do not mix MSW 1.x `rest.*` syntax inside modern repositories. If `msw` in `package.json` is ^2.0.0, any invocation of `rest` or `context` objects will trigger immediate type and runtime exceptions.

2

Environment Secrets & Dependency Validation

Verify package installation and configure the test setup entrypoint without leaking API tokens.

Ensure `msw` is installed as a development dependency. Configure your test runner (Vitest or Jest) to preload the MSW server lifecycle. For Vitest, update `vitest.config.ts` to reference `setupFiles: ['./src/mocks/setup.ts']`.

Terminal Command
pnpm add -D msw@latest
src/mocks/node.ts
import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);
Production Pro-Tip

Instruct the agent to read `package.json` first to confirm the installed MSW major version before generating mock fixtures.

Sandbox Gotcha

Ensure that `server.resetHandlers()` is called in `afterEach`, not `afterAll`. Otherwise, overrides injected with `server.use()` in one test will bleed into subsequent test cases.

3

Intent Matching & Trigger Invocation

Trigger the agent to scaffold handlers and test-lifecycle hooks using precise skill trigger strings.

Provide prompts that activate the skill's triggers: `setup msw 2.0 handlers` or `msw in vitest`. The runtime parser activates the execution boundary, preventing the agent from generating brittle `vi.fn()` fetch wrappers.

src/mocks/handlers.ts
import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('https://api.example.com/v1/users/:id', ({ params }) => {
    const { id } = params;
    return HttpResponse.json({
      id: String(id),
      name: 'Agent Validator',
      role: 'engineer'
    });
  }),
  http.post('https://api.example.com/v1/auth/login', async ({ request }) => {
    const payload = (await request.json()) as { username?: string };
    if (!payload.username) {
      return new HttpResponse(null, { status: 400 });
    }
    return HttpResponse.json({ token: 'mock-jwt-token-xyz' }, { status: 200 });
  })
];
Production Pro-Tip

Specify exact parameter constraints and return types in the prompt to ensure the agent defines schema-compliant responses with `HttpResponse.json<T>()`.

Sandbox Gotcha

Always specify absolute URLs or accurate base paths matching the runtime environment (Node vs browser) to avoid unhandled request errors during SSR or unit test execution.

4

Verification, Linting & Output Quality Gate

Execute the verification checklist to confirm zero unhandled network calls and test suite pass rates.

The agent must run typecheck and test execution passes to ensure MSW intercepted all network activity. If an unhandled request occurs, Vitest will fail immediately due to `{ onUnhandledRequest: 'error' }`.

Terminal Command
pnpm tsc --noEmit && pnpm vitest run
Production Pro-Tip

Use `git diff --stat` after agent execution to verify that no production networking clients (Axios instance, fetch client) were modified to accommodate test mocks.

Sandbox Gotcha

If tests run in an environment without Node 18+ global `fetch` or `Headers`, ensure undici or standard web polyfills are loaded before `server.listen()` is invoked.

Real-World Scenario: Scaffold MSW 2.0 Interception for an Authentication Client in Vitest

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“Set up msw 2.0 handlers for our auth client in Vitest. We need to mock a POST request to '/api/auth/token' returning a refresh token, and write an integration test that checks token refresh and asserts 401 error handling with server.use.”

Deterministic Agent Verification Pipeline:
Agent inspects package.json to verify MSW 2.x and Vitest dependencies.
Agent creates `src/mocks/handlers.ts` exporting default handlers using `http.post('/api/auth/token', ...) ` and `HttpResponse.json()`.
Agent creates `src/mocks/node.ts` initializing `setupServer(...handlers)`.
Agent updates `vitest.setup.ts` adding `beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))`, `afterEach(() => server.resetHandlers())`, and `afterAll(() => server.close())`.
Agent writes an integration test verifying normal authentication and overrides the endpoint via `server.use(http.post('/api/auth/token', () => new HttpResponse(null, { status: 401 })))` to test error recovery.

Runtime Troubleshooting & Failure Modes

Error: [MSW] Error: [setupServer] The "http.get" call signature is invalid. In MSW 2.0, response resolvers receive an object containing "request", "params", and "cookies".

Root Cause: The agent hallucinated legacy MSW 1.x response resolver arguments `(req, res, ctx)` instead of the MSW 2.0 object destructuring signature `({ request, params, cookies })`.

Resolution Command / Fix:
Replace legacy signature `(req, res, ctx) => res(ctx.json(data))` with MSW 2.0 standard: `({ request }) => HttpResponse.json(data)`.
Error: [MSW] Error: Cannot bypass request to "https://api.example.com/data": unhandled request.

Root Cause: The test runner executed a network fetch that lacked a corresponding handler in `handlers.ts` while `server.listen({ onUnhandledRequest: 'error' })` was active.

Resolution Command / Fix:
Add the missing handler: `http.get('https://api.example.com/data', () => HttpResponse.json({ status: 'ok' }))` or adjust URL pattern matching to support wildcard queries.

Frequently Asked Questions (Mock Service Worker (MSW) Network-Level API Mocking SOP)

Q:Can I use Mock Service Worker (MSW) Network-Level API Mocking across Codex, Claude Code, and Cursor simultaneously?

Yes. This skill adheres to the universal SKILL.md specification. All supported agents (Codex, Claude Code CLI, Cursor, and Windsurf) parse the triggers and execution rules identically within project workspaces.

Q:How does Mock Service Worker (MSW) Network-Level API Mocking prevent context window overflow during long agent sessions?

By providing strict SOP templates and targeted file boundaries (`src/mocks/handlers.ts`, `vitest.setup.ts`), the skill prevents the agent from engaging in open-ended trial-and-error generation or outputting entire mock server frameworks into the conversation context.

Q:Does this skill require escalated root or container permissions?

No. The skill is audited with a security score of 98/100, requires zero external shell execution permissions (`shell_exec: false`), and operates strictly within workspace filesystem boundaries.

Ready to equip your autonomous agent with Mock Service Worker (MSW) Network-Level API Mocking?

Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.

Get 1-Click Install Spec