CLI Reference
MockForge provides a comprehensive command-line interface for managing mock servers and generating test data. This reference covers all available commands, options, and usage patterns.
Global Options
All MockForge commands support the following global options:
mockforge-cli [OPTIONS] <COMMAND>
Global Options
-h, --help: Display help information
Commands
proxy - Forward Traffic and Record Contract Violations
mockforge proxy --upstream http://127.0.0.1:8080 --port 9081 \
--spec api.yaml --validate-conformance
The proxy listens on 127.0.0.1:9081 by default. --host and --port
override the listener; --upstream (alias --target) selects the upstream.
The spec can be JSON or YAML. MOCKFORGE_PROXY_SPEC and
MOCKFORGE_PROXY_VALIDATE_CONFORMANCE=true are the environment equivalents.
Invalid or missing specs fail startup when validation is enabled.
Validation is observational: invalid requests still reach the upstream, and
upstream status codes, redirect responses, and response bytes are preserved.
Inspect the shared conformance buffer at
GET /__mockforge/api/conformance/violations?limit=50 on the proxy listener;
DELETE on that path clears it. These routes are enabled with validation.
The usual MOCKFORGE_CONFORMANCE_BUFFER_SIZE and
MOCKFORGE_CONFORMANCE_BUFFER_UNIQUE settings govern the buffer.
--validate-conformance-strict also enables validation and rejects invalid
requests before forwarding them. An upstream response that violates its
declared contract produces a 502 response. Set
MOCKFORGE_PROXY_VALIDATE_CONFORMANCE_STRICT=true for the same policy.
Ctrl-C and SIGTERM stop the listener gracefully.
Conformance response-schema checks currently cover declared JSON schemas.
Local response references, exact status codes, status ranges, and defaults
are supported. Schema selection uses the upstream Content-Type, including
JSON suffix types such as application/problem+json and declared media
wildcards. Other declared formats pass through without JSON schema checks;
missing or undeclared response media types are violations. HEAD, 204 and 304
responses have no representation body to validate. Paths absent from the
spec pass through without validation.
Validation decodes gzip, deflate, Brotli, and Zstandard on a separate copy; forwarded bodies and repeated response headers remain unchanged. Encoded and decoded validation copies are limited to 16 MiB and four encoding layers. Invalid, unsupported, or oversized encoded content is reported as a violation. Passive mode still forwards it; strict mode rejects invalid requests or returns 502 for invalid responses.
serve - Start Mock Servers
The primary command for starting MockForge’s mock servers with support for HTTP, WebSocket, and gRPC protocols.
mockforge-cli serve [OPTIONS]
Server Options
Port Configuration:
--http-port <PORT>: HTTP server port (default: 3000)--ws-port <PORT>: WebSocket server port (default: 3001)--grpc-port <PORT>: gRPC server port (default: 50051)
API Specification:
--spec <PATH>: OpenAPI spec file for HTTP server (JSON or YAML format)
Configuration:
-c, --config <PATH>: Path to configuration file
Admin UI Options
Admin UI Control:
--admin: Enable admin UI--admin-port <PORT>: Admin UI port (default: 9080)--admin-embed: Force embedding Admin UI under HTTP server--admin-mount-path <PATH>: Explicit mount path for embedded Admin UI (implies--admin-embed)--admin-standalone: Force standalone Admin UI on separate port (overrides embed)--disable-admin-api: Disable Admin API endpoints (UI loads but API routes are absent)
Validation Options
Request Validation:
--validation <MODE>: Request validation mode (default: enforce)off: Disable validationwarn: Log warnings but allow requestsenforce: Reject invalid requests
--aggregate-errors: Aggregate request validation errors into JSON array--validate-responses: Validate responses (warn-only)--validation-status <CODE>: Validation error HTTP status code (default: 400)
Response Processing
Template Expansion:
--response-template-expand: Expand templating tokens in responses/examples
Chaos Engineering
Latency Simulation:
--latency-enabled: Enable latency simulation
Failure Injection:
--failures-enabled: Enable failure injection
Examples
Basic HTTP Server:
mockforge-cli serve --spec examples/openapi-demo.json --http-port 3000
Full Multi-Protocol Setup:
mockforge-cli serve \
--spec examples/openapi-demo.json \
--http-port 3000 \
--ws-port 3001 \
--grpc-port 50051 \
--admin \
--admin-port 9080 \
--response-template-expand
Development Configuration:
mockforge-cli serve \
--config demo-config.yaml \
--validation warn \
--response-template-expand \
--latency-enabled
Production Configuration:
mockforge-cli serve \
--config production-config.yaml \
--validation enforce \
--admin-standalone
init - Initialize New Project
Create a new MockForge project with a template configuration file.
mockforge-cli init [OPTIONS] <NAME>
Arguments
<NAME>: Project name or directory path- Use
.to initialize in the current directory - Use a project name to create a new directory
- Use
Options
--no-examples: Skip creating example files (only createmockforge.yaml)
Examples
# Create a new project in a new directory
mockforge-cli init my-mock-api
# Initialize in the current directory
mockforge-cli init .
# Initialize without examples
mockforge-cli init my-project --no-examples
What Gets Created
-
mockforge.yaml: Main configuration file with:
- HTTP, WebSocket, gRPC server configurations
- Admin UI settings
- Core features (latency, failures, overrides)
- Observability configuration
- Data generation settings
- Logging configuration
-
examples/ directory (unless
--no-examples):openapi.json: Sample OpenAPI specification- Example data files
See Also
config - Configuration Management
Validate and manage MockForge configuration files.
mockforge-cli config <SUBCOMMAND>
Subcommands
validate - Validate Configuration File
Validate a MockForge configuration file for syntax and structure errors.
mockforge-cli config validate [OPTIONS]
Options:
--config <PATH>: Path to config file to validate- If omitted, auto-discovers
mockforge.yamlormockforge.ymlin current and parent directories
- If omitted, auto-discovers
What Gets Validated:
- YAML syntax and structure
- File existence
- HTTP endpoints count
- Request chains count
- Missing sections (warnings)
Examples:
# Validate config in current directory
mockforge-cli config validate
# Validate specific config file
mockforge-cli config validate --config my-config.yaml
# Validate before starting server
mockforge-cli config validate && mockforge-cli serve
Output Example:
🔍 Validating MockForge configuration...
📄 Checking configuration file: mockforge.yaml
✅ Configuration is valid
📊 Summary:
Found 5 HTTP endpoints
Found 2 chains
⚠️ Warnings:
- No WebSocket configuration found
Common Issues:
- Invalid YAML syntax: Fix indentation, quotes, or structure
- File not found: Check path or run
mockforge init - Missing sections: Add HTTP, admin, or other required sections
Note: Current validation is basic (syntax, structure, counts). For comprehensive field validation, see the Configuration Validation Guide.
See Also
data - Generate Synthetic Data
Generate synthetic test data using various templates and schemas.
mockforge-cli data <SUBCOMMAND>
Subcommands
template - Generate from Built-in Templates
Generate data using MockForge’s built-in data generation templates.
mockforge-cli data template [OPTIONS]
Options:
--count <N>: Number of items to generate (default: 1)--format <FORMAT>: Output format (json, yaml, csv)--template <NAME>: Template name (user, product, order, etc.)--output <PATH>: Output file path
Examples:
# Generate 10 user records as JSON
mockforge-cli data template --template user --count 10 --format json
# Generate product data to file
mockforge-cli data template --template product --count 50 --output products.json
schema - Generate from JSON Schema
Generate data conforming to a JSON Schema specification.
mockforge-cli data schema [OPTIONS] <SCHEMA>
Parameters:
<SCHEMA>: Path to JSON Schema file
Options:
--count <N>: Number of items to generate (default: 1)--format <FORMAT>: Output format (json, yaml)--output <PATH>: Output file path
Examples:
# Generate data from user schema
mockforge-cli data schema --count 5 user-schema.json
# Generate and save to file
mockforge-cli data schema --count 100 --output generated-data.json api-schema.json
open-api - Generate from OpenAPI Spec
Generate mock data based on OpenAPI specification schemas.
mockforge-cli data open-api [OPTIONS] <SPEC>
Parameters:
<SPEC>: Path to OpenAPI specification file
Options:
--endpoint <PATH>: Specific endpoint to generate data for--method <METHOD>: HTTP method (get, post, put, delete)--count <N>: Number of items to generate (default: 1)--format <FORMAT>: Output format (json, yaml)--output <PATH>: Output file path
Examples:
# Generate data for all endpoints in OpenAPI spec
mockforge-cli data open-api api-spec.yaml
# Generate data for specific endpoint
mockforge-cli data open-api --endpoint /users --method get --count 20 api-spec.yaml
# Generate POST request body data
mockforge-cli data open-api --endpoint /users --method post api-spec.yaml
admin - Admin UI Server
Start the Admin UI as a standalone server without the main mock servers.
mockforge-cli admin [OPTIONS]
Options
--port <PORT>: Server port (default: 9080)
Examples
# Start admin UI on default port
mockforge-cli admin
# Start admin UI on custom port
mockforge-cli admin --port 9090
bench - OpenAPI-driven Load Testing
Generate and run a k6 load test from an OpenAPI spec.
mockforge bench --spec api.yaml --target http://localhost:3000 [OPTIONS]
Common Options
-s, --spec <PATH>— OpenAPI spec file (repeatable for multi-spec mode).--spec-dir <DIR>— Directory of specs (auto-discovered).-t, --target <URL>— Target server URL.-d, --duration <SECS>— Run length (default: 60).--vus <N>— Virtual users (default: 10).--scenario <NAME>—constant|ramp-up|spike|stress|soak.--operations <FILTER>— Comma-separated operation filter (e.g."GET /users,POST /orders").--auth <HEADER>— Authorization header value (e.g."Bearer $TOKEN").--headers <KV>— Comma-separated extra headers (e.g."X-Tenant: a,X-Region: b").--threshold-percentile <P>/--threshold-ms <N>— Latency SLO.--max-error-rate <RATE>— Error-rate SLO (0.01= 1%).--generate-only— Write the k6 script without running it.--script-output <PATH>— Where to write the generated script.--targets-file <PATH>— Multi-target mode (one URL per line).--max-concurrency <N>— Parallel target limit (default: 10).--insecure— Skip TLS verification (test self-signed certs).--chunked-request-bodies— AddTransfer-Encoding: chunkedto every k6 request body. NOTE: k6 runs on Go’snet/http, which may still sendContent-Lengthbased on body type. For guaranteed wire chunking usebench-chunkedinstead.
See the Load Testing chapter for the full options surface (security testing, OWASP API top 10, conformance mode, data-driven testing) and end-to-end examples.
bench-chunked - Native Chunked Traffic Generator
Send guaranteed Transfer-Encoding: chunked request bodies via hyper. Useful
when bench --chunked-request-bodies falls back to Content-Length (Go’s
transport heuristics) and you need real chunked traffic on the wire.
mockforge bench-chunked --target http://localhost:3000/upload [OPTIONS]
Options
--target <URL>— Target URL. Required unless--targets-fileis given.--targets-file <FILE>— Bench every target in the file in parallel (same text/JSON format asbench --targets-file, including per-targetauth,headers,spec). Mutually exclusive with--target.--max-concurrency <N>— Max targets benched at once with--targets-file(default: 10).--method <METHOD>—POST(default),PUT, orPATCH.-c, --concurrency <N>— Concurrent workers per target (default: 10).-d, --duration <DURATION>— Run length, per operation with--spec(default: 30s).--chunk-size-bytes <N>— Bytes per chunk (default: 1024).--total-size-bytes <N>— Total body size per request (default: 1048576 = 1 MiB).--chunk-interval-ms <MS>— Sleep between chunks (default: 0 = back-to-back).--header <NAME: VALUE>— Extra header (repeatable).--insecure— Skip TLS verification.--rps <N>— Cap on request starts per second, per target.--cps— Open a new connection for every request (connections/s = requests/s).--rounds <N>/--repeat-until <DURATION>— Campaign: re-run the whole pass; rounds go to<output>/round_N/, stats tocampaign.jsonlandround-summaries/.--keep-rounds <N>— Campaign only: keep the newest Nround_*dirs.
Reports req/s, p50/p95/p99 latency, and a status-code distribution at the end.
git-watch - Watch a Git Repo for Spec Changes
Monitor a Git repository for changes to OpenAPI / spec files and automatically reload the local mock server when they change. Useful for teams that store specs in a separate repo from their mock config.
mockforge git-watch https://github.com/user/api-specs \
--reload-command "mockforge serve --spec"
Common options: --branch, --poll-interval, --auth-token (for private
repos), --cache-dir, --spec-paths (comma-separated globs to watch).
contract-sync - Sync Contracts from a Git Repo
One-shot pull of OpenAPI / contract specs from a Git repository, with an optional report comparing the new spec against the current mock config.
mockforge contract-sync https://github.com/user/api-specs \
--update --output report.md
Use --update to overwrite local copies; omit it for a dry-run report.
Pairs well with CI — fail the build if the upstream contract drifted from
what the mock returns.
validate-fixtures - Validate Fixture Files
Lint a directory or single file of fixture data against MockForge’s schema. Useful pre-commit guard for repos that check fixtures into source control.
# Validate every fixture in a directory
mockforge validate-fixtures --dir ./fixtures
# Validate one file
mockforge validate-fixtures --file ./fixtures/users.json
# Verbose mode — show per-fixture details, not just failures
mockforge validate-fixtures --dir ./fixtures --verbose
Exit code 0 on clean, non-zero on any validation failure.
mockforge-tui - Terminal Dashboard (separate binary)
Live dashboard in the terminal showing server status, system metrics (current and lifetime peak CPU / memory / error rate), request stats, and recent logs. Auto-refreshes every 2 s.
mockforge-tui
Optionally pair with MOCKFORGE_METRICS_LOG_FILE=path.csv to also append a
persistent CSV record while the server runs.
bench-pipeline - HTTP Pipelining Load Test
Load-test a target with HTTP pipelining: synthetic request bodies (json / xml / urlencoded / multipart) are written back-to-back per connection before any response is read.
mockforge bench-pipeline --target http://localhost:3000/api \
--content-type json --body-size 500KB --pipeline-depth 16 \
--connections 8 --duration 30s
Options
--target <url>(required): plain-http://target URL.--method <method>: HTTP method; pipelining is only meaningful with bodies, so the default isPOST.--content-type <flavour>:json|xml|urlencoded|multipart(defaultjson).--body-size <size>: exact body size per request — bare bytes or KB/MB/GB / KiB/MiB/GiB (default1KB).--pipeline-depth <n>: requests in flight per connection before reading responses (default16).--connections <n>: concurrent connections (default8).
verify-mocks - Mock Fidelity / Drift Detection
Compare the mocks generated from an OpenAPI spec against real captured traffic in a recorder database, and report drift: endpoints whose mocks no longer match how clients actually call them.
mockforge verify-mocks --spec openapi.json --capture-db recorder.sqlite
To compare the OpenAPI definition used to generate an existing mock against
its current source specification, use --mock-spec. Both inputs can be supplied
to check definitions and captured traffic together:
mockforge verify-mocks --spec upstream-current.yaml --mock-spec mock-generated-from.yaml \
--fail-on-drift --output fidelity.json
The JSON report’s definition.routes includes every method/path with a
verified or drift-detected status. Its change is added, removed,
changed, or unchanged, from the mock to the source. Each delta includes a
JSON-pointer location and the corresponding mock and source values.
Changes to nested schema types, properties, required fields, constraints,
parameters, request bodies and responses are reported. Local references are
resolved, including recursive schemas. Unresolved/external references and
excessive expansion fail explicitly. Documentation text and the ordering of
required fields, enum values and parameters do not count as drift.
Options
--spec <path>(required): OpenAPI spec the mocks were generated from (3.x natively; Swagger 2.0 is up-converted automatically).--capture-db <path>: recorder SQLite database holding captured traffic (whatmockforge serve --recorderwrites; the default path is./mockforge-recordings.db).--mock-spec <path>: OpenAPI definition used by the mock, compared against the current source in--spec.--fixtures <path>: HTTP replay fixture JSON file or directory. Checks every selected fixture’s route, status and JSON response schema, and reports source operations with no fixture. See the fixture format and scope.
Supply at least one of --capture-db, --mock-spec or --fixtures. They can be combined.
--limit <n>: maximum recent HTTP exchanges to evaluate, newest first (positive integer; default500). Other protocols do not consume this limit.--fail-on-drift: exit with code 1 when any drift is found — use as a CI gate.--output <path>: write the structured drift report as JSON.--record: keep this run’s result as the project’s latest verification, in.mockforge/reports/verify-mocks.jsonbeside the project’s configuration file (or in the current directory without one).mockforge statusreports it. A run with no recorded traffic is kept with outcomeno_traffic.
status - Project State, Read Only
Report a project’s MockForge state without starting or writing anything:
which configuration file serve would use (discovered from the directory
exactly as serve does), the HTTP port and OpenAPI spec it declares, whether
a MockForge server answers on that port, and the last verify-mocks --record
result.
mockforge status
mockforge status --dir ./services/api --format json
Options
--dir <path>: the project directory (default: the current directory).--format text|json:jsonprints one document and nothing else on stdout.--timeout-ms <n>: how long to wait for the server (default1000).
The server probe asks the management API (GET /__mockforge/api/health), which
a spec’s own /health route cannot shadow, then reads uptime from
/__mockforge/api/stats and the version from /__mockforge/api/config. The
probe uses the declared port; a server started with --http-port elsewhere is
not found. 0.0.0.0 and :: are probed on 127.0.0.1.
The JSON document (schema_version 2):
{
"schema_version": 2,
"version": "0.3.238",
"dir": "/abs/project",
"config": { "path": "/abs/project/mockforge.yaml", "error": null },
"http": { "enabled": true, "host": "0.0.0.0", "port": 3000, "openapi_spec": "./examples/openapi.json" },
"admin": { "enabled": true, "port": 9080 },
"server": {
"url": "http://127.0.0.1:3000/__mockforge/api/health",
"reachable": true, "status": "healthy", "version": "0.3.238",
"uptime_seconds": 12, "error": null
},
"verification": {
"schema_version": 2, "recorded_at": "2026-10-26T10:30:43Z",
"mockforge_version": "0.3.238", "spec": "examples/openapi.json",
"capture_db": "captures.db", "outcome": "faithful",
"exchanges_checked": 8, "endpoints_with_drift": 0, "endpoints_unverified": 0,
"unmatched_real_paths": 4, "findings": []
}
}
config is null when no configuration file exists; config.error names why an
existing one cannot be loaded, and then http, admin and server are null.
server is null when HTTP is disabled. verification.outcome is faithful,
drift, unverified or no_traffic. unverified means response media could
not be checked, without a proven contract violation. Proven drift takes
precedence when a run contains both. Status and newly recorded verifications
use schema 2 for this additional outcome; schema-1 verification files remain
readable with endpoints_unverified defaulting to zero. Fields may be added
within a schema; a change that breaks readers raises schema_version.
validate-spec - OpenAPI Validation, Read Only
Validate one local OpenAPI 2.0 or 3.x document (JSON or YAML) with the
validator generate uses, without generating, starting or writing anything.
Only a local file is read; a URL is refused, not fetched.
mockforge validate-spec api.yaml
mockforge validate-spec ./specs/openapi.json --format json
Options
<spec>(required): the OpenAPI document.--format text|json:jsonprints one document and nothing else on stdout.
Exit codes: 0 when the document is valid (warnings allowed), 1 when it has
errors, 2 when it could not be read as an OpenAPI document. The JSON document
is printed in every case.
The JSON document (schema_version 1):
{
"schema_version": 1,
"mockforge_version": "0.3.237",
"spec": "api.json",
"openapi": "3.1",
"valid": false,
"errors": 1,
"warnings": 0,
"findings": [
{
"severity": "error", "rule": "MISSING_INFO", "path": "/info",
"message": "Missing 'info' section in OpenAPI 3.1 spec",
"suggestion": "Add an 'info' section with 'title' and 'version' fields"
}
]
}
openapi is "2.0", "3.0", "3.1", or null when the document is not
OpenAPI. A document that could not be validated has one error finding whose
rule is UNREADABLE, INVALID_SYNTAX or NOT_OPENAPI. path is a JSON
pointer when the validator names the field.
Capture databases are opened read-only and must already exist. An empty HTTP capture is not drift: the command reports that no traffic was recorded and exits successfully, and with --record it stores a no_traffic verification. Unknown endpoints, missing responses, undeclared statuses and JSON-schema violations count as drift. Exact status declarations take precedence over status ranges and the default response; local response references are resolved before schema validation.
Capture databases are opened read-only and must already exist. Empty HTTP captures fail rather than report a passing check. Unknown endpoints, missing responses, undeclared statuses and JSON-schema violations count as drift. Exact status declarations take precedence over status ranges and the default response; local response references are resolved before schema validation.
sync - Workspace Synchronization Daemon
Start a background daemon that monitors a workspace directory for file changes and automatically syncs them to MockForge workspaces.
mockforge-cli sync [OPTIONS]
Options
Required:
--workspace-dir <PATH>or-w <PATH>: Workspace directory to monitor for changes
Optional:
--config <PATH>or-c <PATH>: Configuration file path for sync settings
How It Works
The sync daemon provides bidirectional synchronization between workspace files and MockForge’s internal workspace storage:
- File Monitoring: Watches for
.yamland.ymlfiles in the workspace directory - Automatic Import: When files are created or modified, they’re automatically imported into the workspace
- Real-time Updates: Changes are detected and processed immediately
- Visual Feedback: Clear console output shows what’s happening in real-time
File Requirements:
- Only
.yamland.ymlfiles are monitored - Hidden files (starting with
.) are ignored - Files must be valid MockRequest YAML format
What You’ll See:
- File creation notifications with import status
- File modification notifications with update status
- File deletion notifications (files are not auto-deleted from workspace)
- Error messages if imports fail
- Real-time feedback for all sync operations
Examples
Basic Usage:
# Start sync daemon for a workspace directory
mockforge-cli sync --workspace-dir ./my-workspace
# Use short form
mockforge-cli sync -w ./my-workspace
# With custom config
mockforge-cli sync --workspace-dir /path/to/workspace --config sync-config.yaml
Git Integration:
# Monitor a Git repository directory
mockforge-cli sync --workspace-dir /path/to/git/repo/workspaces
# Changes you make in Git will automatically sync to MockForge
# Perfect for team collaboration via Git
Development Workflow:
# 1. Start the sync daemon in one terminal
mockforge-cli sync --workspace-dir ./workspaces
# 2. In another terminal, edit workspace files
vim ./workspaces/my-request.yaml
# 3. Save the file - it will automatically import to MockForge
# You'll see output like:
# 🔄 Detected 1 file change in workspace 'default'
# 📝 Modified: my-request.yaml
# ✅ Successfully updated
Example Output
When you start the sync daemon, you’ll see:
🔄 Starting MockForge Sync Daemon...
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📁 Workspace directory: ./my-workspace
ℹ️ What the sync daemon does:
• Monitors the workspace directory for .yaml/.yml file changes
• Automatically imports new or modified request files
• Syncs changes bidirectionally between files and workspace
• Skips hidden files (starting with .)
🔍 Monitoring for file changes...
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Sync daemon started successfully!
💡 Press Ctrl+C to stop
📂 Monitoring workspace 'default' in directory: ./my-workspace
When files change, you’ll see:
🔄 Detected 1 file change in workspace 'default'
➕ Created: new-endpoint.yaml
✅ Successfully imported
🔄 Detected 2 file changes in workspace 'default'
📝 Modified: user-api.yaml
✅ Successfully updated
🗑️ Deleted: old-endpoint.yaml
ℹ️ Auto-deletion from workspace is disabled
If errors occur:
🔄 Detected 1 file change in workspace 'default'
📝 Modified: invalid-file.yaml
⚠️ Failed to import: File is not a recognized format (expected MockRequest YAML)
Stopping the Daemon
Press Ctrl+C to gracefully stop the sync daemon:
^C
🛑 Received shutdown signal
⏹️ Stopped monitoring workspace 'default' in directory: ./my-workspace
👋 Sync daemon stopped
Best Practices
Version Control:
# Use sync with Git for team collaboration
cd /path/to/git/repo
mockforge-cli sync --workspace-dir ./workspaces
# Team members can push/pull changes
# The sync daemon will automatically import updates
Development Workflow:
# Keep sync daemon running during development
# Edit files in your favorite editor
# Changes automatically sync to MockForge
# Perfect for file-based workflows
Directory Organization:
# Organize workspace files in subdirectories
workspaces/
├── api-v1/
│ ├── users.yaml
│ └── products.yaml
├── api-v2/
│ └── users.yaml
└── internal/
└── admin.yaml
# All .yaml files will be monitored
mockforge-cli sync --workspace-dir ./workspaces
Troubleshooting
Files not importing:
- Ensure files have
.yamlor.ymlextension - Check that files are valid MockRequest YAML format
- Look for error messages in the console output
- Verify files are not hidden (don’t start with
.)
Permission errors:
- Ensure MockForge has read access to the workspace directory
- Check file permissions:
ls -la workspace-dir/
Changes not detected:
- The sync daemon uses filesystem notifications
- Some network filesystems may not support change notifications
- Try editing the file locally rather than over a network mount
Enable debug logging:
RUST_LOG=mockforge_core::sync_watcher=debug mockforge-cli sync --workspace-dir ./workspace
Configuration File Format
MockForge supports YAML configuration files that can be used instead of command-line options.
Basic Configuration Structure
# Server configuration
server:
http_port: 3000
ws_port: 3001
grpc_port: 50051
# API specification
spec: examples/openapi-demo.json
# Admin UI configuration
admin:
enabled: true
port: 9080
embedded: false
mount_path: "/admin"
standalone: true
disable_api: false
# Validation settings
validation:
mode: enforce
aggregate_errors: false
validate_responses: false
status_code: 400
# Response processing
response:
template_expand: true
# Chaos engineering
chaos:
latency_enabled: false
failures_enabled: false
# Protocol-specific settings
grpc:
proto_dir: "proto/"
enable_reflection: true
websocket:
replay_file: "examples/ws-demo.jsonl"
Configuration Precedence
Configuration values are applied in the following order (later sources override earlier ones):
- Default values (compiled into the binary)
- Configuration file (
-c/--configoption) - Environment variables
- Command-line arguments (highest priority)
Environment Variables
All configuration options can be set via environment variables using the MOCKFORGE_ prefix:
# Server ports
export MOCKFORGE_HTTP_PORT=3000
export MOCKFORGE_WS_PORT=3001
export MOCKFORGE_GRPC_PORT=50051
# Admin UI
export MOCKFORGE_ADMIN_ENABLED=true
export MOCKFORGE_ADMIN_PORT=9080
# WebSocket settings
export MOCKFORGE_WS_REPLAY_FILE=examples/ws-demo.jsonl
# gRPC settings
export MOCKFORGE_PROTO_DIR=proto/
# Data generation (RAG)
export MOCKFORGE_RAG_ENABLED=true
export MOCKFORGE_RAG_PROVIDER=openai
export MOCKFORGE_RAG_API_KEY=your-api-key
For the full env-var surface, see Environment Variables. Plugin system, admin auth, encryption, sync daemon, and validation toggles are configured via YAML rather than env vars; see the relevant chapter for each.
Exit Codes
MockForge uses standard exit codes:
- 0: Success
- 1: General error
- 2: Configuration error
- 3: Validation error
- 4: File I/O error
- 5: Network error
Logging
MockForge provides configurable logging output to help with debugging and monitoring.
Log Levels
error: Only error messageswarn: Warnings and errorsinfo: General information (default)debug: Detailed debugging informationtrace: Very verbose tracing information
Log Configuration
# Set log level via environment variable
export RUST_LOG=mockforge=debug
# Or via configuration file
logging:
level: debug
format: json
Log Output
Logs include structured information about:
- HTTP requests/responses
- WebSocket connections and messages
- gRPC calls and streaming
- Configuration loading
- Template expansion
- Validation errors
Examples
Complete Development Setup
# Start all servers with admin UI
mockforge-cli serve \
--spec examples/openapi-demo.json \
--http-port 3000 \
--ws-port 3001 \
--grpc-port 50051 \
--admin \
--admin-port 9080 \
--response-template-expand \
--validation warn
CI/CD Testing Pipeline
#!/bin/bash
# test-mockforge.sh
# Start MockForge in background
mockforge-cli serve --spec api-spec.yaml --http-port 3000 &
SERVER_PID=$!
# Wait for server to start
sleep 5
# Run API tests
npm test
# Generate test data
mockforge-cli data open-api --endpoint /users --count 100 api-spec.yaml > test-users.json
# Stop MockForge
kill $SERVER_PID
Load Testing Setup
#!/bin/bash
# load-test-setup.sh
# Start MockForge with minimal validation for performance
MOCKFORGE_RESPONSE_TEMPLATE_EXPAND=false \
mockforge-cli serve \
--spec load-test-spec.yaml \
--http-port 3000 \
--validation off
# Now run your load testing tool against localhost:3000
# Example: hey -n 10000 -c 100 http://localhost:3000/api/test
Docker Integration
# Run MockForge in Docker with CLI commands
docker run --rm -v $(pwd)/examples:/examples \
mockforge \
serve --spec /examples/openapi-demo.json --http-port 3000
Troubleshooting
Common Issues
Server won’t start:
# Check if ports are available
lsof -i :3000
lsof -i :3001
# Try different ports
mockforge-cli serve --http-port 3001 --ws-port 3002
Configuration not loading:
# Validate YAML syntax
yamllint config.yaml
# Check file permissions
ls -la config.yaml
OpenAPI spec not found:
# Verify file exists and path is correct
ls -la examples/openapi-demo.json
# Use absolute path
mockforge-cli serve --spec /full/path/to/examples/openapi-demo.json
Template expansion not working:
# Ensure template expansion is enabled
mockforge-cli serve --response-template-expand --spec api-spec.yaml
Debug Mode
Run with debug logging for detailed information:
RUST_LOG=mockforge=debug mockforge-cli serve --spec api-spec.yaml
Health Checks
Test basic functionality:
# HTTP health check
curl http://localhost:3000/health
# WebSocket connection test
websocat ws://localhost:3001/ws
# gRPC service discovery
grpcurl -plaintext localhost:50051 list
This CLI reference provides comprehensive coverage of MockForge’s command-line interface. For programmatic usage, see the Rust API Reference.