Configuration Reference
Complete reference for mockd configuration files.
File Format
Section titled “File Format”mockd supports YAML and JSON configuration files. The version field is required.
mockd serve --config mocks.yamlmockd serve --config mocks.jsonTop-Level Structure
Section titled “Top-Level Structure”version: "1.0"
mocks: - id: string name: string type: http | websocket | graphql | grpc | mqtt | soap enabled: boolean http: { ... } # if type: http websocket: { ... } # if type: websocket graphql: { ... } # if type: graphql grpc: { ... } # if type: grpc mqtt: { ... } # if type: mqtt soap: { ... } # if type: soap
serverConfig: { ... } # Optional server settingsstatefulResources: [ ... ] # Optional CRUD resources| Field | Type | Required | Description |
|---|---|---|---|
version | string | Yes | Config version (e.g., "1.0") |
mocks | array | Yes | Mock definitions |
serverConfig | object | No | Server configuration |
statefulResources | array | No | Stateful CRUD resources |
Mock Definition
Section titled “Mock Definition”All mock types share common fields:
mocks: - id: unique-mock-id name: "Human-readable name" description: "Optional description" type: http enabled: true parentId: "" # Folder ID (optional) metaSortKey: 0 # Sort order (optional) http: { ... } # Type-specific configurationCommon Fields
Section titled “Common Fields”| Field | Type | Required | Default | Description |
|---|---|---|---|---|
id | string | Yes | Unique identifier | |
type | string | Yes | Mock type: http, websocket, graphql, grpc, mqtt, soap | |
name | string | No | Human-readable name | |
description | string | No | Longer description | |
enabled | boolean | No | true | Whether mock is active |
parentId | string | No | Folder ID for organization | |
metaSortKey | number | No | Manual ordering within folder |
HTTP Mock
Section titled “HTTP Mock”HTTP mocks match incoming requests and return configured responses.
mocks: - id: get-users name: Get Users type: http enabled: true http: priority: 0 matcher: method: GET path: /api/users headers: Authorization: "Bearer *" queryParams: status: active response: statusCode: 200 headers: Content-Type: application/json body: '{"users": []}' delayMs: 100HTTP Spec Fields
Section titled “HTTP Spec Fields”| Field | Type | Description |
|---|---|---|
priority | integer | Match priority (higher = matches first) |
matcher | object | Request matching criteria |
response | object | Response definition |
sse | object | Server-Sent Events config (instead of response) |
chunked | object | Chunked transfer config (instead of response) |
validation | object | Request validation (see Validation) |
HTTP Matcher
Section titled “HTTP Matcher”| Field | Type | Description |
|---|---|---|
method | string | HTTP method (GET, POST, PUT, DELETE, PATCH, etc.) |
path | string | Exact URL path |
pathPattern | string | Regex pattern for URL path |
headers | map | Header matchers (key: regex pattern) |
queryParams | map | Query parameter matchers (key: regex pattern) |
bodyContains | string | Body must contain this string |
bodyEquals | string | Body must equal this string exactly |
bodyPattern | string | Body must match this regex pattern |
bodyJsonPath | map | JSONPath matchers (path: expected value) |
mtls | object | mTLS client certificate matching |
Path Patterns
Section titled “Path Patterns”# Exact matchpath: /api/users
# Path parameterspath: /api/users/{id}path: /api/{resource}/{id}
# Greedy path parameter (matches multiple segments)path: /api/files/{path:.*}
# Regex patternpathPattern: "/api/users/[0-9]+"HTTP Response
Section titled “HTTP Response”| Field | Type | Default | Description |
|---|---|---|---|
statusCode | integer | 200 | HTTP status code |
headers | map | {} | Response headers |
body | string | "" | Response body (supports templates) |
bodyFile | string | Load body from file path | |
delayMs | integer | 0 | Response delay in milliseconds |
mTLS Matching
Section titled “mTLS Matching”matcher: mtls: cn: "client.example.com" # Common Name pattern ou: "Engineering" # Organizational Unit pattern o: "Example Corp" # Organization pattern san: dns: "*.example.com" # DNS SAN pattern email: "*@example.com" # Email SAN pattern ip: "10.0.0.*" # IP SAN patternSSE (Server-Sent Events)
Section titled “SSE (Server-Sent Events)”http: matcher: method: GET path: /events sse: events: - type: update data: '{"status": "connected"}' id: "1" - type: update data: '{"status": "processing"}' delay: 1000 timing: fixedDelay: 1000 # ms between events initialDelay: 0 # ms before first event lifecycle: maxEvents: 10 # max events before closing timeout: 60000 # connection timeout ms keepaliveInterval: 15000 # keepalive interval ms resume: enabled: true # support Last-Event-ID bufferSize: 100 # events to bufferChunked Transfer
Section titled “Chunked Transfer”http: matcher: method: GET path: /stream chunked: chunkSize: 1024 # bytes per chunk chunkDelay: 100 # ms between chunks data: "..." # data to stream dataFile: ./large.json # or load from file format: ndjson # optional: ndjson format ndjsonItems: # for ndjson format - {"id": 1} - {"id": 2}WebSocket Mock
Section titled “WebSocket Mock”WebSocket mocks handle bidirectional message communication.
mocks: - id: chat-ws name: Chat WebSocket type: websocket enabled: true websocket: path: /ws/chat subprotocols: - chat - json requireSubprotocol: false echoMode: true maxMessageSize: 65536 idleTimeout: "5m" maxConnections: 100 heartbeat: enabled: true interval: "30s" timeout: "10s" matchers: - match: type: exact value: "ping" response: type: text value: "pong" - match: type: json path: "$.type" value: "join" response: type: json value: type: "joined" message: "Welcome!" defaultResponse: type: json value: type: "echo" message: "{{message}}"WebSocket Spec Fields
Section titled “WebSocket Spec Fields”| Field | Type | Default | Description |
|---|---|---|---|
path | string | Required | WebSocket upgrade path |
subprotocols | array | [] | Supported subprotocols |
requireSubprotocol | boolean | false | Require matching subprotocol |
echoMode | boolean | false | Echo received messages |
maxMessageSize | integer | 65536 | Max message size (bytes) |
idleTimeout | string | Connection idle timeout | |
maxConnections | integer | 0 | Max concurrent connections (0 = unlimited) |
heartbeat | object | Ping/pong keepalive config | |
matchers | array | [] | Message matching rules |
defaultResponse | object | Response when no matcher matches | |
scenario | object | Scripted message sequence |
WebSocket Match Criteria
Section titled “WebSocket Match Criteria”| Field | Type | Description |
|---|---|---|
type | string | Match type: exact, contains, regex, json |
value | string | Value to match |
path | string | JSONPath for json type |
messageType | string | Filter by message type: text, binary |
WebSocket Message Response
Section titled “WebSocket Message Response”| Field | Type | Description |
|---|---|---|
type | string | Response type: text, json, binary |
value | any | Response content (string or object for json) |
delay | string | Delay before sending (e.g., “100ms”) |
WebSocket Heartbeat
Section titled “WebSocket Heartbeat”| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enable ping/pong |
interval | string | "30s" | Ping interval |
timeout | string | "10s" | Pong timeout |
WebSocket Scenario
Section titled “WebSocket Scenario”websocket: scenario: name: "onboarding" loop: false resetOnReconnect: true steps: - type: send message: type: json value: {"type": "welcome"} - type: wait duration: "1s" - type: waitFor match: type: json path: "$.type" value: "ready" timeout: "10s" optional: falseGraphQL Mock
Section titled “GraphQL Mock”GraphQL mocks provide a full GraphQL API endpoint.
mocks: - id: graphql-api name: GraphQL API type: graphql enabled: true graphql: path: /graphql introspection: true schema: | type Query { users: [User!]! user(id: ID!): User }
type User { id: ID! name: String! email: String! } resolvers: Query.users: response: - id: "1" name: "Alice" email: "alice@example.com" Query.user: response: id: "1" name: "Alice" email: "alice@example.com"GraphQL Spec Fields
Section titled “GraphQL Spec Fields”| Field | Type | Default | Description |
|---|---|---|---|
path | string | Required | GraphQL endpoint path |
schema | string | Inline SDL schema | |
schemaFile | string | Path to .graphql schema file | |
introspection | boolean | false | Enable introspection queries |
resolvers | map | {} | Field resolver configurations |
subscriptions | map | {} | Subscription configurations |
GraphQL Resolvers
Section titled “GraphQL Resolvers”Resolvers are keyed by Type.field:
resolvers: Query.users: response: - { id: "1", name: "Alice" } - { id: "2", name: "Bob" } delay: "100ms"
Query.user: # Match specific arguments match: args: id: "1" response: id: "1" name: "Alice"
Mutation.createUser: response: id: "{{uuid}}" name: "New User"
Query.error: error: message: "Something went wrong" path: ["error"] extensions: code: "INTERNAL_ERROR"gRPC Mock
Section titled “gRPC Mock”gRPC mocks provide a gRPC service endpoint.
mocks: - id: grpc-greeter name: Greeter Service type: grpc enabled: true grpc: port: 50051 reflection: true protoFile: | syntax = "proto3"; package helloworld;
service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} rpc SayHelloStream (HelloRequest) returns (stream HelloReply) {} }
message HelloRequest { string name = 1; }
message HelloReply { string message = 1; } services: helloworld.Greeter: methods: SayHello: response: message: "Hello, World!" SayHelloStream: responses: - message: "Hello 1" - message: "Hello 2" - message: "Hello 3" streamDelay: "500ms"gRPC Spec Fields
Section titled “gRPC Spec Fields”| Field | Type | Default | Description |
|---|---|---|---|
port | integer | Required | gRPC server port |
protoFile | string | Inline proto definition | |
protoFiles | array | Paths to .proto files | |
importPaths | array | Proto import paths | |
reflection | boolean | false | Enable gRPC reflection |
services | map | {} | Service configurations |
gRPC Method Config
Section titled “gRPC Method Config”services: package.Service: methods: MethodName: response: # Single response field: value responses: # Multiple responses (streaming) - { field: value1 } - { field: value2 } delay: "100ms" # Response delay streamDelay: "50ms" # Delay between stream messages match: # Request matching metadata: authorization: "Bearer *" request: field: expected_value error: code: "NOT_FOUND" message: "Resource not found" details: type: "ErrorInfo"MQTT Mock
Section titled “MQTT Mock”MQTT mocks provide an MQTT broker.
mocks: - id: mqtt-broker name: IoT MQTT Broker type: mqtt enabled: true mqtt: port: 1883 tls: enabled: false certFile: ./certs/mqtt.crt keyFile: ./certs/mqtt.key auth: enabled: false users: - username: device password: secret123 acl: - topic: "sensors/#" access: publish - topic: "commands/#" access: subscribe topics: - topic: sensors/temperature qos: 1 retain: true messages: - payload: '{"temp": 22, "unit": "celsius"}' interval: "5s" repeat: true - topic: commands/device/+ qos: 1 onPublish: response: payload: '{"status": "ack"}' forward: responses/deviceMQTT Spec Fields
Section titled “MQTT Spec Fields”| Field | Type | Default | Description |
|---|---|---|---|
port | integer | Required | MQTT broker port |
tls | object | TLS configuration | |
auth | object | Authentication configuration | |
topics | array | [] | Topic configurations |
MQTT Topic Config
Section titled “MQTT Topic Config”| Field | Type | Default | Description |
|---|---|---|---|
topic | string | Required | Topic pattern (supports + and # wildcards) |
qos | integer | 0 | Quality of Service (0, 1, 2) |
retain | boolean | false | Retain last message |
messages | array | Messages to publish | |
onPublish | object | Handler for received messages | |
deviceSimulation | object | Simulate multiple devices |
MQTT Message Config
Section titled “MQTT Message Config”| Field | Type | Description |
|---|---|---|
payload | string | Message payload (supports templates) |
delay | string | Initial delay before sending |
interval | string | Repeat interval |
repeat | boolean | Whether to repeat |
SOAP Mock
Section titled “SOAP Mock”SOAP mocks provide SOAP/WSDL service endpoints.
mocks: - id: soap-service name: Calculator Service type: soap enabled: true soap: path: /soap/calculator wsdlFile: ./calculator.wsdl # or inline with wsdl: operations: Add: soapAction: "http://example.com/Add" response: | <AddResponse> <AddResult>{{add request.a request.b}}</AddResult> </AddResponse> delay: "50ms" match: xpath: "//a": "10" fault: code: "Server.InvalidInput" message: "Invalid input provided" detail: "<errorCode>1001</errorCode>"SOAP Spec Fields
Section titled “SOAP Spec Fields”| Field | Type | Description |
|---|---|---|
path | string | SOAP endpoint path |
wsdl | string | Inline WSDL definition |
wsdlFile | string | Path to WSDL file |
operations | map | Operation configurations |
SOAP Operation Config
Section titled “SOAP Operation Config”| Field | Type | Description |
|---|---|---|
soapAction | string | SOAPAction header value |
response | string | XML response body |
delay | string | Response delay |
match | object | XPath-based request matching |
fault | object | SOAP fault response |
Server Configuration
Section titled “Server Configuration”Server settings can be included in the config file.
Note: Port settings (
httpPort,httpsPort,adminPort) from config files are currently overridden by CLI flags. Use--portand--admin-portflags to set ports:Terminal window mockd serve --config myconfig.yaml --port 8080 --admin-port 8081
version: "1.0"
serverConfig: httpPort: 4280 httpsPort: 4283 adminPort: 4290 logRequests: true maxLogEntries: 1000 maxBodySize: 10485760 # 10MB readTimeout: 30 # seconds writeTimeout: 30 # seconds tls: enabled: false certFile: ./certs/server.crt keyFile: ./certs/server.key autoGenerateCert: true mtls: enabled: false clientAuth: "require-and-verify" caCertFile: ./certs/ca.crt allowedCNs: - "client.example.com"
mocks: [...]Server Config Fields
Section titled “Server Config Fields”| Field | Type | Default | Description |
|---|---|---|---|
httpPort | integer | 4280 | HTTP server port (0 = disabled) |
httpsPort | integer | 0 | HTTPS server port (0 = disabled) |
adminPort | integer | 4290 | Admin API port |
managementPort | integer | 4281 | Engine management API port (internal) |
logRequests | boolean | true | Enable request logging |
maxLogEntries | integer | 1000 | Max log entries to retain |
maxBodySize | integer | 10485760 | Max request body size (bytes) |
readTimeout | integer | 30 | HTTP read timeout (seconds) |
writeTimeout | integer | 30 | HTTP write timeout (seconds) |
The managementPort is used for internal communication between the Admin API and the mock engine. In standalone mode, you typically don’t need to configure this.
TLS Configuration
Section titled “TLS Configuration”| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enable TLS/HTTPS |
certFile | string | Path to certificate file | |
keyFile | string | Path to private key file | |
autoGenerateCert | boolean | false | Auto-generate self-signed cert |
mTLS Configuration
Section titled “mTLS Configuration”| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enable mTLS |
clientAuth | string | "none" | Client auth mode |
caCertFile | string | CA certificate file | |
caCertFiles | array | Multiple CA certificate files | |
allowedCNs | array | Allowed client Common Names | |
allowedOUs | array | Allowed Organizational Units |
Client auth modes:
none- No client certificate requestedrequest- Client certificate requested but not requiredrequire- Client certificate required but not verifiedverify-if-given- Verify client certificate if providedrequire-and-verify- Require and verify client certificate
CORS Configuration
Section titled “CORS Configuration”Configure Cross-Origin Resource Sharing for the mock server.
serverConfig: cors: enabled: true allowOrigins: - "http://localhost:3000" - "https://app.example.com" allowMethods: - GET - POST - PUT - DELETE - OPTIONS allowHeaders: - Content-Type - Authorization - X-Requested-With exposeHeaders: - X-Request-ID allowCredentials: false maxAge: 86400| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Enable CORS handling |
allowOrigins | array | ["http://localhost:*"] | Allowed origins (use ["*"] for any) |
allowMethods | array | [GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD] | Allowed HTTP methods |
allowHeaders | array | [Content-Type, Authorization, X-Requested-With, Accept, Origin] | Allowed request headers |
exposeHeaders | array | [] | Headers browsers can access |
allowCredentials | boolean | false | Allow credentials (cannot use with * origin) |
maxAge | integer | 86400 | Preflight cache duration (seconds) |
Default behavior: When not configured, mockd allows requests from localhost origins only. This is secure for local development while preventing cross-origin attacks.
Wildcard origins:
cors: allowOrigins: ["*"] # Allow any origin (not recommended for production)Note: When allowCredentials: true, you cannot use wildcard origins.
Rate Limiting Configuration
Section titled “Rate Limiting Configuration”Configure rate limiting for the mock server.
serverConfig: rateLimit: enabled: true requestsPerSecond: 1000 burstSize: 2000 trustedProxies: - "10.0.0.0/8" - "172.16.0.0/12"| Field | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enable rate limiting |
requestsPerSecond | float | 1000 | Requests per second limit |
burstSize | integer | 2000 | Maximum burst size (token bucket) |
trustedProxies | array | [] | CIDR ranges for trusted proxies |
How it works: Rate limiting uses a token bucket algorithm. The bucket fills at requestsPerSecond rate up to burstSize tokens. Each request consumes one token.
Trusted proxies: When set, mockd trusts X-Forwarded-For headers from these IP ranges for accurate client IP detection.
Example: Strict rate limiting for load testing:
serverConfig: rateLimit: enabled: true requestsPerSecond: 100 burstSize: 150Stateful Resources
Section titled “Stateful Resources”Stateful resources provide automatic CRUD operations with persistent state.
version: "1.0"
statefulResources: - name: users basePath: /api/users idField: id parentField: "" seedData: - id: "1" name: "Alice" email: "alice@example.com" - id: "2" name: "Bob" email: "bob@example.com"
mocks: []Stateful Resource Fields
Section titled “Stateful Resource Fields”| Field | Type | Default | Description |
|---|---|---|---|
name | string | Required | Resource name (e.g., “users”) |
basePath | string | Required | Base URL path (e.g., “/api/users”) |
idField | string | "id" | Field name for resource ID |
parentField | string | Parent FK field for nested resources | |
seedData | array | [] | Initial data to load |
validation | object | Validation rules (see Validation) |
Generated Endpoints
Section titled “Generated Endpoints”For a resource with basePath: /api/users:
| Method | Path | Description |
|---|---|---|
| GET | /api/users | List all resources |
| POST | /api/users | Create resource |
| GET | /api/users/{id} | Get resource by ID |
| PUT | /api/users/{id} | Replace resource |
| PATCH | /api/users/{id} | Update resource |
| DELETE | /api/users/{id} | Delete resource |
Validation
Section titled “Validation”Stateful resources and HTTP mocks support field-level request validation.
StatefulValidation
Section titled “StatefulValidation”| Field | Type | Default | Description |
|---|---|---|---|
mode | string | "strict" | Validation mode: strict, warn, permissive |
auto | boolean | false | Auto-infer rules from seed data |
required | array | [] | Required field names (shared) |
fields | map | {} | Field validators (shared) |
pathParams | map | {} | Path parameter validators |
onCreate | object | Create-specific validation | |
onUpdate | object | Update-specific validation | |
schema | object | Inline JSON Schema | |
schemaRef | string | Path to JSON Schema file |
RequestValidation (for HTTP mocks)
Section titled “RequestValidation (for HTTP mocks)”| Field | Type | Default | Description |
|---|---|---|---|
mode | string | "strict" | Validation mode: strict, warn, permissive |
failStatus | integer | 400 | HTTP status code for failures |
required | array | [] | Required field names |
fields | map | {} | Field validators |
pathParams | map | {} | Path parameter validators |
queryParams | map | {} | Query parameter validators |
headers | map | {} | Header validators |
schema | object | Inline JSON Schema | |
schemaRef | string | Path to JSON Schema file |
FieldValidator
Section titled “FieldValidator”| Field | Type | Description |
|---|---|---|
type | string | Expected type: string, number, integer, boolean, array, object |
required | boolean | Field must be present |
nullable | boolean | Allow null values |
minLength | integer | Minimum string length |
maxLength | integer | Maximum string length |
pattern | string | Regex pattern for strings |
format | string | Format: email, uuid, date, datetime, uri, ipv4, ipv6, hostname |
min | number | Minimum value (inclusive) |
max | number | Maximum value (inclusive) |
exclusiveMin | number | Minimum value (exclusive) |
exclusiveMax | number | Maximum value (exclusive) |
minItems | integer | Minimum array items |
maxItems | integer | Maximum array items |
uniqueItems | boolean | Array items must be unique |
items | object | FieldValidator for array items |
enum | array | Allowed values |
properties | map | Nested object validators |
message | string | Custom error message |
Nested Fields
Section titled “Nested Fields”Use dot notation for nested object fields:
fields: "address.city": type: string required: true "address.zipCode": type: string pattern: "^[0-9]{5}$" "items.sku": type: string required: trueFor arrays, the field after the dot applies to each array item:
items.skuvalidates theskufield in each item of theitemsarray
See the Validation Guide for comprehensive examples.
Template Variables
Section titled “Template Variables”Response bodies support template variables:
body: | { "id": "{{request.pathParam.id}}", "query": "{{request.query.search}}", "header": "{{request.header.Authorization}}", "body": {{request.body}}, "field": "{{jsonPath request.body '$.field'}}", "timestamp": "{{now}}", "unix": "{{timestamp}}", "uuid": "{{uuid}}", "random": {{randomInt 1 100}} }Available Variables
Section titled “Available Variables”| Variable | Description |
|---|---|
{{request.method}} | HTTP method |
{{request.path}} | Request path |
{{request.url}} | Full URL |
{{request.pathParam.name}} | Path parameter value |
{{request.query.name}} | Query parameter value |
{{request.header.Name}} | Request header value |
{{request.body}} | Full request body (raw) |
{{jsonPath request.body '$.path'}} | JSONPath extraction |
{{now}} | ISO 8601 timestamp |
{{timestamp}} | Unix timestamp (seconds) |
{{uuid}} | Random UUID |
{{randomInt min max}} | Random integer |
{{randomFloat min max}} | Random float |
See mockd help templating for the complete list.
Complete Example
Section titled “Complete Example”version: "1.0"
serverConfig: httpPort: 4280 adminPort: 4290 logRequests: true
mocks: # HTTP mock - id: health-check name: Health Check type: http enabled: true http: matcher: method: GET path: /health response: statusCode: 200 body: '{"status": "ok"}'
# HTTP with path parameters - id: get-user name: Get User type: http enabled: true http: matcher: method: GET path: /api/users/{id} response: statusCode: 200 headers: Content-Type: application/json body: | { "id": "{{request.pathParam.id}}", "name": "User {{request.pathParam.id}}" }
# WebSocket - id: ws-echo name: Echo WebSocket type: websocket enabled: true websocket: path: /ws/echo echoMode: true
# GraphQL - id: graphql name: GraphQL API type: graphql enabled: true graphql: path: /graphql introspection: true schema: | type Query { hello: String! } resolvers: Query.hello: response: "Hello, World!"
statefulResources: - name: posts basePath: /api/posts seedData: - id: "1" title: "First Post" content: "Hello, World!"See Also
Section titled “See Also”- CLI Reference - Command-line options
- Request Matching - Matching patterns
mockd help config- Built-in configuration helpmockd help templating- Template variable referencemockd init --template list- Available templates