Skip to content

CLI Reference

Complete reference for the mockd command-line interface.

These flags apply to all commands:

FlagDescription
-h, --helpShow help message
-v, --versionShow version information
--admin-urlAdmin API base URL (default: http://localhost:4290)
--workspaceWorkspace to scope operations to (overrides MOCKD_WORKSPACE env and context config)
--jsonOutput command results in JSON format

mockd leverages Cobra to generate autocomplete scripts for popular shells.

Generate the autocompletion script for the specified shell.

Terminal window
mockd completion [command]

Commands:

CommandDescription
bashGenerate the autocompletion script for bash
fishGenerate the autocompletion script for fish
powershellGenerate the autocompletion script for powershell
zshGenerate the autocompletion script for zsh

Examples:

Terminal window
# Load bash completion in the current shell
source <(mockd completion bash)
# Load zsh completion in the current shell
source <(mockd completion zsh)
# Configure bash completion permanently (Linux)
mockd completion bash > /etc/bash_completion.d/mockd

Start the mock server (default command).

Terminal window
mockd serve [flags]

Flags:

FlagShortDescriptionDefault
--port-pHTTP server port4280
--admin-port-aAdmin API port4290
--config-cPath to mock configuration file
--https-portHTTPS server port (0 = disabled)0
--read-timeoutRead timeout in seconds30
--write-timeoutWrite timeout in seconds30
--request-timeoutRequest timeout in seconds (sets both read and write timeout)0
--max-log-entriesMaximum request log entries1000
--max-connectionsMaximum concurrent HTTP connections (0 = unlimited)0
--auto-certAuto-generate TLS certificatetrue

CORS Flags:

FlagDescriptionDefault
--cors-originsComma-separated CORS allowed origins (e.g., '*' or 'https://app.example.com')

Rate Limiting Flags:

FlagDescriptionDefault
--rate-limitRate limit in requests per second (0 = disabled)0

Persistence Flags:

FlagDescriptionDefault
--no-persistDisable persistent storage (mocks are lost on restart)false

Storage Flags:

FlagDescriptionDefault
--data-dirData directory for persistent storage~/.local/share/mockd
--no-authDisable API key authentication on admin APIfalse

TLS Flags:

FlagDescription
--tls-certPath to TLS certificate file
--tls-keyPath to TLS private key file
--tls-autoAuto-generate self-signed certificate

mTLS Flags:

FlagDescription
--mtls-enabledEnable mTLS client certificate validation
--mtls-client-authClient auth mode (none, request, require, verify-if-given, require-and-verify)
--mtls-caPath to CA certificate for client validation
--mtls-allowed-cnsComma-separated list of allowed Common Names

Audit Flags:

FlagDescription
--audit-enabledEnable audit logging
--audit-filePath to audit log file
--audit-levelLog level (debug, info, warn, error)

Runtime Mode Flags (register with control plane):

FlagDescriptionDefault
--registerRegister with control plane as a runtime
--control-planeControl plane URLhttps://api.mockd.io
--tokenRuntime token (or MOCKD_RUNTIME_TOKEN env var)
--nameRuntime name (required with —register)
--labelsRuntime labels (key=value,key2=value2)

Pull Mode Flags:

FlagDescription
--pullmockd:// URI to pull and serve
--cacheLocal cache directory for pulled mocks

GraphQL Flags:

FlagDescriptionDefault
--graphql-schemaPath to GraphQL schema file
--graphql-pathGraphQL endpoint path/graphql

OAuth Flags:

FlagDescription
--oauth-enabledEnable OAuth provider
--oauth-issuerOAuth issuer URL
--oauth-portOAuth server port

Chaos Flags:

FlagDescription
--chaos-profileApply a built-in chaos profile at startup (e.g., slow-api, flaky, offline)
--chaos-enabledEnable chaos injection with custom settings
--chaos-latencyAdd random latency (e.g., “10ms-100ms”)
--chaos-error-rateError rate (0.0-1.0)

Note: --chaos-profile cannot be combined with --chaos-enabled, --chaos-latency, or --chaos-error-rate. Use either a profile or custom settings, not both.

MCP Flags:

FlagDescriptionDefault
--mcpEnable MCP (Model Context Protocol) HTTP serverfalse
--mcp-portMCP server port9091
--mcp-allow-remoteAllow remote MCP connections (default: localhost only)false

Validation Flags:

FlagDescriptionDefault
--validate-specPath to OpenAPI spec for request validation
--validate-failFail on validation errorfalse

Daemon Flags:

FlagShortDescriptionDefault
--detach-dRun server in background (daemon mode)
--pid-filePath to PID file~/.mockd/mockd.pid

Logging Flags:

FlagDescriptionDefault
--log-levelLog level (debug, info, warn, error)info
--log-formatLog format (text, json)text
--loki-endpointLoki endpoint for log aggregation

Tracing Flags:

FlagDescriptionDefault
--otlp-endpointOTLP HTTP endpoint for distributed tracing (e.g., http://localhost:4318/v1/traces)
--trace-samplerTrace sampling ratio (0.0-1.0)1.0

Examples:

Terminal window
# Start with defaults
mockd serve
# Start with config file on custom port
mockd serve --config mocks.json --port 3000
# Register as a runtime
mockd serve --register --name ci-runner-1 --token $MOCKD_RUNTIME_TOKEN
# Pull and serve from cloud
mockd serve --pull mockd://acme/payment-api
# Start with TLS using certificate files
mockd serve --tls-cert server.crt --tls-key server.key --https-port 8443
# Start with mTLS enabled
mockd serve --mtls-enabled --mtls-ca ca.crt --tls-cert server.crt --tls-key server.key
# Start with audit logging
mockd serve --audit-enabled --audit-file audit.log --audit-level debug
# Start in daemon/background mode
mockd serve -d
# Start with distributed tracing (send traces to Jaeger)
mockd serve --otlp-endpoint http://localhost:4318/v1/traces
# Start with JSON structured logging
mockd serve --log-level debug --log-format json
# Send logs to Loki for aggregation
mockd serve --loki-endpoint http://localhost:3100/loki/api/v1/push
# Allow CORS from any origin
mockd serve --cors-origins '*'
# Allow CORS from specific origins
mockd serve --cors-origins 'https://app.example.com,https://admin.example.com'
# Rate limit to 100 requests per second
mockd serve --rate-limit 100
# Ephemeral mode — mocks are lost on restart
mockd serve --no-persist
# Watch config file for changes and auto-reload
# Combine: ephemeral server with CORS and rate limiting
mockd serve --no-persist --cors-origins '*' --rate-limit 50 --config mocks.yaml

Start the mock server (alias for serve with additional directory loading features).

Terminal window
mockd start [flags]

Flags:

FlagShortDescriptionDefault
--port-pHTTP server port4280
--admin-port-aAdmin API port4290
--config-cPath to mock configuration file
--loadLoad mocks from directory
--validateValidate files before serving (with —load)
--watchWatch for file changes and auto-reload (with —load)false
--engine-nameName for this engine when registering with admin
--admin-urlAdmin server URL to register with (enables engine mode)
--https-portHTTPS server port (0 = disabled)0
--read-timeoutRead timeout in seconds30
--write-timeoutWrite timeout in seconds30
--max-log-entriesMaximum request log entries1000
--auto-certAuto-generate TLS certificatetrue
--detach-dRun server in background (daemon mode)false
--pid-filePath to PID file~/.mockd/mockd.pid
--log-levelLog level (debug, info, warn, error)info
--log-formatLog format (text, json)text

Also supports all TLS, mTLS, Audit, GraphQL, gRPC, OAuth, MQTT, Chaos, Validation, and Storage flags from serve.

Examples:

Terminal window
# Start with defaults
mockd start
# Start with config file on custom port
mockd start --config mocks.json --port 3000
# Start with HTTPS enabled
mockd start --https-port 8443
# Load mocks from directory
mockd start --load ./mocks/
# Validate mocks before serving
mockd start --load ./mocks/ --validate

Stop a running mockd server.

Terminal window
mockd stop [component] [flags]

Arguments:

ArgumentDescription
componentOptional component to stop: “admin” or “engine” (if not specified, stops all)

Flags:

FlagShortDescriptionDefault
--pid-filePath to PID file~/.mockd/mockd.pid
--force-fSend SIGKILL instead of SIGTERM
--timeoutTimeout in seconds to wait for shutdown10

Examples:

Terminal window
# Stop all components
mockd stop
# Force stop
mockd stop --force
# Stop with custom PID file
mockd stop --pid-file /tmp/mockd.pid
# Stop with longer timeout
mockd stop --timeout 30

Show status of running mockd server.

Terminal window
mockd status [flags]

Flags:

FlagDescriptionDefault
--pid-filePath to PID file~/.mockd/mockd.pid
--jsonOutput in JSON format

Examples:

Terminal window
# Check server status
mockd status
# Output as JSON
mockd status --json
# Use custom PID file
mockd status --pid-file /tmp/mockd.pid

Start the MCP (Model Context Protocol) server in stdio mode. Reads JSON-RPC from stdin, writes responses to stdout. Used by AI-powered editors (Claude Code, Cursor, Windsurf) to interact with mockd directly.

If no mockd server is running, auto-starts a background daemon so AI assistants work with zero setup. The daemon survives the MCP session and is shared across multiple sessions.

Terminal window
mockd mcp [flags]

Flags:

FlagDescriptionDefault
--admin-urlConnect to a specific admin API URL (skips auto-start)
--data-dirProject-scoped data directory (starts separate daemon)
--configConfig file to load on daemon startup
--portMock server port for project daemon4280 (or 14280 with --data-dir)
--admin-portAdmin API port for project daemon4290 (or 14290 with --data-dir)
--log-levelLog level for stderr output (debug, info, warn, error)warn

Connection Strategy:

  1. If --admin-url is given, connects directly to that server
  2. Otherwise, checks the PID file and default URL for a running server
  3. If nothing is running, auto-starts mockd start --detach --no-auth

Examples:

Terminal window
# Basic usage — auto-starts daemon if needed
mockd mcp
# Connect to a specific server (no auto-start)
mockd mcp --admin-url http://localhost:4290
# Project-scoped isolation (separate daemon per project)
mockd mcp --data-dir ./mockd-data
# Load a config file when auto-starting
mockd mcp --data-dir ./mockd-data --config mocks.yaml
# Custom ports for project daemon
mockd mcp --data-dir ./mockd-data --port 5000 --admin-port 5001

Editor Integration:

Add to your MCP config file:

{
"mcpServers": {
"mockd": {
"command": "mockd",
"args": ["mcp"]
}
}
}

See the MCP Server guide for detailed editor setup (Claude Code, Cursor, Windsurf).


Run a headless mock engine — no admin API, no data persistence, no PID files. Ideal for CI/CD pipelines, Docker containers, and environments where you need a lightweight, stateless mock server.

Terminal window
mockd engine [flags]

Flags:

FlagShortDescriptionDefault
--config-cPath to mock config file (YAML or JSON)Required
--port-pHTTP server port (0 = OS auto-assign)4280
--hostBind address0.0.0.0
--print-urlPrint the server URL to stdout on startupfalse
--log-levelLog level (debug, info, warn, error)warn
--log-formatLog format (text, json)text
--read-timeoutHTTP read timeout in seconds30
--write-timeoutHTTP write timeout in seconds30

Unlike mockd serve or mockd start, mockd engine:

  • Does not start an admin API
  • Does not persist data to disk
  • Does not create PID files or support daemon mode
  • Loads all mocks from a single config file
  • Runs in the foreground until SIGTERM/SIGINT

Examples:

Terminal window
# Start with a config file
mockd engine --config mocks.yaml
# Auto-assign a port and print it (great for CI where ports may conflict)
mockd engine --config mocks.yaml --port 0 --print-url
# JSON logs for CI log parsing
mockd engine --config mocks.yaml --log-format json
# Custom timeouts for slow-response testing
mockd engine --config mocks.yaml --read-timeout 60 --write-timeout 60

CI/CD Usage:

Terminal window
# In a GitHub Action or CI script
mockd engine --config test-mocks.yaml --port 0 --print-url &
MOCKD_URL=$(head -1 /dev/stdin)
# Run tests against $MOCKD_URL
pytest tests/ --base-url "$MOCKD_URL"
kill %1

Start local admins and engines defined in mockd.yaml. Validates the project configuration, starts servers, and bootstraps workspaces seamlessly.

Terminal window
mockd up [flags]

Flags:

FlagShortDescriptionDefault
--config-fConfig file path (can be specified multiple times)
--detach-dRun in background (daemon mode)false
--log-levelLog level (debug, info, warn, error)info

Examples:

Terminal window
mockd up
mockd up -f custom-mockd.yaml -d

Stop all services started by a previous mockd up command.

Terminal window
mockd down [flags]

Flags:

FlagDescriptionDefault
--pid-filePath to PID file~/.mockd/mockd.pid
--timeoutShutdown timeout duration30s

Show all ports in use by the running mockd server.

Terminal window
mockd ports [flags]

Flags:

FlagShortDescriptionDefault
--pid-filePath to PID file~/.mockd/mockd.pid
--admin-port-aAdmin API port to query4290
--jsonOutput in JSON format

Output:

The command displays a table of all ports with their protocol, component, and status:

PORT PROTOCOL COMPONENT STATUS
------- ---------- --------------- --------
1883 MQTT MQTT Broker running
4280 HTTP Mock Engine running
4290 HTTP Admin API running
50051 gRPC gRPC Server running

Examples:

Terminal window
# Show all ports
mockd ports
# Output as JSON
mockd ports --json
# Query a different admin port
mockd ports --admin-port 8090

Create a starter mockd configuration file.

Terminal window
mockd init [flags]

Flags:

FlagShortDescriptionDefault
--forceOverwrite existing config file
--output-oOutput filenamemockd.yaml
--formatOutput format: yaml or jsoninferred from filename
--interactive-iInteractive mode - prompts for configuration
--template-tTemplate to usedefault

Templates:

TemplateDescription
defaultBasic HTTP mocks (hello, echo, health)
crudFull REST CRUD API for resources
websocket-chatChat room WebSocket endpoint with echo
graphql-apiGraphQL API with User CRUD resolvers
grpc-servicegRPC Greeter service with reflection
mqtt-iotMQTT broker with IoT sensor topics

Examples:

Terminal window
# Create default mockd.yaml
mockd init
# List available templates
mockd init --template list
# Use CRUD API template
mockd init --template crud
# Use WebSocket template with custom output
mockd init -t websocket-chat -o websocket.yaml
# Interactive setup
mockd init -i
# Create with custom filename
mockd init -o my-mocks.yaml
# Create JSON config
mockd init --format json -o mocks.json
# Overwrite existing config
mockd init --force

The mockd CLI organizes mock creation by protocol. Each protocol has its own <protocol> add subcommand.

By default, if a mock already exists with the same method and path (or equivalent identifiers), it is updated in place (upsert behavior). The command prints “Updated mock: …” when an existing mock is modified and “Created mock: …” when a new mock is created.

The following flags apply to all <protocol> add commands:

FlagShortDescriptionDefault
--name-nMock display name
--allow-duplicateCreate a second mock even if one already exists on the same routefalse
--admin-urlAdmin API base URLhttp://localhost:4290
--jsonOutput in JSON format

Add or update an HTTP or SSE mock endpoint.

Terminal window
mockd http add [flags]

HTTP Flags:

FlagShortDescriptionDefault
--method-mHTTP method to matchGET
--pathURL path to matchRequired
--status-sResponse status code200
--body-bResponse body
--body-fileRead response body from file
--header-HResponse header (key:value), repeatable
--match-headerRequired request header (key:value), repeatable
--match-queryRequired query param (key=value or key:value), repeatable
--match-body-containsMatch requests whose body contains this string
--path-patternRegex path pattern for matching (alternative to --path)
--priorityMock priority (higher = matched first)
--delayResponse delay in milliseconds
--stateful-operationWire to a custom stateful operation (e.g., TransferFunds)
--tableBind to a stateful resource table (e.g., users)
--bindStateful action: list, get, create, update, patch, delete, custom

SSE Flags (for streaming):

FlagDescriptionDefault
--sseEnable SSE streaming response
--sse-eventSSE event (type:data), repeatable
--sse-delayDelay between events in milliseconds100
--sse-templateBuilt-in template: openai-chat, notification-stream
--sse-repeatRepeat events N times (0 = infinite)1
--sse-keepaliveKeepalive interval in milliseconds (0 = disabled)0

Examples:

Terminal window
mockd http add --path /api/users --status 200 --body '[{"id":1}]'
mockd http add -m POST --path /api/users -s 201 -b '{"created": true}'
mockd http add --path /events --sse --sse-event 'connected:{"status":"ok"}'
mockd http add -m POST --path /api/transfer --stateful-operation TransferFunds
# Stateful bindings — bind to a table for automatic CRUD
mockd http add --path /api/users --table users --bind list
mockd http add -m POST --path /api/users --table users --bind create
mockd http add --path /api/users/{id} --table users --bind get
mockd http add -m PUT --path /api/users/{id} --table users --bind update
mockd http add -m DELETE --path /api/users/{id} --table users --bind delete
mockd http add -m POST --path /api/users/{id}/verify --table users --bind custom --stateful-operation VerifyUser

Add or update a WebSocket mock endpoint.

Terminal window
mockd websocket add [flags]

WebSocket Flags:

FlagDescriptionDefault
--pathWebSocket pathRequired
--messageDefault response message (JSON)
--echoEnable echo mode

Examples:

Terminal window
mockd websocket add --path /ws/chat --echo
mockd websocket add --path /ws/events --message '{"type": "connected"}'

Add or update a GraphQL mock endpoint.

Terminal window
mockd graphql add [flags]

GraphQL Flags:

FlagDescriptionDefault
--pathGraphQL endpoint path/graphql
--operationOperation nameRequired
--op-typeOperation type: query or mutationquery
--responseJSON response data

Examples:

Terminal window
mockd graphql add --operation getUser --response '{"data": {"user": {"id": "1"}}}'

Validate a GraphQL schema file.

Terminal window
mockd graphql validate <schema-file>

Execute a query against a GraphQL endpoint.

Terminal window
mockd graphql query <endpoint> <query> [flags]

Flags:

FlagShortDescriptionDefault
--header-HAdditional headers (key:value,key2:value2)
--prettyPretty print outputtrue

Examples:

Terminal window
mockd graphql query http://localhost:4280/graphql 'query { getUser { id name } }'

Add or update a gRPC mock endpoint.

Terminal window
mockd grpc add [flags]

gRPC Flags:

FlagDescriptionDefault
--protoPath to .proto file (required, repeatable)
--proto-pathImport path for proto dependencies (repeatable)
--serviceService name, e.g., myapp.UserService (required)
--rpc-methodRPC method name (required)
--responseJSON response data
--grpc-portgRPC server port50051

Examples:

Terminal window
mockd grpc add --proto ./user.proto --service myapp.UserService --rpc-method GetUser --response '{"id": "1"}'

Call a gRPC endpoint directly from the CLI.

Terminal window
mockd grpc call <endpoint> <service/method> <json-body> [flags]

Flags:

FlagShortDescriptionDefault
--metadata-mgRPC metadata (key:value)
--plaintextUse plaintext connectiontrue
--prettyPretty print JSON outputtrue

Examples:

Terminal window
mockd grpc call localhost:50051 myapp.UserService/GetUser '{"id": "1"}'

Add or update an MQTT mock endpoint.

Terminal window
mockd mqtt add [flags]

MQTT Flags:

FlagDescriptionDefault
--topicTopic patternRequired
--payloadResponse payload
--qosQoS level: 0, 1, or 20
--mqtt-portMQTT broker port (required)

Examples:

Terminal window
mockd mqtt add --topic sensors/temperature --payload '{"temp": 72.5}' --qos 1

Publish a message to an MQTT topic.

Terminal window
mockd mqtt publish <broker> <topic> <message> [flags]

Flags:

FlagShortDescriptionDefault
--message-mMessage to publish (alternative to positional arg)
--qos-qQoS level (0, 1, 2)0
--retain-rRetain messagefalse
--username-uMQTT username
--password-PMQTT password

Subscribe to an MQTT topic and print messages to the console.

Terminal window
mockd mqtt subscribe <broker> <topic> [flags]

Flags:

FlagShortDescriptionDefault
--qos-qQoS level (0, 1, 2)0
--username-uMQTT username
--password-PMQTT password
--count-cNumber of messages to receive before exiting (0 = infinite)0

Show the current mockd MQTT broker status.

Terminal window
mockd mqtt status [flags]

Flags:

FlagDescriptionDefault
--admin-urlAdmin API base URLhttp://localhost:4290

Add or update a SOAP mock endpoint.

Terminal window
mockd soap add [flags]

SOAP Flags:

FlagDescriptionDefault
--pathSOAP endpoint path/soap
--operationSOAP operation nameRequired
--soap-actionSOAPAction header value
--responseXML response body
--stateful-resourceStateful resource name (e.g., users)
--stateful-actionStateful action: list, get, create, update, delete, custom

--stateful-resource and --stateful-action must be used together. When set, the operation reads/writes the named stateful resource instead of returning a canned response.

Examples:

Terminal window
# Canned response
mockd soap add --operation GetWeather --soap-action "http://example.com/GetWeather" --response '<GetWeatherResponse><Temperature>72</Temperature></GetWeatherResponse>'
# Stateful: list all users from the "users" resource
mockd soap add --path /soap --action GetUsers --stateful-resource users --stateful-action list
# Stateful: get a single user by ID
mockd soap add --path /soap --action GetUser --stateful-resource users --stateful-action get

Generate SOAP mock configurations from a WSDL file.

Terminal window
mockd soap import <wsdl-file> [flags]

Flags:

FlagShortDescriptionDefault
--statefulEnable stateful CRUD heuristicsfalse
--output-oOutput file pathstdout
--format-fOutput format (yaml/json)yaml

Examples:

Terminal window
# Generate static SOAP mocks from WSDL
mockd soap import service.wsdl
# Generate stateful mocks (auto-detects CRUD operations)
mockd soap import service.wsdl --stateful
# Save to a file
mockd soap import service.wsdl --stateful -o soap-mocks.yaml
# Output as JSON
mockd soap import service.wsdl --format json

When --stateful is enabled, the importer detects CRUD patterns in operation names (Get, List, Create, Update, Delete) and generates both statefulResources definitions and SOAP operations pre-wired with statefulResource/statefulAction fields. For new projects, consider converting the generated statefulResources to tables and extend bindings for a cleaner separation of data and routing.


Validate a WSDL file against standard schema rules.

Terminal window
mockd soap validate <wsdl-file>

Execute a SOAP call against an endpoint.

Terminal window
mockd soap call <endpoint> <action> <body> [flags]

Flags:

FlagShortDescriptionDefault
--header-HAdditional headers (key:value,key2:value2)
--prettyPretty print outputtrue
--actionSOAPAction header value
--soap12Use SOAP 1.2 envelope formatfalse
--timeoutRequest timeout in seconds30

Examples:

Terminal window
mockd soap call http://localhost:4280/soap "http://example.com/GetWeather" '<soapenv:Envelope>...</soapenv:Envelope>'
# SOAP 1.2 with custom action
mockd soap call --soap12 --action "http://example.com/GetWeather" http://localhost:4280/soap GetWeather

Add or update an OAuth/OIDC mock provider. This creates a full OAuth/OIDC mock server with standard endpoints including /.well-known/openid-configuration, /token, /authorize, /userinfo, and /jwks.

Terminal window
mockd oauth add [flags]

OAuth Flags:

FlagDescriptionDefault
--issuerOAuth issuer URLhttp://localhost:4280
--client-idOAuth client IDtest-client
--client-secretOAuth client secrettest-secret
--oauth-userTest usernametestuser
--oauth-passwordTest passwordpassword

Examples:

Terminal window
mockd oauth add
mockd oauth add --name "Auth Server" --issuer http://localhost:4280/auth --client-id my-app --client-secret s3cret --oauth-user admin --oauth-password admin123

List all OAuth mocks.

Terminal window
mockd oauth list [flags]

Get details of a specific OAuth mock.

Terminal window
mockd oauth get <id> [flags]

Delete an OAuth mock.

Terminal window
mockd oauth delete <id> [flags]

Show the OAuth provider status.

Terminal window
mockd oauth status [flags]

Manage stateful CRUD resources. Stateful resources provide in-memory data stores that can be shared across protocols (HTTP REST, SOAP, GraphQL, gRPC, etc.).

Terminal window
mockd stateful [command]

Commands:

CommandDescription
addCreate a stateful CRUD resource
listList all stateful resources
resetReset a stateful resource to seed data

Create a new stateful CRUD resource (data store). Resources are created as pure data stores with no auto-generated HTTP endpoints. Use extend bindings in config files to wire mocks to tables, or use mockd http add --stateful for quick CLI prototyping.

Terminal window
mockd stateful add <name> [flags]

Flags:

FlagDescriptionDefault
--id-fieldCustom ID field nameid

Examples:

Terminal window
# Create a data store
mockd stateful add users
# Custom ID field
mockd stateful add orders --id-field orderId
# Quick prototyping: create resource + HTTP CRUD mocks in one step
mockd http add --path /api/users --stateful

List all stateful resources and their item counts.

Terminal window
mockd stateful list [flags]

Flags:

FlagDescriptionDefault
--limitMaximum items to show per resource100
--offsetSkip this many items0
--sortSort field
--orderSort order (asc or desc)

Example output:

Stateful Resources (3):
NAME ITEMS SEED ID FIELD
---- ----- ---- --------
users 5 3 id
products 12 10 id
orders 0 0 orderId
Total items across all resources: 17

Reset a stateful resource to its initial seed data state. All current items are removed and replaced with the original seed data (if any).

Terminal window
mockd stateful reset <name> [flags]

Examples:

Terminal window
# Reset users to seed data
mockd stateful reset users
# Reset with JSON output
mockd stateful reset products --json

Manage custom multi-step operations that run against stateful resources. Custom operations define a pipeline of steps (read, create, update, delete, set) with expression-based logic using expr-lang/expr. They can be invoked via CLI, REST API, SOAP, or any protocol that supports the stateful bridge.

Terminal window
mockd stateful custom [command]

Commands:

CommandDescription
listList all registered custom operations
getShow details of a custom operation
addRegister a new custom operation
validateValidate a custom operation definition (no writes)
runExecute a custom operation
deleteDelete a custom operation

List all registered custom operations.

Terminal window
mockd stateful custom list [flags]

Example:

Terminal window
mockd stateful custom list
mockd stateful custom list --json

Show details of a custom operation including its steps and response template.

Terminal window
mockd stateful custom get <name> [flags]

Example:

Terminal window
mockd stateful custom get TransferFunds
mockd stateful custom get TransferFunds --json

Register a new custom operation from a file or inline definition.

Terminal window
mockd stateful custom add [flags]

Flags:

FlagDescriptionDefault
--filePath to YAML/JSON file containing the operation definition
--definitionInline JSON operation definition

Examples:

Terminal window
# From a YAML file
mockd stateful custom validate --file transfer.yaml
mockd stateful custom add --file transfer.yaml
# Inline JSON definition
mockd stateful custom add --definition '{
"name": "TransferFunds",
"consistency": "atomic",
"steps": [
{"type": "read", "resource": "accounts", "id": "input.sourceId", "as": "source"},
{"type": "read", "resource": "accounts", "id": "input.destId", "as": "dest"},
{"type": "update", "resource": "accounts", "id": "input.sourceId", "set": {"balance": "source.balance - input.amount"}},
{"type": "update", "resource": "accounts", "id": "input.destId", "set": {"balance": "dest.balance + input.amount"}}
],
"response": {"status": "\"completed\""}
}'

Operation Definition Format:

name: TransferFunds
consistency: atomic
steps:
- type: read
resource: accounts
id: "input.sourceId"
as: source
- type: read
resource: accounts
id: "input.destId"
as: dest
- type: set
as: total
value: "source.balance + dest.balance"
- type: update
resource: accounts
id: "input.sourceId"
set:
balance: "source.balance - input.amount"
- type: update
resource: accounts
id: "input.destId"
set:
balance: "dest.balance + input.amount"
response:
status: '"completed"'
total: "string(total)"

Step Types:

TypeDescriptionRequired Fields
readRead a single item from a resourceresource, id, as
createCreate a new item in a resourceresource, set
updateUpdate an existing item in a resourceresource, id, set
deleteDelete an item from a resourceresource, id
setSet a computed value in the expression contextvar, value

All id, value, and set field values are expr expressions evaluated against an environment containing input (the request data) and all previously computed variables from as and set.var.


Validate a custom operation definition locally before registering it. This command performs preflight checks and does not mutate server state.

Terminal window
mockd stateful custom validate [flags]

Flags:

FlagDescriptionDefault
--filePath to YAML/JSON file containing the operation definition
--definitionInline JSON operation definition
--inputInline JSON input example for expression compile checks
--input-filePath to JSON file containing input example
--fixtures-filePath to JSON/YAML fixtures file for runtime expression checks
--check-resourcesVerify referenced stateful resources exist on the running admin/enginefalse
--check-expressions-runtimeEvaluate expressions with sample input/fixtures (no writes)false
--strictTreat validation warnings as errorsfalse

Examples:

Terminal window
# Validate a YAML definition locally (no writes)
mockd stateful custom validate --file transfer.yaml
# Validate with example input to catch expression/env issues
mockd stateful custom validate --file transfer.yaml \
--input '{"sourceId":"acct-1","destId":"acct-2","amount":100}'
# Validate and verify referenced stateful resources exist on the running engine
mockd stateful custom validate --file transfer.yaml --check-resources
# Runtime-check expressions with sample input + fixtures (no writes)
mockd stateful custom validate --file transfer.yaml \
--input '{"sourceId":"acct-1","destId":"acct-2","amount":100}' \
--check-expressions-runtime \
--fixtures-file transfer-fixtures.json
# Fail on warnings (e.g., empty update/create set maps)
mockd stateful custom validate --file transfer.yaml --strict

Fixtures file (optional, recommended for --check-expressions-runtime):

{
"resources": {
"accounts": {
"acct-1": { "id": "acct-1", "balance": 500 },
"acct-2": { "id": "acct-2", "balance": 200 }
}
},
"vars": {
"source": { "id": "acct-1", "balance": 500 }
}
}

If fixtures are missing for read/update aliases, validation still runs using synthetic placeholders and emits warnings (or fails under --strict).


Execute a registered custom operation with the given input.

Terminal window
mockd stateful custom run <name> [flags]

Flags:

FlagDescriptionDefault
--inputInline JSON input for the operation
--input-filePath to JSON file containing operation input

Examples:

Terminal window
# Run with inline input
mockd stateful custom run TransferFunds --input '{"sourceId":"acct-1","destId":"acct-2","amount":100}'
# Run with input from file
mockd stateful custom run TransferFunds --input-file transfer-input.json
# Run with no input
mockd stateful custom run TransferFunds

Delete a registered custom operation.

Terminal window
mockd stateful custom delete <name> [flags]

Example:

Terminal window
mockd stateful custom delete TransferFunds

Create mocks from templates.

Terminal window
mockd new [flags]

Flags:

FlagShortDescriptionDefault
--template-tTemplate: blank, crud, auth, pagination, errorsblank
--name-nCollection name
--output-oOutput filestdout
--resourceResource name (for crud/pagination templates)

Templates:

TemplateDescription
blankEmpty mock collection
crudREST CRUD endpoints (GET list, GET one, POST, PUT, DELETE)
authAuthentication flow (login, logout, refresh, me)
paginationList endpoints with cursor/offset pagination
errorsCommon HTTP error responses (400, 401, 403, 404, 500)

Examples:

Terminal window
# Create a blank collection
mockd new -t blank -o mocks.yaml
# Create CRUD endpoints for users
mockd new -t crud --resource users -o users.yaml
# Create auth endpoints
mockd new -t auth -n "Auth API" -o auth.yaml

List all configured mocks.

Terminal window
mockd list [flags]

Flags:

FlagShortDescriptionDefault
--config-cList mocks from config file (no server needed)
--type-tFilter by type: http, websocket, graphql, grpc, mqtt, soap, oauth
--no-truncate-wShow full IDs and paths without truncationfalse
--admin-urlAdmin API base URLhttp://localhost:4290
--jsonOutput in JSON format

Examples:

Terminal window
# List all mocks from running server
mockd list
# List mocks from config file (no server needed)
mockd list --config mockd.yaml
# List only WebSocket mocks
mockd list --type websocket
# Show full IDs and paths (useful for copy-pasting IDs into delete commands)
mockd list --no-truncate
# List as JSON
mockd list --json
# List from remote server
mockd list --admin-url http://remote:4290
# List mocks in a specific workspace
mockd list --workspace ws_abc123

Get details of a specific mock.

Terminal window
mockd get <mock-id> [flags]

Arguments:

ArgumentDescription
mock-idID of the mock to retrieve (required)

Flags:

| Flag | Description | Default | |------|-------|-------------|---------| | --admin-url | Admin API base URL | http://localhost:4290 | | --json | Output in JSON format | |

Examples:

Terminal window
# Get mock details
mockd get abc123
# Get as JSON
mockd get abc123 --json

Delete mocks by ID, ID prefix, or path. Also available as mockd remove and mockd rm.

Terminal window
mockd delete [<mock-id>] [flags]

Arguments:

ArgumentDescription
mock-idFull or prefix of the mock ID. Supports prefix matching — if the prefix uniquely identifies one mock, it is deleted. If the prefix matches multiple mocks, all matches are shown and you are asked to be more specific.

Flags:

FlagShortDescriptionDefault
--pathDelete mocks matching a URL path
--methodFilter by HTTP method (used with --path)
--yes-ySkip confirmation when multiple mocks matchfalse
--admin-urlAdmin API base URLhttp://localhost:4290

Examples:

Terminal window
# Delete by exact ID
mockd delete http_abc123def456
# Delete by ID prefix (must uniquely match one mock)
mockd delete http_abc
# Output: Deleted mock: http_abc123def456
# If prefix is ambiguous, shows matches and asks for more specificity
mockd delete http_a
# Output:
# Multiple mocks match prefix "http_a":
# http_abc123def456 GET /api/users
# http_aef789012345 POST /api/users
# Please provide a more specific prefix.
# Delete all mocks on a path
mockd delete --path /api/users
# Delete only GET mocks on a path
mockd delete --path /api/users --method GET
# Skip confirmation when deleting multiple mocks
mockd delete --path /api/users -y
# Using aliases
mockd remove http_abc123
mockd rm http_abc123

Hidden aliases for mockd delete. All flags and arguments are identical.

Terminal window
mockd remove [<mock-id>] [flags]
mockd rm [<mock-id>] [flags]

See mockd delete for full documentation.


Update an existing mock endpoint by ID. Only specified fields are modified — unspecified fields retain their current values.

Terminal window
mockd update <id> [flags]

Arguments:

ArgumentDescription
idID of the mock to update (required)

Flags:

FlagShortDescriptionDefault
--body-bNew response body
--body-fileRead response body from file
--status-sNew response status code
--header-HResponse header (key:value), repeatable
--delayResponse delay in milliseconds
--tableBind to a stateful resource table
--bindStateful action: list, get, create, update, patch, delete, custom
--operationCustom operation name (for --bind custom)
--name-nMock display name
--enabledEnable or disable the mock (true/false)

--table and --bind must be used together. When set, the mock is bound to the specified table and the response/SSE/statefulOperation fields are cleared.

Examples:

Terminal window
# Change response status code
mockd update http_abc123 --status 201
# Change response body
mockd update http_abc123 --body '{"updated": true}'
# Read body from file
mockd update http_abc123 --body-file response.json
# Bind to a stateful table
mockd update http_abc123 --table users --bind list
# Bind to a custom operation
mockd update http_abc123 --table users --bind custom --operation VerifyUser
# Add response delay
mockd update http_abc123 --delay 500
# Disable a mock
mockd update http_abc123 --enabled false
# Re-enable a mock
mockd update http_abc123 --enabled true
# Rename a mock
mockd update http_abc123 --name "Get Users v2"
# Set a response header
mockd update http_abc123 -H "X-Custom:value"

Manage workspaces within the current context. Workspaces provide isolated environments for mocks, stateful resources, request logs, and configuration.

Terminal window
mockd workspace [command]

Running mockd workspace without a subcommand shows the current workspace.

Subcommands:

CommandAliasesDescription
showShow current workspace (default)
listlsList all workspaces on the server
createCreate a new workspace
use <id>Switch to a different workspace
delete <id>rm, removeDelete a workspace
clearClear workspace selection (use default)

Show the current workspace and context information.

Terminal window
mockd workspace show

List all workspaces on the server.

Terminal window
mockd workspace list [flags]

Example output:

CURRENT ID NAME TYPE DESCRIPTION
* ws_abc123 Payment API local Stripe mock environment
ws_def456 Comms API local Twilio mock environment

Create a new workspace.

Terminal window
mockd workspace create [flags]

Flags:

FlagShortDescriptionDefault
--name-nWorkspace name (required)
--description-dWorkspace description
--typeWorkspace typelocal
--useSwitch to this workspace after creatingfalse

Examples:

Terminal window
# Create a workspace
mockd workspace create -n "Payment API" -d "Stripe mock environment"
# Create and switch to it
mockd workspace create -n "Payment API" --use

Switch to a different workspace. All subsequent commands will be scoped to this workspace.

Terminal window
mockd workspace use <id>

Examples:

Terminal window
mockd workspace use ws_abc123

Tip: You can also use --workspace <id> on any command to scope a single operation without switching the persistent context.


Delete a workspace. Prompts for confirmation unless --force is given.

Terminal window
mockd workspace delete <id> [flags]

Flags:

FlagShortDescriptionDefault
--force-fSkip confirmationfalse

Clear the current workspace selection, reverting to the default workspace.

Terminal window
mockd workspace clear

Import mocks from various sources and formats. Imported configurations may include statefulResources definitions (legacy) or tables and extend bindings (recommended), which are persisted to the admin file store and survive restarts. Runtime data for stateful resources is in-memory only and resets to seed data on restart.

Terminal window
mockd import <source> [flags]

Arguments:

ArgumentDescription
sourcePath to file, or cURL command (in quotes)

Flags:

FlagShortDescriptionDefault
--format-fForce format (auto-detected if omitted)
--replaceReplace all existing mocksmerge
--dry-runPreview import without saving
--include-staticInclude static assets (for HAR imports)
--admin-urlAdmin API base URLhttp://localhost:4290

Supported Formats:

FormatDescription
mockdMockd native format (YAML/JSON)
openapiOpenAPI 3.x or Swagger 2.0
postmanPostman Collection v2.x
harHTTP Archive (browser recordings)
wiremockWireMock JSON mappings
mockoonMockoon environment JSON
curlcURL command
wsdlWSDL 1.1 service definition (generates SOAP mocks)

Examples:

Terminal window
# Import from OpenAPI spec (auto-detected)
mockd import openapi.yaml
# Import from Postman collection
mockd import collection.json -f postman
# Import from Mockoon environment
mockd import environment.json -f mockoon
# Import from HAR file including static assets
mockd import recording.har --include-static
# Import from cURL command
mockd import "curl -X POST https://api.example.com/users -H 'Content-Type: application/json' -d '{\"name\": \"test\"}'"
# Preview import without saving
mockd import openapi.yaml --dry-run
# Replace all mocks with imported ones
mockd import mocks.yaml --replace
# Import into a specific workspace
mockd import openapi.yaml --workspace ws_abc123

Export current mocks to file.

Terminal window
mockd export [flags]

Flags:

FlagShortDescriptionDefault
--output-oOutput filestdout
--name-nCollection nameexported-config
--format-fOutput format: mockd, openapimockd
--versionVersion tag for the export
--admin-urlAdmin API base URLhttp://localhost:4290

Formats:

FormatDescription
mockdMockd native format (YAML/JSON) - recommended for portability
openapiOpenAPI 3.x specification - for API documentation

Examples:

Terminal window
# Export to stdout as YAML
mockd export
# Export to JSON file
mockd export -o mocks.json
# Export to YAML file
mockd export -o mocks.yaml
# Export as OpenAPI specification
mockd export -f openapi -o api.yaml
# Export with custom name
mockd export -n "My API Mocks" -o mocks.yaml
# Export mocks from a specific workspace
mockd export --workspace ws_abc123 -o mocks.yaml

Convert recorded API traffic directly into mockd mock configurations. Reads recordings from disk (written by mockd proxy start) and outputs mock configurations that can be piped or imported with mockd import.

Terminal window
mockd convert [flags]

Flags:

FlagShortDescriptionDefault
--session-sSession name or directorylatest
--file-fPath to a specific recording file or directory
--recordings-dirBase recordings directory override
--include-hostsComma-separated host patterns to include (e.g. api.*.com)
--path-filterGlob pattern to filter paths (e.g., /api/*)
--methodComma-separated HTTP methods (e.g., GET,POST)
--statusStatus code filter (e.g., 2xx, 200,201)
--smart-matchConvert dynamic path segments like /users/123 to /users/{id}false
--duplicatesDuplicate handling strategy: first, last, allfirst
--include-headersInclude request headers in mock matchersfalse
--check-sensitiveCheck for sensitive data in recordings and show warningstrue
--output-oOutput file path (default is stdout)

Examples:

Terminal window
# Convert the latest proxy recording session into mocks
mockd convert
# Convert a named session with smart path parameter matching
mockd convert --session stripe-api --smart-match
# Convert only specific host traffic, targeting only GET/POST methods
mockd convert --include-hosts "api.stripe.com" --method GET,POST
# Convert a specific recording JSON file
mockd convert --file ./my-recordings/rec_abc123.json
# Pipe converted JSON directly into the server using 'mockd import'
mockd convert --session my-api --smart-match | mockd import "curl -X POST -d @-"

View request logs.

Terminal window
mockd logs [flags]

Flags:

FlagShortDescriptionDefault
--protocolFilter by protocol (http, grpc, mqtt, soap, graphql, websocket, sse)
--method-mFilter by HTTP method
--path-pFilter by path (substring match)
--matchedShow only matched requests
--unmatchedShow only unmatched requests
--limit-nNumber of entries to show20
--verboseShow headers and body
--clearClear all logs
--follow-fStream logs in real-time (like tail -f)
--admin-urlAdmin API base URLhttp://localhost:4290
--jsonOutput in JSON format

Examples:

Terminal window
# Show recent logs
mockd logs
# Show last 50 entries
mockd logs -n 50
# Filter by method
mockd logs -m POST
# Filter by protocol
mockd logs --protocol grpc
# Show verbose output
mockd logs --verbose
# Stream logs in real-time
mockd logs --follow
# Clear logs
mockd logs --clear
# Show logs for a specific workspace
mockd logs --workspace ws_abc123

Show effective configuration.

Terminal window
mockd config [flags]

Flags:

FlagDescription
--jsonOutput in JSON format

Examples:

Terminal window
mockd config
mockd config --json

Diagnose common setup issues and validate configuration.

Terminal window
mockd doctor [flags]

Flags:

FlagShortDescriptionDefault
--configPath to config file to validate
--port-pMock server port to check4280
--admin-port-aAdmin API port to check4290

Examples:

Terminal window
# Run all checks with defaults
mockd doctor
# Validate a specific config file
mockd doctor --config mocks.yaml
# Check custom ports
mockd doctor -p 3000 -a 3001

Manage contexts (admin server + workspace pairs). Similar to kubectl contexts, allows quick switching between different mockd deployments (local, staging, CI, cloud, etc.).

Terminal window
mockd context [command]

Subcommands:

CommandDescription
(no command)Show current context
showShow current context (same as no command)
use <name>Switch to a different context
add <name>Add a new context
listList all contexts
remove <name>Remove a context

Configuration:

Contexts are stored in ~/.config/mockd/contexts.yaml. A default “local” context pointing to http://localhost:4290 is created automatically.


Show the current context.

Terminal window
mockd context
mockd context show

Output includes:

  • Current context name
  • Admin URL
  • Workspace (if set)
  • Description (if set)
  • Environment variable overrides (if active)

Switch to a different context.

Terminal window
mockd context use <name>

Examples:

Terminal window
# Switch to staging context
mockd context use staging
# Switch back to local
mockd context use local

Add a new context.

Terminal window
mockd context add <name> [flags]

Flags:

FlagShortDescriptionDefault
--sessionClear specific session only
--recordings-dirBase recordings directory override
--force-fSkip confirmation

Examples:

Terminal window
mockd recordings clear
mockd recordings clear --force


Manage WebSocket and SSE stream recordings.

Terminal window
mockd stream-recordings <subcommand> [flags]

Subcommands:

  • list, ls - List all stream recordings
  • show, get - Show details of a specific recording
  • delete, rm - Delete a recording
  • export - Export a recording to JSON
  • convert - Convert a recording to mock config
  • stats - Show storage statistics
  • vacuum - Remove soft-deleted recordings
  • sessions - List active recording sessions

List all WebSocket and SSE stream recordings.

Terminal window
mockd stream-recordings list [flags]

Flags:

FlagDescriptionDefault
--protocolFilter by protocol (websocket, sse)
--pathFilter by path prefix
--statusFilter by status (complete, incomplete, recording)
--jsonOutput as JSON
--limitMaximum number of recordings to show20
--offsetOffset for pagination
--sortSort by field: startTime, name, sizestartTime
--orderSort order: asc, descdesc
--include-deletedInclude soft-deleted recordings

Examples:

Terminal window
# List all recordings
mockd stream-recordings list
# List only WebSocket recordings
mockd stream-recordings list --protocol websocket
# List as JSON
mockd stream-recordings list --json
# Paginate results
mockd stream-recordings list --limit 10 --offset 20

Show details of a specific stream recording.

Terminal window
mockd stream-recordings show <id> [flags]

Flags:

FlagDescription
--jsonOutput as JSON

Examples:

Terminal window
mockd stream-recordings show 01ABCDEF123456
mockd stream-recordings show 01ABCDEF123456 --json

Delete a stream recording.

Terminal window
mockd stream-recordings delete <id> [flags]

Flags:

FlagShortDescription
--force-fSkip confirmation
--permanentPermanently delete (not soft-delete)

Examples:

Terminal window
mockd stream-recordings delete 01ABCDEF123456
mockd stream-recordings delete 01ABCDEF123456 --force
mockd stream-recordings delete 01ABCDEF123456 --permanent

Export a stream recording to JSON format.

Terminal window
mockd stream-recordings export <id> [flags]

Flags:

FlagShortDescriptionDefault
--output-oOutput file pathstdout

Examples:

Terminal window
mockd stream-recordings export 01ABCDEF123456
mockd stream-recordings export 01ABCDEF123456 -o recording.json

Convert a stream recording to a mock configuration.

Terminal window
mockd stream-recordings convert <id> [flags]

Flags:

FlagShortDescriptionDefault
--output-oOutput file pathstdout
--simplify-timingNormalize timing to reduce noise
--min-delayMinimum delay to preserve in ms10
--max-delayMaximum delay in ms5000
--include-clientInclude client messages as expect stepstrue
--deduplicateRemove consecutive duplicate messages

Examples:

Terminal window
mockd stream-recordings convert 01ABCDEF123456
mockd stream-recordings convert 01ABCDEF123456 --simplify-timing
mockd stream-recordings convert 01ABCDEF123456 -o scenario.json

Show storage statistics for stream recordings.

Terminal window
mockd stream-recordings stats [flags]

Flags:

FlagDescription
--jsonOutput as JSON

Permanently remove soft-deleted recordings.

Terminal window
mockd stream-recordings vacuum [flags]

Flags:

FlagShortDescription
--force-fSkip confirmation

Examples:

Terminal window
mockd stream-recordings vacuum
mockd stream-recordings vacuum --force

List active recording sessions.

Terminal window
mockd stream-recordings sessions [flags]

Flags:

FlagDescription
--jsonOutput as JSON

Generate mock configurations using AI.

Terminal window
mockd generate [flags]

Flags:

FlagShortDescriptionDefault
--input-iInput OpenAPI spec file
--prompt-pNatural language description for generation
--output-oOutput filestdout
--aiEnable AI-powered data generation
--providerAI provider (openai, anthropic, ollama)
--modelAI model to use
--dry-runPreview generation without saving
--admin-urlAdmin API base URLhttp://localhost:4290

Environment Variables:

VariableDescription
MOCKD_AI_PROVIDERDefault AI provider
MOCKD_AI_API_KEYAPI key for the provider
MOCKD_AI_MODELDefault model
MOCKD_AI_ENDPOINTCustom endpoint (for Ollama)

Examples:

Terminal window
# Generate mocks from OpenAPI spec with AI enhancement
mockd generate --ai --input openapi.yaml -o mocks.yaml
# Generate mocks from natural language description
mockd generate --ai --prompt "user management API with CRUD operations"
# Generate mocks using specific provider
mockd generate --ai --provider openai --prompt "payment processing API"
# Preview what would be generated
mockd generate --ai --prompt "blog API" --dry-run

Enhance existing mocks with AI-generated response data.

Terminal window
mockd enhance [flags]

Flags:

FlagDescription
--aiEnable AI-powered enhancement (required)
--providerAI provider (openai, anthropic, ollama)
--modelAI model to use
--admin-urlAdmin API base URL (default: http://localhost:4290)

Environment Variables:

VariableDescription
MOCKD_AI_PROVIDERDefault AI provider
MOCKD_AI_API_KEYAPI key for the provider
MOCKD_AI_MODELDefault model
MOCKD_AI_ENDPOINTCustom endpoint (for Ollama)

Examples:

Terminal window
# Enhance all mocks with AI-generated data
mockd enhance --ai
# Use specific provider
mockd enhance --ai --provider anthropic

Manage and test GraphQL endpoints.

Terminal window
mockd graphql <subcommand> [flags]

Subcommands:

  • validate - Validate a GraphQL schema file
  • query - Execute a query against a GraphQL endpoint

Validate a GraphQL schema file.

Terminal window
mockd graphql validate <schema-file>

Arguments:

ArgumentDescription
schema-filePath to the GraphQL schema file (.graphql or .gql)

Examples:

Terminal window
# Validate a schema file
mockd graphql validate schema.graphql
# Validate with full path
mockd graphql validate ./schemas/api.graphql

Execute a GraphQL query against an endpoint.

Terminal window
mockd graphql query <endpoint> <query> [flags]

Arguments:

ArgumentDescription
endpointGraphQL endpoint URL (e.g., http://localhost:4280/graphql)
queryGraphQL query string or @filename

Flags:

FlagShortDescriptionDefault
--variables-vJSON string of variables
--operation-oOperation name for multi-operation documents
--header-HAdditional headers (key:value,key2:value2)
--prettyPretty print outputtrue

Examples:

Terminal window
# Simple query
mockd graphql query http://localhost:4280/graphql "{ users { id name } }"
# Query with variables
mockd graphql query http://localhost:4280/graphql \
"query GetUser($id: ID!) { user(id: $id) { name } }" \
-v '{"id": "123"}'
# Query from file
mockd graphql query http://localhost:4280/graphql @query.graphql
# With custom headers
mockd graphql query http://localhost:4280/graphql "{ me { name } }" \
-H "Authorization:Bearer token123"

Manage chaos injection for fault testing.

Terminal window
mockd chaos <subcommand> [flags]

Subcommands:

  • enable - Enable chaos injection
  • disable - Disable chaos injection
  • status - Show current chaos configuration
  • profiles - List available chaos profiles
  • apply - Apply a named chaos profile

Enable chaos injection on the running mock server.

Terminal window
mockd chaos enable [flags]

Flags:

FlagShortDescriptionDefault
--admin-urlAdmin API base URLhttp://localhost:4290
--latency-lAdd random latency (e.g., “10ms-100ms”)
--error-rate-eError rate (0.0-1.0)
--error-codeHTTP error code to return500
--path-pPath pattern to apply chaos to (regex)
--probabilityProbability of applying chaos1.0

Examples:

Terminal window
# Enable random latency
mockd chaos enable --latency "50ms-200ms"
# Enable error injection with 10% rate
mockd chaos enable --error-rate 0.1 --error-code 503
# Apply chaos only to specific paths
mockd chaos enable --latency "100ms-500ms" --path "/api/.*"
# Combine latency and errors
mockd chaos enable --latency "10ms-50ms" --error-rate 0.05

Disable chaos injection on the running mock server.

Terminal window
mockd chaos disable [flags]

Flags:

FlagDescriptionDefault
--admin-urlAdmin API base URLhttp://localhost:4290

Examples:

Terminal window
mockd chaos disable

Show current chaos configuration.

Terminal window
mockd chaos status [flags]

Flags:

FlagDescriptionDefault
--admin-urlAdmin API base URLhttp://localhost:4290
--jsonOutput in JSON format

Examples:

Terminal window
mockd chaos status
mockd chaos status --json

List all available chaos profiles. Profiles are pre-built chaos configurations for common failure scenarios.

Terminal window
mockd chaos profiles [flags]

Flags:

FlagDescriptionDefault
--admin-urlAdmin API base URLhttp://localhost:4290
--jsonOutput in JSON format (includes full config for each profile)

Examples:

Terminal window
# List all profiles
mockd chaos profiles
# List with full configuration details
mockd chaos profiles --json

Output:

Available chaos profiles:
degraded Partially degraded service
dns-flaky Intermittent DNS resolution failures
flaky Unreliable service with random errors
mobile-3g Mobile 3G network conditions
offline Service completely down
overloaded Overloaded server under heavy load
rate-limited Rate-limited API
satellite Satellite internet simulation
slow-api Simulates slow upstream API
timeout Connection timeout simulation
Apply a profile with: mockd chaos apply <profile-name>

Apply a named chaos profile. This replaces the current chaos configuration with the profile’s settings.

Terminal window
mockd chaos apply <profile-name> [flags]

Arguments:

ArgumentDescription
profile-nameName of the chaos profile to apply (see mockd chaos profiles)

Flags:

FlagDescriptionDefault
--admin-urlAdmin API base URLhttp://localhost:4290

Examples:

Terminal window
# Simulate a flaky service (20% errors, 0-100ms latency)
mockd chaos apply flaky
# Simulate mobile network conditions (300-800ms, 50KB/s, 2% errors)
mockd chaos apply mobile-3g
# Take the service completely offline (100% 503 errors)
mockd chaos apply offline
# Disable when done
mockd chaos disable

Verify mock call counts and inspect invocations. Useful for integration testing where you need to prove your code makes the correct API calls.

Terminal window
mockd verify <subcommand> [flags]

Subcommands:

CommandDescription
statusShow call count and last-called time for a mock
checkAssert that a mock was called the expected number of times
invocationsList recorded request details for a mock
resetClear verification data (call counts and invocation history)

Show the call count and last-called timestamp for a specific mock.

Terminal window
mockd verify status <mock-id> [flags]

Flags:

FlagDescriptionDefault
--admin-urlAdmin API base URLhttp://localhost:4290
--jsonOutput in JSON format

Examples:

Terminal window
# Check how many times a mock was called
mockd verify status http_abc123
# Output:
# Mock: http_abc123
# Call count: 5
# Last called: 2026-02-26 19:30:45
# JSON output
mockd verify status http_abc123 --json

Assert call count expectations for a mock. Returns exit code 0 on pass and exit code 1 on failure — suitable for CI scripts and test automation.

At least one assertion flag is required.

Terminal window
mockd verify check <mock-id> [flags]

Flags:

FlagDescriptionDefault
--exactlyAssert mock was called exactly N times
--at-leastAssert mock was called at least N times
--at-mostAssert mock was called at most N times
--neverAssert mock was never called
--admin-urlAdmin API base URLhttp://localhost:4290
--jsonOutput in JSON format

Examples:

Terminal window
# Assert exactly 3 calls
mockd verify check http_abc123 --exactly 3
# PASS: called exactly 3 time(s) (called 3 time(s))
# Assert at least 1 call
mockd verify check http_abc123 --at-least 1
# PASS: called at least 1 time(s) (called 5 time(s))
# Assert never called (useful for negative testing)
mockd verify check http_abc123 --never
# FAIL: expected never called but was called 5 time(s)
# Assert a range (combine flags)
mockd verify check http_abc123 --at-least 1 --at-most 10
# Use in CI — non-zero exit code on failure
mockd verify check http_abc123 --exactly 1 || echo "Verification failed!"

List all recorded invocation details (method, path, timestamp, body) for a specific mock.

Terminal window
mockd verify invocations <mock-id> [flags]

Flags:

FlagDescriptionDefault
--admin-urlAdmin API base URLhttp://localhost:4290
--jsonOutput in JSON format

Examples:

Terminal window
# List all invocations for a mock
mockd verify invocations http_abc123
# Output:
# Mock: http_abc123 (3 invocation(s))
#
# [1] 19:30:45.123 GET /api/users at http_abc123
# [2] 19:31:02.456 POST /api/users at http_abc123
# Body: {"name":"Alice","email":"alice@example.com"}
# [3] 19:31:15.789 GET /api/users at http_abc123
# JSON output (full request details)
mockd verify invocations http_abc123 --json

Clear verification data (call counts and invocation history) for a specific mock or all mocks. Use between test runs for isolation.

Terminal window
mockd verify reset [mock-id] [flags]

Flags:

FlagDescriptionDefault
--allReset verification data for all mocks
--admin-urlAdmin API base URLhttp://localhost:4290
--jsonOutput in JSON format

Examples:

Terminal window
# Reset a specific mock
mockd verify reset http_abc123
# Verification data cleared for mock: http_abc123
# Reset all mocks (useful between test suites)
mockd verify reset --all
# All verification data cleared

Start a local mock server + admin API + cloud tunnel in one shot. This is the easiest way to expose mocks to the internet — everything starts with a single command.

If no --token flag or MOCKD_TOKEN environment variable is set, an anonymous tunnel token is fetched automatically (2-hour session, 100MB bandwidth).

Terminal window
mockd tunnel [flags]

Flags:

FlagShortDescriptionDefault
--port-pHTTP server port4280
--admin-portAdmin API port4290
--config-cPath to mock configuration file
--relayRelay server address (host or host:port)relay.mockd.io
--tokenAuthentication token (or set MOCKD_TOKEN env var)
--subdomain-sRequested subdomain (auto-assigned if empty)
--domainCustom domain (must be verified)
--auth-tokenRequire this token for incoming requests
--auth-basicRequire Basic Auth for incoming requests (format: user:pass)
--allow-ipsAllow only these IPs (comma-separated CIDR or IP)

The default relay is relay.mockd.io on port 443. If the relay address does not include a port, port 443 is appended automatically.

Authentication modes (--auth-token, --auth-basic, --allow-ips) are mutually exclusive — use at most one per tunnel.

Examples:

Terminal window
# Start mock server + tunnel (anonymous token, zero config)
mockd tunnel
# Start with a config file
mockd tunnel --config mocks.yaml
# Request a custom subdomain
mockd tunnel --config mocks.yaml --subdomain my-api
# Use an authenticated token
mockd tunnel --token $MOCKD_TOKEN --config mocks.yaml
# Protect the tunnel with a bearer token
mockd tunnel --config mocks.yaml --auth-token secret123
# Protect with Basic Auth
mockd tunnel --config mocks.yaml --auth-basic admin:password
# Restrict by IP range
mockd tunnel --config mocks.yaml --allow-ips "10.0.0.0/8,192.168.1.0/24"
# Use a custom relay and port
mockd tunnel --relay relay.yourcompany.com:4433 --token $TOKEN

Enable a tunnel on an already-running engine, making its mocks publicly accessible. The engine must be reachable via the admin API.

Terminal window
mockd tunnel enable [flags]

Flags:

FlagDescriptionDefault
--engineEngine IDlocal
--modeExposure mode: all, selected, noneall
--subdomainCustom subdomain (auto-assigned if empty)
--domainCustom domain
--auth-tokenRequire token for incoming requests
--auth-basicRequire Basic Auth (user:pass)
--allow-ipsRestrict by IP (comma-separated CIDRs)
--workspacesExpose only these workspaces (comma-separated)
--foldersExpose only these folders (comma-separated)
--mocksExpose only these mock IDs (comma-separated)
--typesExpose only these mock types (comma-separated)
--exclude-workspacesExclude these workspaces (comma-separated)
--exclude-foldersExclude these folders (comma-separated)
--exclude-mocksExclude these mock IDs (comma-separated)

Examples:

Terminal window
# Enable tunnel on the local engine (all mocks)
mockd tunnel enable
# Expose only HTTP mocks
mockd tunnel enable --types http
# Expose only specific workspaces
mockd tunnel enable --workspaces payments,users
# Expose all except certain folders
mockd tunnel enable --exclude-folders internal,debug
# Enable with authentication
mockd tunnel enable --auth-token my-secret-token
# Enable on a specific engine
mockd tunnel enable --engine my-engine-id

Disable the tunnel on an engine, removing public access.

Terminal window
mockd tunnel disable [flags]

Flags:

FlagDescriptionDefault
--engineEngine IDlocal

Examples:

Terminal window
# Disable tunnel on the local engine
mockd tunnel disable
# Disable on a specific engine
mockd tunnel disable --engine my-engine-id

Show detailed tunnel status for an engine, including public URL, transport, session ID, and connection time.

Terminal window
mockd tunnel status [flags]

Flags:

FlagDescriptionDefault
--engineEngine IDlocal

Examples:

Terminal window
# Check tunnel status
mockd tunnel status
# Check status on a specific engine
mockd tunnel status --engine my-engine-id

Alias for mockd tunnel disable. Disables the tunnel on an engine.

Terminal window
mockd tunnel stop [flags]

Flags:

FlagDescriptionDefault
--engineEngine IDlocal

List all active tunnels across all engines.

Terminal window
mockd tunnel list

Displays a table of active tunnels with engine ID, name, public URL, status, transport, and uptime.

Examples:

Terminal window
mockd tunnel list

Preview which mocks would be exposed through a tunnel without actually enabling it. Useful for verifying filter settings before going live.

Terminal window
mockd tunnel preview [flags]

Flags:

FlagDescriptionDefault
--engineEngine IDlocal
--modeExposure mode: all, selected, noneall
--workspacesExpose only these workspaces (comma-separated)
--foldersExpose only these folders (comma-separated)
--mocksExpose only these mock IDs (comma-separated)
--typesExpose only these mock types (comma-separated)
--exclude-workspacesExclude these workspaces (comma-separated)
--exclude-foldersExclude these folders (comma-separated)
--exclude-mocksExclude these mock IDs (comma-separated)

Examples:

Terminal window
# Preview all mocks that would be exposed
mockd tunnel preview
# Preview only HTTP mocks
mockd tunnel preview --types http
# Preview with exclusions
mockd tunnel preview --exclude-workspaces internal