Agent skill

Build Simulation

by counterfact in counterfact/api-simulator

Build a fully simulated API from an OpenAPI spec using Counterfact.

MITAuto-check passedBackend & APIs

Install Build Simulation

skills CLI
$ npx skills add counterfact/api-simulator --skill build-simulation -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install counterfact/api-simulator build-simulation --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/counterfact/api-simulator.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/build-simulation .claude/skills/build-simulation && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
build-simulation
GitHub stars
170
Token cost
~2.9k tokens
SKILL.md length
792 words
Files
1
Skills in repo
12
Repo updated
First seen
Licence
MIT

At a glance

Build a fully simulated API from an OpenAPI spec using Counterfact.

  • Works in 6 steps: Generate the initial scaffold → Research the real API → Implement context classes → …
  • Tasks that involve OpenAPI specifications
  • SKILL.md covers Purpose, Step 1 — Generate the initial…, Step 2 — Research the real API and Step 3 — Implement context…, plus 5 more sections
  • Calls npx; reaches petstore3.swagger.io

What it does

Build Simulation is an agent skill from counterfact/api-simulator. Build a fully simulated API from an OpenAPI spec using Counterfact. Generate the initial scaffold, research the real API's behaviour, implement stateful context classes, write tests for those classes, and configure scenario scripts (including a startup scenario) so the mock server is immediately useful without manual setup.

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs, covering OpenAPI specifications and Test generation. It works with OpenAPI. The repository describes itself as: Turn an OpenAPI spec into a local API in one command. Build and test your frontend with custom responses, shared state, and simulated failures, without waiting for the backend. The licence is MIT.

When your agent uses it

  • Tasks that involve OpenAPI specifications
  • Tasks that involve Test generation

Example prompts

  • “/build-simulation”

Requirements

  • Node.js

Workflow steps

6 steps, taken from the step headings in SKILL.md.

  1. Generate the initial scaffold
  2. Research the real API
  3. Implement context classes
  4. Test the context classes
  5. Set up scenario scripts
  6. Add failure and edge-case scenarios

What it can do on your machine

Read from SKILL.md and the folder at commit ad1a2a3. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • npx

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • petstore3.swagger.io

    Also links to:

    • counterfact.dev
    • github.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Build Simulation loads about 2.9k tokens when it runs. Until then it costs about 86 tokens; SKILL.md has 792 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~86
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from counterfact/api-simulator at commit ad1a2a3, republished under its MIT licence (© counterfact). 792 words, ~2,943 tokens.

Download SKILL.mdSave it as .claude/skills/build-simulation/SKILL.md (or your agent's skills folder).
name
build-simulation
description
Build a fully simulated API from an OpenAPI spec using Counterfact. Generate the initial scaffold, research the real API's behaviour, implement stateful context classes, write tests for those classes, and configure scenario scripts (including a startup scenario) so the mock server is immediately useful without manual setup.
applyTo
**/*.{yaml,yml,json}, **/routes/**/*.{ts,js}, **/*context.{ts,js}, **/scenarios/**/*.{ts,js}

Build-Simulation Skill

Purpose

Guide an AI agent through the full workflow of turning a bare OpenAPI spec into a realistic, stateful API simulation using Counterfact. This skill covers every step: generation, research, context implementation, testing, and scenario setup.


Step 1 — Generate the initial scaffold

Run Counterfact against the spec to produce a working server immediately:

sh
npx counterfact@latest <spec-url-or-path> <output-directory>

Example:

sh
npx counterfact@latest https://petstore3.swagger.io/api/v3/openapi.json api

This creates:

<output-directory>/
├── routes/          # one .ts file per API path — edit these
└── types/           # generated request/response types — never edit these

Every endpoint is live right away. By default each handler returns schema-valid random data (.random()). The simulation work that follows will replace those random responses with realistic, stateful behaviour.

Docs: Getting Started


Step 2 — Research the real API

Because the spec describes a well-known public API, look up official documentation before writing any simulation code. Understanding what the real API actually does is what separates a useful simulation from a pretty type stub.

Do at least the following:

  1. Read the official API docs — authentication flows, pagination styles, required vs. optional fields, status codes, error shapes, and any notable business rules (e.g. "a pet cannot be ordered if its status is sold").
  2. Check for public examples and SDKs — official SDKs often clarify which fields are commonly populated and how resources relate to each other.
  3. Note realistic data shapes — names, IDs, statuses, and dates that appear in the real API's example responses will make the simulation convincing.

Use this research to inform what methods the context classes should expose, what validation the context should perform, and what data the startup scenario should seed.


Step 3 — Implement context classes

Handlers should be thin. All stateful logic — lookups, mutations, derived data, invariants, error conditions — belongs in a _.context.ts file. Handlers read from context and return responses; they contain no business logic of their own.

Single-domain API

Place one _.context.ts at the root of the routes tree:

ts
// api/routes/_.context.ts
import type { Pet } from "../types/components/pet.types.js";

export class Context {
  private pets = new Map<number, Pet>();
  private nextId = 1;

  add(data: Omit<Pet, "id">): Pet {
    const pet = { ...data, id: this.nextId++ };
    this.pets.set(pet.id, pet);
    return pet;
  }

  get(id: number): Pet | undefined {
    return this.pets.get(id);
  }

  list(status?: Pet["status"]): Pet[] {
    const all = [...this.pets.values()];
    return status ? all.filter((p) => p.status === status) : all;
  }

  remove(id: number): boolean {
    return this.pets.delete(id);
  }
}

Then wire the context into each handler:

ts
// api/routes/pet.ts
export const GET: HTTP_GET = ($) =>
  $.response[200].json($.context.list($.query.status));

export const POST: HTTP_POST = ($) =>
  $.response[200].json($.context.add($.body));
ts
// api/routes/pet/{petId}.ts
export const GET: HTTP_GET = ($) => {
  const pet = $.context.get($.path.petId);
  return pet
    ? $.response[200].json(pet)
    : $.response[404].text(`Pet ${$.path.petId} not found`);
};

export const DELETE: HTTP_DELETE = ($) => {
  $.context.remove($.path.petId);
  return $.response[200];
};
Multi-domain API

For APIs with several distinct domains (users, orders, payments, …), give each domain its own _.context.ts at its subtree boundary. Use $.loadContext(path) to reach across boundaries when one domain needs data from another:

ts
// api/routes/payments/{paymentId}.ts
import type { Context as UsersContext } from "../../users/_.context.js";

export const GET: HTTP_GET = ($) => {
  const payment = $.context.getById($.path.paymentId);
  if (!payment) return $.response[404].text("Payment not found");

  const usersCtx = $.loadContext("/users") as UsersContext;
  const user = usersCtx.getById(payment.userId);

  return $.response[200].json({ ...payment, user });
};

Keep each context class focused on a single responsibility. If a class is growing too large, split it along domain lines.

Docs:


Step 4 — Test the context classes

The context class accumulates real logic; bugs in it break every handler that depends on it. Write unit tests that exercise the class directly, with no server, no $ object, and no HTTP machinery.

ts
// test/context.test.ts
import { Context } from "../api/routes/_.context.js";

describe("Context", () => {
  let context: Context;

  beforeEach(() => {
    context = new Context();
  });

  it("assigns sequential ids", () => {
    const a = context.add({ name: "Fluffy", status: "available", photoUrls: [] });
    const b = context.add({ name: "Rex",    status: "available", photoUrls: [] });
    expect(a.id).toBe(1);
    expect(b.id).toBe(2);
  });

  it("returns undefined for an unknown id", () => {
    expect(context.get(99)).toBeUndefined();
  });

  it("filters by status", () => {
    context.add({ name: "Fluffy", status: "available", photoUrls: [] });
    context.add({ name: "Rex",    status: "sold",      photoUrls: [] });
    expect(context.list("sold")).toHaveLength(1);
  });

  it("removes a pet", () => {
    const pet = context.add({ name: "Fluffy", status: "available", photoUrls: [] });
    context.remove(pet.id);
    expect(context.get(pet.id)).toBeUndefined();
  });
});

Do not test handler files. Handlers are intentionally thin, freely editable, and contain no logic worth automating against. Only the context class needs tests.

Docs: Pattern: Test the Context, Not the Handlers


Step 5 — Set up scenario scripts

Scenario scripts are TypeScript files in the scenarios/ directory. Each file exports named functions that receive a $ argument giving access to live context and a route builder. Run them from the REPL with .scenario, or have one run automatically at startup.

Show full SKILL.md (305 more words)Show less
The startup scenario

Export a function named startup from scenarios/index.ts. Counterfact calls it automatically when the server initialises, right before the REPL prompt appears. Use it to seed realistic data so the server is immediately useful without any manual REPL commands.

ts
// api/scenarios/index.ts
import type { Scenario } from "../types/_.context.js";

export const startup: Scenario = ($) => {
  $.context.add({ name: "Fluffy", status: "available", photoUrls: [] });
  $.context.add({ name: "Rex",    status: "sold",      photoUrls: [] });
};

For large startup sets, delegate to helper functions in separate files so each file stays focused and the helpers can also be called from the REPL:

ts
// api/scenarios/index.ts
import type { Scenario } from "../types/_.context.js";
import { addPets }   from "./pets.js";
import { addOrders } from "./orders.js";

export const startup: Scenario = ($) => {
  addPets($, 20, "dog");
  addOrders($, 5);
};
ts
// api/scenarios/pets.ts
import type { Scenario$ } from "../types/_.context.js";

export function addPets($: Scenario$, count: number, species: string) {
  for (let i = 0; i < count; i++) {
    $.context.add({
      name: `${species} ${i + 1}`,
      status: "available",
      photoUrls: [],
    });
  }
}
Additional scenario scripts

Write named exports for other useful states — an empty store, a rate-limited service, a full inventory. Run them from the REPL whenever you need them:

ts
// api/scenarios/index.ts
export const soldOut: Scenario = ($) => {
  $.context.list().forEach((p) => {
    p.status = "sold";
  });
};
⬣> .scenario soldOut
Applied soldOut

Docs:


Step 6 — Add failure and edge-case scenarios

Encode failure conditions in the context and toggle them on demand. This lets consumers of the simulation test error-handling code without coordinating with the real API.

ts
// api/routes/_.context.ts
export class Context {
  isRateLimited = false;
  isDown = false;
  // … rest of context …
}
ts
// api/routes/pet/{petId}.ts
export const GET: HTTP_GET = ($) => {
  if ($.context.isDown) return $.response[500].text("Service unavailable");
  if ($.context.isRateLimited) return $.response[429].text("Too many requests");
  const pet = $.context.get($.path.petId);
  return pet ? $.response[200].json(pet) : $.response[404].text("Not found");
};

Toggle from the REPL or via a scenario:

⬣> context.isRateLimited = true
⬣> client.get("/pet/1")
{ status: 429, body: 'Too many requests' }

Docs: Pattern: Simulate Failures and Edge Cases


Quick-reference: key documentation


Checklist

Work through these steps in order:

  • Run npx counterfact@latest to generate the initial scaffold
  • Read the real API's documentation and note key business rules and data shapes
  • Implement a _.context.ts with typed methods for all CRUD operations
  • Update each handler to delegate to the context instead of calling .random()
  • Write unit tests for the context class (not the handlers)
  • Export a startup function from scenarios/index.ts that seeds realistic data
  • Add named scenario exports for useful non-default states (empty, error, edge cases)
  • Verify the server starts with realistic data by running it and checking the REPL

© counterfact, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in skills/build-simulation of counterfact/api-simulator.

Open the folder on GitHubat commit ad1a2a3

Compare with similar skills

Build Simulation next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Build Simulation compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Build Simulation this skillcounterfact/api-simulator170—~2.9kAutomated safety check: PassMIT
Afrexai API ArchitectLeoYeAI/openclaw-master-skills2.2k—~6.8kAutomated safety check: PassMIT
Codexqa Testdata Generatoropenqa-cn/codexqa152—~4.8kAutomated safety check: PassApache-2.0
ToolJet Marketplace Plugin BuilderToolJet/ToolJet41k—~2.1kAutomated safety check: PassAGPL-3.0
Step Partsearthtojake/text-to-cad18k1 repos~1.5kAutomated safety check: PassMIT
API DesignerJeffallan/claude-skills12k2 repos~2kAutomated safety check: PassMIT

Similar skills

  • Afrexai API Architect

    LeoYeAI/openclaw-master-skills

    Design, build, test, document, and secure production-grade APIs.

    2.2k GitHub stars~6.8k tokensUpdated 2 mo ago
    Backend & APIsAuto-check passed
  • Constructs test data against real backends and writes it back into test cases as executable preconditions.

    152 GitHub stars~4.8k tokensUpdated 5 days ago
    Testing & QAAuto-check passed
  • Turns an API description, such as an OpenAPI file or a Postman collection, into a connector plugin for ToolJet's marketplace and checks it with the repo's validator.

    41k GitHub stars~2.1k tokensUpdated today
    Backend & APIsAuto-check passed
  • Step Parts

    earthtojake/text-to-cad

    Find, evaluate, and download common purchasable CAD parts from step.parts, including named off-the-shelf actuators, servos, motors, electronics boards, connectors, screws, bolts, nuts, washers…

    18k GitHub starsUsed in 1 repo~1.5k tokens
    Backend & APIsAuto-check passed
  • API Designer

    Jeffallan/claude-skills

    Designs REST and GraphQL APIs from resource modeling to an OpenAPI 3.1 contract, with versioning, pagination and RFC 7807 error handling.

    12k GitHub starsUsed in 2 repos~2k tokens
    Backend & APIsAuto-check passed
  • OpenAPI to MCP Server

    mcp-use/mcp-use

    Turns an OpenAPI or Swagger spec into an MCP server with the mcp-use TypeScript SDK, mapping each operation to a tool, wiring auth, testing and deploying.

    11k GitHub stars~5.2k tokensUpdated today
    Backend & APIsAuto-check passed

More from counterfact/api-simulator

All 12 skills in this repo
  • Counterfact PR Creation

    counterfact/api-simulator

    Create Counterfact pull requests with the required agent-authored acceptance and repository-learning notes; do not use to review another PR.

    170 GitHub stars~918 tokensUpdated today
    Auto-check passed
  • Counterfact Repl

    counterfact/api-simulator

    Interact with Counterfact mock API server programmatically. An agent skill from counterfact/api-simulator.

    170 GitHub stars~3.2k tokensUpdated today
    Auto-check passed
  • Counterfact Maintenance

    counterfact/api-simulator

    Keep contributor changes aligned with repository test patterns, diagnostics, black-box test boundaries, release/versioning workflow, documentation requirements, and compatibility.

    170 GitHub stars~3.1k tokensUpdated today
    Auto-check passed
  • Counterfact Repo Basics

    counterfact/api-simulator

    Provide Counterfact repository orientation, high-level architecture, and the canonical command reference for install/build/test/lint workflows.

    170 GitHub stars~868 tokensUpdated today
    Auto-check passed
  • Route

    counterfact/api-simulator

    Edit Counterfact route files to add endpoint behavior while keeping handlers thin and delegating business logic to context classes.

    170 GitHub stars~341 tokensUpdated today
    Auto-check passed
  • Scenario

    counterfact/api-simulator

    Create and update Counterfact scenario modules that seed or mutate context state through reusable scenario functions.

    170 GitHub stars~356 tokensUpdated today
    Auto-check passed

Works with

Categories

Questions about Build Simulation

What does Build Simulation do?

Build a fully simulated API from an OpenAPI spec using Counterfact. Build Simulation is an agent skill from counterfact/api-simulator. Build a fully simulated API from an OpenAPI spec using Counterfact.

When should I use Build Simulation?

Build Simulation fits situations like: tasks that involve OpenAPI specifications; tasks that involve Test generation.

How do I install Build Simulation in Claude Code?

Run `npx skills add counterfact/api-simulator --skill build-simulation -a claude-code`. Or copy the skill folder (skills/build-simulation in counterfact/api-simulator) into .claude/skills/build-simulation in your project. Claude Code loads it when a task matches its description.

How do I install Build Simulation in Codex?

Run `npx skills add counterfact/api-simulator --skill build-simulation -a codex`. Or copy the skill folder (skills/build-simulation in counterfact/api-simulator) into .agents/skills/build-simulation in your project. Codex loads it when a task matches its description.

Can I use Build Simulation in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add counterfact/api-simulator --skill build-simulation -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/build-simulation, .gemini/skills/build-simulation, .github/skills/build-simulation and .opencode/skills/build-simulation in your project.

What does Build Simulation need to run?

Going by SKILL.md and its folder, Build Simulation needs the command-line tools its instructions call (npx). Our summary lists: Node.js.

Does Build Simulation access the network?

SKILL.md names 3 domains. In commands or code: petstore3.swagger.io; the agent is likely to contact it when it follows the instructions. As links in the text: counterfact.dev and github.com. This is read from the text; nothing was executed.

Is Build Simulation safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Build Simulation use?

Build Simulation is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Build Simulation use?

About 2.9k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Build Simulation?

Skills that share tags, products or a category with Build Simulation: Afrexai API Architect (LeoYeAI/openclaw-master-skills, 2.2k stars), Codexqa Testdata Generator (openqa-cn/codexqa, 152 stars), ToolJet Marketplace Plugin Builder (ToolJet/ToolJet, 41k stars) and Step Parts (earthtojake/text-to-cad, 18k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Build Simulation?

counterfact (a GitHub organization) maintains it in counterfact/api-simulator, which has 170 GitHub stars. The repository holds 12 skills in this directory. The repository was last updated on October 8, 2026.

Source: counterfact/api-simulator on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.