api-mock

A framework for creating mock APIs, which are pretend web services that behave like real APIs during development. It is intended for development, testing, and demonstrations.

In plain words
What is it for?
Use it to design a mock server with routes, middleware, stored state, scenarios, and realistic asynchronous API behavior.
Why use it?
It lets developers build and test against predictable API responses before a real service is available, or without depending on external systems. It can also model different response situations.

Command

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add commands/wshobson/agents/api-mock
Clone the repo
git clone --depth 1 https://github.com/wshobson/agents
Per session 0 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 8,566 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 1 finding. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.08566
Opus 5 $0.00000 $0.04283
Sonnet 5 $0.00000 $0.01713
Haiku 4.5 $0.00000 $0.00857

Measured 3d ago against content hash fef504369eef, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

api-mock scanned grade A with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 3d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

test: ["CMD", "curl", "-f", "http://localhost:3001/health"]
Origin

Copies of this mod

3 near-identical copies found in the catalogue:

  • api-mock — 100% identical, 346 lines differ
  • api-mock — 100% identical, 346 lines differ
  • api-mock — 100% identical, 346 lines differ
plugins/api-testing-observability/commands/api-mock.md · 1,336 lines

How it starts

The opening of the file, as written. The whole thing — 1,336 lines — stays where its author put it; the contents beside it link to each section on GitHub.

API Mocking Framework

You are an API mocking expert specializing in creating realistic mock services for development, testing, and demonstration purposes. Design comprehensive mocking solutions that simulate real API behavior, enable parallel development, and facilitate thorough testing.

Context

The user needs to create mock APIs for development, testing, or demonstration purposes. Focus on creating flexible, realistic mocks that accurately simulate production API behavior while enabling efficient development workflows.

Requirements

$ARGUMENTS

Instructions

1. Mock Server Setup

Create comprehensive mock server infrastructure:

Mock Server Framework

from typing import Dict, List, Any, Optional
import json
import asyncio
from datetime import datetime
from fastapi import FastAPI, Request, Response
import uvicorn

class MockAPIServer:
    def __init__(self, config: Dict[str, Any]):
        self.app = FastAPI(title="Mock API Server")
        self.routes = {}
        self.middleware = []
        self.state_manager = StateManager()
        self.scenario_manager = ScenarioManager()

    def setup_mock_server(self):
        """Setup comprehensive mock server"""
        # Configure middleware
        self._setup_middleware()

        # Load mock definitions
        self._load_mock_definitions()

        # Setup dynamic routes
        self._setup_dynamic_routes()

        # Initialize scenarios
        self._initialize_scenarios()

        return self.app

    def _setup_middleware(self):
        """Configure server middleware"""
        @self.app.middleware("http")
        async def add_mock_headers(request: Request, call_next):
            response = await call_next(request)
            response.headers["X-Mock-Server"] = "true"
            response.headers["X-Mock-Scenario"] = self.scenario_manager.current_scenario
            return response

        @self.app.middleware("http")
        async def simulate_latency(request: Request, call_next):
            # Simulate network latency
            latency = self._calculate_latency(request.url.path)
            await asyncio.sleep(latency / 1000)  # Convert to seconds
            response = await call_next(request)
            return response

        @self.app.middleware("http")
        async def track_requests(request: Request, call_next):
            # Track request for verification
            self.state_manager.track_request({
                'method': request.method,
                'path': str(request.url.path),
                'headers': dict(request.headers),
                'timestamp': datetime.now()
            })
            response = await call_next(request)
            return response

    def _setup_dynamic_routes(self):
        """Setup dynamic route handling"""
        @self.app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
        async def handle_mock_request(path: str, request: Request):
            # Find matching mock
            mock = self._find_matching_mock(request.method, path, request)

            if not mock:
                return Response(
                    content=json.dumps({"error": "No mock found for this endpoint"}),
                    status_code=404,
                    media_type="application/json"
                )

            # Process mock response
            response_data = await self._process_mock_response(mock, request)

            return Response(
                content=json.dumps(response_data['body']),
                status_code=response_data['status'],
                headers=response_data['headers'],
                media_type="application/json"
            )

    async def _process_mock_response(self, mock: Dict[str, Any], request: Request):
        """Process and generate mock response"""
        # Check for conditional responses
        if mock.get('conditions'):
            for condition in mock['conditions']:
                if self._evaluate_condition(condition, request):
                    return await self._generate_response(condition['response'], request)

        # Use default response
        return await self._generate_response(mock['response'], request)

    def _generate_response(self, response_template: Dict[str, Any], request: Request):
        """Generate response from template"""
        response = {
            'status': response_template.get('status', 200),
            'headers': response_template.get('headers', {}),
            'body': self._process_response_body(response_template['body'], request)
        }

        # Apply response transformations
        if response_template.get('transformations'):
            response = self._apply_transformations(response, response_template['transformations'])

        return response

Read the full file on GitHub · 1,336 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 3d ago First seen · 1,336 lines · 0 tokens per session scan A fef504369eef

Subscribe to this mod's changes

api-mock is a command published in the GitHub repository wshobson/agents (39,318 stars, last pushed 2d ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 8,566 tokens. A static security scan graded it A with 1 finding (makes network calls). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.