MockServer MCP Tools Reference for AI Assistants
MockServer's MCP server exposes a comprehensive set of tools that AI assistants can use to interact with MockServer. Tools are divided into high-level tools (simplified parameters for common tasks) and low-level tools (full JSON passthrough for advanced use cases).
Tool Overview
| Tool | Description | Level |
|---|---|---|
create_expectation | Create a mock expectation | High |
verify_request | Verify a request was received N times | High |
verify_request_sequence | Verify requests were received in order | High |
retrieve_recorded_requests | Get recorded requests | High |
retrieve_request_responses | Get request-response pairs | High |
list_expectations | List the active mock expectations, optionally filtered | High |
retrieve_logs | Get log messages for debugging | High |
clear_expectations | Clear matching expectations and/or logs | High |
set_operating_mode | Switch operating mode — SIMULATE, SPY, or CAPTURE | High |
promote_recordings | Promote recorded traffic into active mocks (redact, consolidate, parameterize) | High |
reset | Reset all MockServer state | High |
get_status | Server status and ports | High |
manage_service_chaos | Register, remove, or clear service-scoped HTTP chaos per upstream host | High |
create_forward_expectation | Create a forwarding proxy expectation | High |
debug_request_mismatch | Diagnose why a request did not match | High |
explain_unmatched_requests | Explain recent unmatched requests with ranked diagnostics | High |
explain_request | Explain why one received request matched one expectation and not another | High |
diagnose_config | Show which configuration settings are in effect and where each came from | High |
explain_forward_failure | Explain why a forwarded or proxied request got a 502 | High |
suggest_expectation_fix | Suggest a JSON patch that makes a close expectation match an unmatched request | High |
lint_expectations | Find expectations that can never match, or will not match the way they read | High |
test_template | Dry-run a response or forward template against a sample request | High |
stop_server | Stop the MockServer instance | High |
create_expectation_from_openapi | Generate expectations from an OpenAPI spec | High |
create_expectations_from_recorded_traffic | Convert recorded proxy traffic into mock expectations | High |
verify_traffic_against_openapi | Verify recorded traffic conforms to an OpenAPI spec | High |
run_contract_test | Send example requests from an OpenAPI spec and validate responses | High |
run_resiliency_test | Send malformed and boundary-case requests to verify error handling | High |
record_llm_fixtures | Snapshot recorded LLM/MCP traffic into a committable fixture file | High |
load_expectations_from_file | Load expectations from a fixture file for replay | High |
mock_llm_completion | Create a single-turn LLM completion expectation for any supported provider | High |
create_llm_conversation | Create a multi-turn scripted LLM conversation with optional per-session isolation | High |
mock_llm_failover | Create an LLM failover/retry scenario — first N requests fail, then succeed | High |
verify_tool_call | Assert an agent called a named tool, from recorded LLM requests | High |
explain_agent_run | Summarise a recorded agent run (turns, tool-call sequence) | High |
verify_structured_output | Validate recorded LLM responses' JSON output against a JSON Schema | High |
verify_cost_budget | Assert the total estimated USD cost of recorded LLM responses is within a budget | High |
detect_llm_drift | Replay a cassette against the live provider and report structural drift | High |
export_optimisation_report | Turn captured LLM traffic into an optimisation brief covering both spend and agent design (Markdown, JSON, CSV, or an eval/fine-tune dataset export) | High |
diff_agent_runs | Prompt-level diff of two recorded agent runs — message, tool-call, and token/cost changes | High |
mock_adversarial_llm_response | Mock a hostile/malformed LLM response to test agent resilience | High |
run_mcp_contract_test | Check a target MCP server conforms to the protocol over Streamable HTTP | High |
list_mock_tools | Generate MCP tool definitions from the current active mock expectations | High |
raw_expectation | Full expectation JSON passthrough | Low |
raw_retrieve | Full retrieve with correlation ID filtering | Low |
raw_verify | Full verification JSON | Low |
High-Level Tools
create_expectation
Create a mock expectation that matches incoming requests and returns a specified response.
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | Yes | HTTP method to match (GET, POST, PUT, DELETE, etc.) |
path | string | Yes | URL path to match (e.g. /api/users) |
statusCode | integer | No | HTTP status code to return. Defaults to 200. |
responseBody | string or object | No | Response body to return. Strings are sent as-is; objects are serialised as JSON. |
responseHeaders | object | No | Response headers as key-value pairs |
times | integer | No | Number of times the expectation should be used. Defaults to unlimited. |
timeToLive | string | No | How long the expectation remains active, in format <number> <UNIT> (e.g. "60 SECONDS"). Defaults to unlimited. |
chaos | object | No | Declarative HTTP chaos/fault-injection profile for resilience testing — probabilistic errors, latency, connection drops, body corruption, slow (dribbled) responses, time/count-based outage windows, and a stateful request quota (see the table below). |
chaos fields (all optional):
| Field | Type | Description |
|---|---|---|
errorStatus | integer | HTTP status to inject on error (e.g. 500, 503, 429). |
errorProbability | number | Probability 0.0–1.0 of injecting an error. Fractional values are non-deterministic unless seed is set. |
retryAfter | string | Optional Retry-After header value on an injected error. |
latency | object | Injected latency delay — an object with timeUnit (e.g. MILLISECONDS, SECONDS) and value (integer). |
dropConnectionProbability | number | Probability 0.0–1.0 of dropping the TCP connection without sending any response. |
seed | integer | Optional seed for reproducible probabilistic draws. |
succeedFirst | integer | First N matches are not eligible for chaos (≥ 0). |
failRequestCount | integer | After succeedFirst, the next M matches are eligible for chaos (≥ 1). |
outageAfterMillis | integer | Time-based outage window: chaos becomes active this many ms after the first match (≥ 0). |
outageDurationMillis | integer | Time-based outage window: chaos stays active for this many ms then self-heals (≥ 1). |
truncateBodyAtFraction | number | Corrupt the response body by keeping only this leading fraction (0.0–1.0) of its bytes. |
malformedBody | boolean | Corrupt the response body by appending a broken-JSON fragment so it fails to parse. |
slowResponseChunkSize | integer | Dribble the response body in chunks of this many bytes (≥ 1); requires slowResponseChunkDelay. |
slowResponseChunkDelay | object | Delay between dribbled response chunks — an object with timeUnit and value (integer). |
quotaName | string | Stateful quota: shared counter key; expectations with the same quotaName share one rate-limit counter. |
quotaLimit | integer | Stateful quota: max requests allowed per window before requests are rejected (≥ 1). |
quotaWindowMillis | integer | Stateful quota: fixed-window length in milliseconds (≥ 1). |
quotaErrorStatus | integer | Stateful quota: status returned when the quota is exceeded (default 429). |
degradationRampMillis | integer | Gradual degradation: ramp errorProbability and dropConnectionProbability from 0 to full over this many ms from the first match (≥ 1). |
Example request:
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "create_expectation",
"arguments": {
"method": "GET",
"path": "/api/users",
"statusCode": 200,
"responseBody": "{\"users\": [{\"id\": 1, \"name\": \"Alice\"}]}",
"responseHeaders": {
"content-type": "application/json"
}
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"created\",\"count\":1}"
}
],
"isError": false
}
}
Errors an assistant can act on: a call that is rejected creates nothing and returns "error": true with a message naming the field to change. A parameter the tool does not have (including one inside chaos) is never ignored silently: the result lists it in unknownParameters, lists the names the tool accepts in acceptedParameters, and, when the intended name is clear, maps it in suggestions (for example body to responseBody, headers to responseHeaders, or status_code to statusCode). Keys that start with _, such as a client's _meta, are treated as metadata and let through. responseHeaders must be an object whose values are strings, or arrays of strings for a header with several values. To match on request headers, query parameters, cookies or a body, or to add a delay or a template, use raw_expectation instead.
{
"error": true,
"message": "create_expectation does not accept: 'body' (did you mean 'responseBody'?), 'queryParameters'. It accepts: method, path, statusCode, responseBody, responseHeaders, times, timeToLive, chaos. To match on request headers, query parameters, cookies or a body, or to add a delay or a template, use raw_expectation with the full expectation JSON.",
"unknownParameters": ["body", "queryParameters"],
"acceptedParameters": ["method", "path", "statusCode", "responseBody", "responseHeaders", "times", "timeToLive", "chaos"],
"suggestions": { "body": "responseBody" }
}
verify_request
Verify that a specific request was received by MockServer a certain number of times.
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | No | HTTP method to match |
path | string | No | URL path to match |
atLeast | integer | No | Minimum number of times the request must have been received |
atMost | integer | No | Maximum number of times the request must have been received |
Example request:
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "verify_request",
"arguments": {
"method": "POST",
"path": "/api/orders",
"atLeast": 1,
"atMost": 3
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "Verification passed"
}
],
"isError": false
}
}
verify_request_sequence
Verify that a sequence of requests was received in the specified order.
| Parameter | Type | Required | Description |
|---|---|---|---|
requests | array | Yes | Ordered array of request matchers, each with optional method and path fields |
Example request:
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "verify_request_sequence",
"arguments": {
"requests": [
{ "method": "POST", "path": "/api/login" },
{ "method": "GET", "path": "/api/profile" },
{ "method": "POST", "path": "/api/logout" }
]
}
}
}
retrieve_recorded_requests
Retrieve requests that have been recorded by MockServer.
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | No | Filter by HTTP method |
path | string | No | Filter by URL path |
limit | integer | No | Maximum number of requests to return |
Example request:
{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "retrieve_recorded_requests",
"arguments": {
"path": "/api/payments",
"limit": 10
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"content": [
{
"type": "text",
"text": "[{\"method\": \"POST\", \"path\": \"/api/payments\", \"headers\": {\"content-type\": [\"application/json\"]}, \"body\": {\"amount\": 99.99}}]"
}
],
"isError": false
}
}
retrieve_request_responses
Retrieve request-response pairs recorded by MockServer, useful for understanding the full HTTP conversation.
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | No | Filter by HTTP method |
path | string | No | Filter by URL path |
limit | integer | No | Maximum number of pairs to return |
Example request:
{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "retrieve_request_responses",
"arguments": {
"path": "/api/users",
"limit": 5
}
}
}
list_expectations
List the mock expectations that are currently active, optionally filtered by request method and/or path. Each expectation is returned in the full MockServer JSON format (including its id), so an agent can inspect what is mocked and then modify it (with create_expectation / raw_expectation) or remove it (with clear_expectations).
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | No | Only return expectations whose request matcher targets this HTTP method |
path | string | No | Only return expectations whose request matcher targets this path |
Example request:
{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "list_expectations",
"arguments": {
"path": "/api/users"
}
}
}
retrieve_logs
Retrieve MockServer's recorded log messages — request matching, mismatches, actions and errors — to debug why a test or request behaved as it did. Returns structured LOG_ENTRIES format. Use the correlationId filter to narrow to a single request's lifecycle.
| Parameter | Type | Required | Description |
|---|---|---|---|
correlationId | string | No | Filter to a single request's log entries by its correlation ID. Each incoming request is assigned a unique correlation ID that links all log entries for that request's lifecycle. |
limit | integer | No | Maximum number of log entries to return (default 100, max 500). Returns the most recent entries when more are available. |
Example request:
{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "retrieve_logs",
"arguments": {
"correlationId": "abc-123-def",
"limit": 20
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 5,
"result": {
"content": [
{
"type": "text",
"text": "{\"logEntries\":[{\"description\":\"received request\",\"logLevel\":\"INFO\",\"timestamp\":\"...\"}],\"total\":1,\"returned\":1}"
}
],
"isError": false
}
}
clear_expectations
Clear expectations and/or recorded requests and logs that match the specified request matcher.
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | No | HTTP method to match |
path | string | No | URL path to match |
type | string | No | What to clear: ALL, LOG, or EXPECTATIONS. Defaults to ALL. |
Example request:
{
"jsonrpc": "2.0",
"id": 6,
"method": "tools/call",
"params": {
"name": "clear_expectations",
"arguments": {
"path": "/api/users",
"type": "EXPECTATIONS"
}
}
}
set_operating_mode
Set MockServer's high-level operating mode in a single switch. This lets an agent flip between mocking and recording without reconfiguring the server:
SIMULATE— match expectations and return mocks; unmatched requests get a404(the default).SPY— match expectations and return mocks, but forward unmatched requests to the real upstream so they are served live and recorded.CAPTURE— forward and record everything (with no expectations defined this captures all traffic).
Use SPY or CAPTURE to record real upstream traffic, then turn it into mocks with promote_recordings.
| Parameter | Type | Required | Description |
|---|---|---|---|
mode | string | Yes | One of SIMULATE, SPY, or CAPTURE (case-insensitive) |
Example request:
{
"jsonrpc": "2.0",
"id": 6,
"method": "tools/call",
"params": {
"name": "set_operating_mode",
"arguments": {
"mode": "SPY"
}
}
}
promote_recordings
Promote traffic already recorded by MockServer's forwarding/proxy mode (for example after set_operating_mode SPY/CAPTURE) into active mock expectations in one step — the "record then mock" workflow. Secrets are redacted, and by default the recordings are consolidated and parameterized into reusable mocks (unlimited use). This mirrors PUT /mockserver/recordings/promote.
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | No | Filter recorded traffic by HTTP method |
path | string | No | Filter recorded traffic by request path |
consolidate | boolean | No | Collapse duplicate recordings into consolidated reusable mocks. Defaults to true; set false to promote each recording verbatim. |
parameterize | boolean | No | When consolidating, generalise volatile path/query/header/body values so a single recorded id does not pin the mock. Defaults to true. |
redactSensitiveData | boolean | No | Redact secrets (auth headers, common secret body fields) from promoted mocks. Defaults to true. |
Example request:
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "promote_recordings",
"arguments": {
"path": "/api/users"
}
}
}
reset
Reset MockServer by clearing all expectations, recorded requests, and logs. This tool takes no parameters.
Example request:
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "reset",
"arguments": {}
}
}
get_status
Retrieve the status of MockServer, including which ports it is listening on. This tool takes no parameters.
Example request:
{
"jsonrpc": "2.0",
"id": 8,
"method": "tools/call",
"params": {
"name": "get_status",
"arguments": {}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 8,
"result": {
"content": [
{
"type": "text",
"text": "{\"ports\": [1080], \"running\": true}"
}
],
"isError": false
}
}
manage_service_chaos
Manage service-scoped HTTP chaos. Register one chaos profile per upstream host (applied to all matched forwards to that host that have no chaos of their own), remove a host's profile, or clear all host-keyed profiles. An expectation's own chaos always takes precedence over a host-keyed profile.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | Yes | One of register (set a host's chaos), remove (clear one host), or clear (clear all) |
host | string | For register/remove | Upstream host to break; matched case-insensitively, ignoring any :port |
chaos | object | For register | The chaos profile to apply — same fields as the create_expectation chaos block (e.g. errorStatus, errorProbability, dropConnectionProbability, latency, truncateBodyAtFraction, malformedBody) |
ttlMillis | integer | No | Optional time-to-live for a register: the chaos auto-reverts after this many milliseconds (a dead-man's switch so chaos self-heals if no clear is sent). Omit for chaos that persists until explicitly cleared. |
Example request:
{
"jsonrpc": "2.0",
"id": 9,
"method": "tools/call",
"params": {
"name": "manage_service_chaos",
"arguments": {
"action": "register",
"host": "payments.example.com",
"chaos": {
"errorStatus": 503,
"errorProbability": 0.5
},
"ttlMillis": 60000
}
}
}
create_forward_expectation
Create a forwarding proxy expectation that forwards matching requests to a destination host.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | URL path to match for forwarding |
host | string | Yes | Destination host to forward to |
port | integer | No | Destination port. Defaults to 443. |
scheme | string | No | Protocol scheme: HTTP or HTTPS. Defaults to HTTPS. |
Example request:
{
"jsonrpc": "2.0",
"id": 9,
"method": "tools/call",
"params": {
"name": "create_forward_expectation",
"arguments": {
"path": "/api/.*",
"host": "api.example.com",
"port": 443,
"scheme": "HTTPS"
}
}
}
debug_request_mismatch
Diagnose why a request did not match any expectation. This tool compares the provided request details against active expectations and returns detailed mismatch information. Results are ranked by closeness (fewest differing fields first), and each mismatched field includes an actionable remediation hint.
Note: This functionality is also available as a REST API endpoint (PUT /mockserver/debugMismatch) and via the Java client (mockServerClient.debugMismatch(request)). See Troubleshooting Matching for details.
Tip: If you want to diagnose mismatches after a test run without reconstructing requests, use explain_unmatched_requests instead, which works from MockServer's traffic log.
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | No | HTTP method of the failing request |
path | string | Yes | URL path of the failing request |
headers | object | No | Headers of the failing request |
body | string | No | Body of the failing request |
Example request:
{
"jsonrpc": "2.0",
"id": 10,
"method": "tools/call",
"params": {
"name": "debug_request_mismatch",
"arguments": {
"method": "POST",
"path": "/api/users",
"headers": {
"content-type": "application/xml"
},
"body": "<user><name>Alice</name></user>"
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 10,
"result": {
"content": [
{
"type": "text",
"text": "{\"totalExpectations\":2,\"results\":[{\"expectationId\":\"abc-123\",\"expectationPath\":\"/api/users\",\"expectationMethod\":\"POST\",\"matches\":false,\"matchedFieldCount\":15,\"totalFieldCount\":16,\"differingFieldCount\":1,\"differences\":{\"body\":[\"expected JSON body but was XML\"]},\"remediation\":{\"body\":\"check the Content-Type header and body format\"}},{\"expectationId\":\"def-456\",\"expectationPath\":\"/api/orders\",\"expectationMethod\":\"GET\",\"matches\":false,\"matchedFieldCount\":12,\"totalFieldCount\":16,\"differingFieldCount\":4,\"differences\":{\"method\":[\"expected GET but was POST\"],\"path\":[\"expected /api/orders but was /api/users\"]},\"remediation\":{\"method\":\"use method GET not POST\",\"path\":\"use path /api/orders not /api/users\"}}],\"closestMatch\":{\"expectationId\":\"abc-123\",\"expectationPath\":\"/api/users\",\"expectationMethod\":\"POST\",\"remediation\":{\"body\":\"check the Content-Type header and body format\"}}}"
}
],
"isError": false
}
}
The results array is sorted by closeness (fewest differing fields first). Each entry includes:
differences— per-field mismatch details explaining what did not matchremediation— actionable hints for each mismatched field, such as "use method POST not GET" or "check the Content-Type header and body format"matchedFieldCount/totalFieldCount— numeric closeness rankingclosestMatch— the top-ranked result (at the root level) with its remediation hints
explain_unmatched_requests
Returns recent requests that hit MockServer and matched no expectation, with ranked closest-expectation diagnostics and actionable remediation hints. Use this after a failed test run to understand why requests received 404 responses, without needing to reconstruct each failing request. A request MockServer forwarded or proxied that failed with a 502 is not listed here, because it did not go unmatched: use explain_forward_failure for it.
Note: This functionality is also available as a REST API endpoint (PUT /mockserver/explainUnmatched) and as an MCP resource (mockserver://unmatched).
| Parameter | Type | Required | Description |
|---|---|---|---|
limit | integer | No | Maximum number of unmatched requests to return. Defaults to 10, maximum 100. |
Example request:
{
"jsonrpc": "2.0",
"id": 20,
"method": "tools/call",
"params": {
"name": "explain_unmatched_requests",
"arguments": {
"limit": 5
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 20,
"result": {
"content": [
{
"type": "text",
"text": "{\"unmatchedRequestCount\":1,\"unmatchedRequests\":[{\"timestamp\":\"2026-05-21 12:00:00.000\",\"method\":\"GET\",\"path\":\"/api/users\",\"closestExpectations\":[{\"expectationId\":\"abc123\",\"expectationPath\":\"/api/users\",\"expectationMethod\":\"POST\",\"matches\":false,\"matchedFieldCount\":15,\"totalFieldCount\":16,\"differingFieldCount\":1,\"differences\":{\"method\":[\"expected POST but was GET\"]},\"remediation\":{\"method\":\"use method POST not GET\"}}]}]}"
}
],
"isError": false
}
}
Each unmatched request includes a closestExpectations array ranked by closeness (fewest differing fields first). Each expectation entry includes:
differences— per-field mismatch detailsremediation— actionable hints such as "use method POST not GET" or "add missing header Authorization"differingFieldCount/matchedFieldCount— numeric closeness ranking
explain_request
Explains one request MockServer has already received, identified by its correlation ID: which expectation would serve it now, why each expectation checked before that one was passed over, which lower-priority expectations it hides, and how the request was actually handled when it arrived, including, when its forward failed with a 502, the expectation that forwarded it and the reason the forward failed. Use it when a request was served by the wrong expectation, or by none. Find the correlation ID with retrieve_logs: every log entry for a request carries it.
The answer is worked out again when you ask, against the expectations as they are now, so it says whether they have changed since the request arrived. Asking changes nothing: no Times are used up and no scenario moves. The fields and reasons are described in Troubleshooting Matching.
Note: This functionality is also available as a REST API endpoint (PUT /mockserver/explain?correlationId=<id>).
Redaction: values quoted from the recorded request, such as an Authorization header in a field difference, are masked when redactSecretsInLog is enabled, exactly as in the event log. Enable it if your assistant should not see credentials from your traffic.
| Parameter | Type | Required | Description |
|---|---|---|---|
correlationId | string | Yes | Correlation ID of the received request |
Example request:
{
"jsonrpc": "2.0",
"id": 21,
"method": "tools/call",
"params": {
"name": "explain_request",
"arguments": {
"correlationId": "abc-123-def-456"
}
}
}
Example response (the text holds the same JSON as the REST endpoint, shortened here):
{
"jsonrpc": "2.0",
"id": 21,
"result": {
"content": [
{
"type": "text",
"text": "{\"correlationId\":\"abc-123-def-456\",\"recomputed\":true,\"atArrival\":{\"outcome\":\"MATCHED\",\"expectationId\":\"catch-all\"},\"expectationsChangedSince\":false,\"matchedExpectation\":{\"expectationId\":\"catch-all\",\"position\":2,\"priority\":0},\"skippedExpectations\":[{\"expectationId\":\"gold-tenant\",\"position\":1,\"priority\":10,\"reason\":\"FIELDS_DIFFER\",\"explanation\":\"the request differs on: headers\"}],\"shadowedExpectations\":[]}"
}
],
"isError": false
}
}
An unknown or evicted correlation ID returns "isError": true with a message saying no request is recorded with it (the event log keeps the most recent maxLogEntries entries).
diagnose_config
Shows which configuration settings are in effect and where each came from: a system property, the properties file, an environment variable or a runtime setter. Without parameters it lists only the settings changed from their default. Pass name to check one setting, in any form (maxExpectations, mockserver.maxExpectations, MOCKSERVER_MAX_EXPECTATIONS or max-expectations); a name that matches nothing returns a hint and the suggestions it was probably meant to be. Every answer also lists, under unrecognised, each mockserver.* or MOCKSERVER_* key you set that MockServer does not recognise and so ignores, with the setting it was probably meant to be. Credential values, such as passwords, tokens and API keys, are always shown as ***REDACTED***, and an unrecognised key is shown by name only, never its value.
Note: This reports the same values and sources as GET /mockserver/config and the --print-config command-line flag, which list every setting, including those at their default. A value set only on the Configuration object of an embedded server, or through PUT /mockserver/configuration, is not shown; GET /mockserver/configuration returns those.
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | No | A setting name, or part of one, to look up, including settings at their default (shown with the default's value) |
Example request:
{
"jsonrpc": "2.0",
"id": 22,
"method": "tools/call",
"params": {
"name": "diagnose_config",
"arguments": {
"name": "MOCKSERVER_MAX_EXPECTATIONS"
}
}
}
Example response (the text content, formatted):
{
"properties": [
{ "name": "mockserver.maxExpectations", "value": "5000", "source": "environment-variable", "default": "15000" }
],
"count": 1,
"explicitlySetCount": 3,
"unrecognised": [
{ "name": "MOCKSERVER_MAX_EXPECTATONS", "setAs": "environment variable", "suggestions": [ "MOCKSERVER_MAX_EXPECTATIONS" ], "systemPropertyOnly": false, "removed": false }
],
"note": "values come from system properties, the properties file, environment variables and runtime setters; ..."
}
A setting changed from its default also shows, as default, the built-in default it replaced, so you can see what you changed it from; a credential's default is always shown as ***REDACTED***, and default is left out when MockServer cannot work it out. A setting at its default shows the default's value, for example "value": "false", "source": "default"; a default worked out from the JVM heap size or from another setting shows the value worked out now (in the example above, the heap-based default of maxExpectations at its 15000 cap), and a credential at its default is still shown as ***REDACTED***. explicitlySetCount is the number of settings changed from their default, and totalProperties (left out above) the number of settings MockServer recognises. In unrecognised, setAs says how the key was set (system property, environment variable or properties-file key), and systemPropertyOnly is true for a setting MockServer reads only as a -D JVM system property, which has no effect where it was set. removed is true for a setting that MockServer no longer has (such as forwardBinaryRequestsWithoutWaitingForResponse, removed in 9.0.0): delete it from your configuration.
explain_forward_failure
Explains why MockServer could not forward or proxy a request. Without parameters it returns the most recent failed forwards, newest first; pass correlationId to get one request's. Each failure gives the request's method and path, the status code (502) and the reason MockServer gave. When MockServer can name the cause, the reason says what went wrong and what to change: a TLS failure, an HTTP/2 error, a connection it could not set up from its configuration, an upstream response it could not decode, a host name that does not resolve, a refused or timed-out connection, no route to the upstream, local ports or open files running out, an upstream proxy it could not reach, or a keep-alive connection the upstream closed. causeNamed is true for those, and forwardLoopSuspected is true when the forward went back to MockServer itself. When the cause could not be named, the reason is the raw error and a hint suggests retrieve_logs with the correlation ID.
MockServer records a failed forward only when logLevel is INFO (the default) or more detailed, and keeps it until the event log is cleared or the entry is evicted (see maxLogEntries). The forward-failure causes are described in Debugging Issues.
Redaction: a credential from the request quoted in the reason is masked when redactSecretsInLog is enabled, exactly as in the event log. A reason longer than 2,048 characters is cut and marked reasonTruncated.
| Parameter | Type | Required | Description |
|---|---|---|---|
correlationId | string | No | Correlation ID of one request whose forward failed |
limit | integer | No | How many of the most recent failed forwards to return (default 5, maximum 20) |
Example request:
{
"jsonrpc": "2.0",
"id": 23,
"method": "tools/call",
"params": {
"name": "explain_forward_failure",
"arguments": {}
}
}
Example response (the text content, formatted and shortened):
{
"forwardFailureCount": 1,
"forwardFailures": [
{
"correlationId": "abc-123-def-456",
"method": "GET",
"path": "/inventory",
"statusCode": 502,
"forwardLoopSuspected": false,
"reason": "upstream refused the connection: check the upstream is running and listening on the port forwarded to",
"causeNamed": true
}
]
}
A correlationId with no failed forward recorded returns "isError": true. With no parameters and no failed forward recorded, the result is empty and has a note.
suggest_expectation_fix
For each recent request that matched no expectation, suggests a fix to each of its closest expectations (at most five): a JSON patch (RFC 6902) of the expectation, as list_expectations returns it, that changes only its httpRequest so it would match the request. Each suggestion also lists the fields it could not patch, with a reason, and matchesAfterPatch. Every change in the patch is preceded by a test of the current value, so the patch fails, rather than overwriting, if the expectation has been edited since. Pass expectationId to get fixes for one expectation only.
Nothing is applied. To apply a fix, patch the expectation's JSON and send it with raw_expectation, keeping its id so it replaces the original. The fixes are described in Troubleshooting Matching.
Note: This is PUT /mockserver/explainUnmatched with "suggestFixes": true, keeping only the expectations that have a suggested fix. explain_unmatched_requests returns every comparison.
Redaction: a value the event log would mask is never copied into a patch; that field is listed as unpatched instead.
| Parameter | Type | Required | Description |
|---|---|---|---|
limit | integer | No | How many of the most recent unmatched requests to suggest fixes for (default 5, maximum 20) |
expectationId | string | No | Only suggest fixes to this expectation |
Example response (the text content, formatted and shortened):
{
"unmatchedRequestCount": 1,
"suggestedFixCount": 1,
"unmatchedRequests": [
{
"method": "GET",
"path": "/api/orders",
"closestExpectations": [
{
"expectationId": "orders",
"matches": false,
"differingFieldCount": 1,
"differences": { "path": ["string or regex match failed expected: /api/order found: /api/orders"] },
"suggestedFix": {
"patch": [
{ "op": "test", "path": "/httpRequest/path", "value": "/api/order" },
{ "op": "replace", "path": "/httpRequest/path", "value": "/api/orders" }
],
"patchedFields": ["path"],
"unpatchedFields": [],
"matchesAfterPatch": true
}
}
]
}
]
}
lint_expectations
Finds expectations that can never match, or will not match the way they read: one hidden by an earlier expectation that matches everything it does, times, time to live or percentage of 0, sequential responses that are never reached, path mistakes (no leading slash, a scheme and host or a query string in the path, a glob wildcard, an OpenAPI {param} with no path parameters), method and header-name typos, duplicate ids, and STRICT JSON bodies with arrays. Without parameters it checks the active expectations; pass expectations to check expectations before you create them. It is advisory: nothing is rejected or changed, and expectations passed in are not stored.
Note: This functionality is also available as a REST API endpoint (PUT /mockserver/lint) and from the command line (mockserver lint); the rules are described in Troubleshooting Matching.
| Parameter | Type | Required | Description |
|---|---|---|---|
expectations | object or array | No | One expectation, or an array of them, in MockServer's JSON format, to check without storing |
maxIssues | integer | No | Most issues to return, errors first (default 100, maximum 1000); the counts always cover every issue found |
Example response (the text content, formatted and shortened):
{
"source": "stored",
"expectationsChecked": 2,
"issueCount": 1,
"errorCount": 0,
"warningCount": 1,
"issues": [
{
"rule": "SHADOWED",
"severity": "WARNING",
"expectationId": "get-orders",
"message": "...",
"relatedExpectationId": "all-orders"
}
]
}
When more issues are found than maxIssues, issuesReturned and issuesOmitted say how many were left out.
test_template
Renders a Velocity, Mustache or JavaScript response or forward template against a sample request without creating an expectation, using the same template engines, security settings and the JavaScript and Velocity time limits MockServer uses when serving. It returns the rendered response or request, or why the template failed with its line and column and a hint, plus warnings for Velocity references and Mustache variables that did not resolve and for scenario.set calls, which a dry run reports instead of applying. Nothing reaches the event log.
Note: This is the same dry run as PUT /mockserver/template/test, described in Response Templates. Because it runs the template code it is sent, it needs the same permission as creating an expectation: with control-plane authorisation enabled, a principal that may only read cannot call it.
| Parameter | Type | Required | Description |
|---|---|---|---|
templateType | string | Yes | VELOCITY, MUSTACHE or JAVASCRIPT |
template | string | Yes | The template text |
actionType | string | No | RESPONSE_TEMPLATE (default) or FORWARD_TEMPLATE |
request | object | No | Sample request in MockServer's JSON format; defaults to GET / |
Example request:
{
"jsonrpc": "2.0",
"id": 24,
"method": "tools/call",
"params": {
"name": "test_template",
"arguments": {
"templateType": "VELOCITY",
"template": "{ \"statusCode\": 200, \"body\": \"$request.path\" }",
"request": { "path": "/sample" }
}
}
}
Example response (the text content, formatted and shortened):
{
"templateType": "VELOCITY",
"actionType": "RESPONSE_TEMPLATE",
"valid": true,
"renderedResponse": { "statusCode": 200, "body": "/sample" }
}
A missing or unknown templateType, or a missing template, returns "isError": true, as does a call made while two dry runs are already running.
stop_server
Stop the MockServer instance. This tool takes no parameters. Use with caution as the server will shut down immediately.
Example request:
{
"jsonrpc": "2.0",
"id": 15,
"method": "tools/call",
"params": {
"name": "stop_server",
"arguments": {}
}
}
create_expectation_from_openapi
Generate mock expectations from an OpenAPI v3 specification. MockServer will create one expectation per operation in the specification, using example responses where available.
| Parameter | Type | Required | Description |
|---|---|---|---|
specUrlOrPayload | string | Yes | URL, file path, or inline OpenAPI specification (JSON or YAML) |
operationsAndResponses | object | No | Map of operationId to control which operations and responses are mocked. Each value is either a status-code string (e.g. "200") or an object { "statusCode": "200", "exampleName": "..." } to pick a named example for that operation |
contextPathPrefix | string | No | Path prefix prepended to every path in the OpenAPI spec (e.g. /api/v1) |
Example request:
{
"jsonrpc": "2.0",
"id": 11,
"method": "tools/call",
"params": {
"name": "create_expectation_from_openapi",
"arguments": {
"specUrlOrPayload": "https://petstore3.swagger.io/api/v3/openapi.json",
"operationsAndResponses": {
"findPetsByStatus": "200",
"getPetById": "200"
}
}
}
}
The result gives the number of expectations created (count), their ids, and loadProblems: where a spec that loaded breaks the OpenAPI rules, each with its kind, kindLabel, JSON-pointer location, description and, for common causes, a hint. At most 50 problems are listed; when there are more, loadProblemsNotShown says how many were left out. The parts of the spec with problems may not behave as expected; see When A Spec Has Problems.
create_expectations_from_recorded_traffic
Converts traffic already recorded by MockServer's forwarding/proxy mode into active mock expectations in one step. After observing a real API via a forwarding proxy (e.g. using create_forward_expectation), call this tool to generate expectations that replay the recorded responses. This enables an "observe then mock" workflow: point MockServer at a real API once, record the traffic, then switch to mocked responses.
| Parameter | Type | Required | Description |
|---|---|---|---|
method | string | No | Filter recorded traffic by HTTP method (e.g. GET, POST) |
path | string | No | Filter recorded traffic by request path (e.g. /api/users) |
preview | boolean | No | When true, return the generated expectations as JSON without adding them. Defaults to false. |
Example request (preview):
{
"jsonrpc": "2.0",
"id": 16,
"method": "tools/call",
"params": {
"name": "create_expectations_from_recorded_traffic",
"arguments": {
"path": "/api/users",
"preview": true
}
}
}
Example response (preview):
{
"jsonrpc": "2.0",
"id": 16,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"preview\",\"count\":1,\"message\":\"Preview of expectations that would be created. Call again with preview=false to activate them.\",\"expectations\":[{\"httpRequest\":{\"method\":\"GET\",\"path\":\"/api/users\"},\"httpResponse\":{\"statusCode\":200,\"body\":\"[{\\\"id\\\":1}]\"}}]}"
}
],
"isError": false
}
}
Example request (create):
{
"jsonrpc": "2.0",
"id": 17,
"method": "tools/call",
"params": {
"name": "create_expectations_from_recorded_traffic",
"arguments": {
"method": "GET"
}
}
}
Example response (create):
{
"jsonrpc": "2.0",
"id": 17,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"created\",\"count\":2,\"ids\":[\"abc-123\",\"def-456\"]}"
}
],
"isError": false
}
}
When no recorded traffic is found, the tool returns a helpful message suggesting you set up a forwarding proxy first.
verify_traffic_against_openapi
Verify the API calls already recorded by MockServer conform to an OpenAPI contract. Pulls recorded request-response pairs from the event log, validates each request and response against the spec, and returns a per-pair conformance report. See Contract Verification for workflow details.
| Parameter | Type | Required | Description |
|---|---|---|---|
specUrlOrPayload | string | Yes | OpenAPI spec as a URL, file path, or inline JSON/YAML payload |
method | string | No | Filter recorded traffic by HTTP method (e.g. GET, POST) |
path | string | No | Filter recorded traffic by request path (e.g. /api/users) |
Example request:
{
"jsonrpc": "2.0",
"id": 18,
"method": "tools/call",
"params": {
"name": "verify_traffic_against_openapi",
"arguments": {
"specUrlOrPayload": "/specs/api.yaml",
"method": "GET"
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 18,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"conformant\",\"totalPairs\":2,\"passed\":2,\"failed\":0,\"results\":[{\"method\":\"GET\",\"path\":\"/api/users\",\"matchedOperation\":\"GET /api/users\",\"passed\":true},{\"method\":\"GET\",\"path\":\"/api/orders\",\"matchedOperation\":\"GET /api/orders\",\"passed\":true}]}"
}
],
"isError": false
}
}
run_contract_test
Send example requests derived from an OpenAPI spec to a running service and check the responses conform. For each operation in the spec, the tool builds a representative request (with path parameters, query parameters, headers, and request body derived from examples and schema defaults), sends it to the specified base URL, and validates the response. See Contract Verification for workflow details.
| Parameter | Type | Required | Description |
|---|---|---|---|
specUrlOrPayload | string | Yes | OpenAPI spec as a URL, file path, or inline JSON/YAML payload |
baseUrl | string | Yes | Base URL of the service under test (e.g. http://localhost:8080) |
operationId | string | No | Optional filter to test only a specific operation by operationId |
Example request:
{
"jsonrpc": "2.0",
"id": 19,
"method": "tools/call",
"params": {
"name": "run_contract_test",
"arguments": {
"specUrlOrPayload": "/specs/api.yaml",
"baseUrl": "http://localhost:3000"
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 19,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"all_passed\",\"totalOperations\":3,\"passed\":3,\"failed\":0,\"results\":[{\"operationId\":\"listUsers\",\"method\":\"GET\",\"path\":\"/api/users\",\"statusCode\":200,\"passed\":true},{\"operationId\":\"createUser\",\"method\":\"POST\",\"path\":\"/api/users\",\"statusCode\":201,\"passed\":true},{\"operationId\":\"getUser\",\"method\":\"GET\",\"path\":\"/api/users/{userId}\",\"statusCode\":200,\"passed\":true}]}"
}
],
"isError": false
}
}
run_resiliency_test
Send malformed and boundary-case requests derived from an OpenAPI spec to a running service and report which inputs it failed to handle gracefully. For each operation, the tool generates a bounded mutation catalogue (omitting required fields, type violations, numeric and string boundary violations, oversized strings, and malformed JSON) and classifies each response as HANDLED (4xx) or UNEXPECTED (5xx, 2xx, or connection error). See Resiliency Testing for workflow details.
| Parameter | Type | Required | Description |
|---|---|---|---|
specUrlOrPayload | string | Yes | OpenAPI spec as a URL, file path, or inline JSON/YAML payload |
baseUrl | string | Yes | Base URL of the service under test (e.g. http://localhost:8080) |
operationId | string | No | Optional filter to test only a specific operation by operationId |
Example request:
{
"jsonrpc": "2.0",
"id": 20,
"method": "tools/call",
"params": {
"name": "run_resiliency_test",
"arguments": {
"specUrlOrPayload": "/specs/api.yaml",
"baseUrl": "http://localhost:3000"
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 20,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"failures_detected\",\"totalMutations\":10,\"handled\":7,\"unexpected\":3,\"operationSummaries\":[{\"operationId\":\"createUser\",\"method\":\"POST\",\"path\":\"/api/users\",\"handled\":7,\"unexpected\":3}],\"results\":[{\"operationId\":\"createUser\",\"method\":\"POST\",\"path\":\"/api/users\",\"mutationType\":\"OMIT_REQUIRED_BODY_FIELD\",\"mutationDescription\":\"omit required body field 'name'\",\"statusCode\":400,\"classification\":\"HANDLED\"},{\"operationId\":\"createUser\",\"method\":\"POST\",\"path\":\"/api/users\",\"mutationType\":\"TYPE_VIOLATION\",\"mutationDescription\":\"type violation on field 'age' (expected integer)\",\"statusCode\":500,\"classification\":\"UNEXPECTED\"}]}"
}
],
"isError": false
}
}
record_llm_fixtures
Snapshots LLM/MCP traffic recorded through MockServer's forwarding proxy into a committable, secret-free fixture file for deterministic replay. Converts SSE streaming responses (from APIs like Anthropic Claude, OpenAI, etc.) into MockServer's SSE response format for faithful event-by-event replay. Sensitive headers (Authorization, api-key, Cookie, etc.) are automatically redacted. Note that request and response bodies are not redacted — if your application places credentials in a request or response body, review fixture files before committing them to version control.
The written fixture is automatically registered as a cassette (origin recorded), so it appears under GET /mockserver/cassettes and in the dashboard's Cassettes tab without a separate PUT /mockserver/cassettes call (PUT exists for tracking a cassette file produced some other way). Recording to the same path again updates that entry in place rather than adding a duplicate. Remove a tracked cassette with DELETE /mockserver/cassettes, passing its path either as the ?path= query parameter or as a JSON body {"path": "..."}; this untracks the entry only, it does not delete the fixture file.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path to write the fixture JSON to. The directory must exist. |
host | string | No | Only include recorded traffic whose request host matches this value |
requestPath | string | No | Only include recorded traffic whose request path matches this value |
redactBodyFields | array of string | No | JSON field names whose values are redacted from recorded request/response bodies (in addition to sensitive headers and the mockserver.fixtureBodyRedactFields config). Non-JSON bodies are left intact. |
Example request:
{
"jsonrpc": "2.0",
"id": 21,
"method": "tools/call",
"params": {
"name": "record_llm_fixtures",
"arguments": {
"path": "./fixtures/anthropic-chat.json",
"requestPath": "/v1/messages"
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 21,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"written\",\"count\":3,\"file\":\"/absolute/path/to/fixtures/anthropic-chat.json\",\"message\":\"Wrote 3 expectation(s) to /absolute/path/to/fixtures/anthropic-chat.json. Secrets have been redacted. Load with load_expectations_from_file or initializationJsonPath for replay.\"}"
}
],
"isError": false
}
}
load_expectations_from_file
Loads expectations from a JSON fixture file and adds them as active mock expectations in MockServer. Use this to replay LLM/MCP traffic previously recorded with record_llm_fixtures. SSE streaming responses in the fixture are replayed with Server-Sent Events.
The loaded fixture is automatically registered as a cassette (origin loaded), so it appears under GET /mockserver/cassettes and in the dashboard's Cassettes tab without a separate PUT /mockserver/cassettes call. Loading the same path again updates that entry in place rather than adding a duplicate. See record_llm_fixtures above for how to remove a tracked cassette with DELETE /mockserver/cassettes.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path to the fixture JSON file to load. Must contain expectations in MockServer's standard JSON format. |
strict | boolean | No | Strict VCR mode: register a low-priority catch-all per cassette path so a request matching no recorded fixture returns HTTP 599 instead of falling through. Defaults to the mockserver.llmVcrStrict config. |
normalizeRequestBodyFields | array of string | No | JSON field names to drop from each recorded request body on load; the remaining fields are matched loosely (extra fields in the incoming request are ignored), so volatile per-run values do not block replay. |
Example request:
{
"jsonrpc": "2.0",
"id": 22,
"method": "tools/call",
"params": {
"name": "load_expectations_from_file",
"arguments": {
"path": "./fixtures/anthropic-chat.json"
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 22,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"loaded\",\"count\":3,\"file\":\"/absolute/path/to/fixtures/anthropic-chat.json\",\"ids\":[\"abc-123\",\"def-456\",\"ghi-789\"],\"message\":\"Loaded 3 expectation(s) from /absolute/path/to/fixtures/anthropic-chat.json. They are now active and will match incoming requests.\"}"
}
],
"isError": false
}
}
mock_llm_completion
Creates a mock LLM completion expectation that returns a provider-correct response from a high-level description of text, tool calls, stop reason, and usage. The response wire format matches the target provider — for example, Anthropic returns the Anthropic Messages API format, OpenAI returns the Chat Completions format. Streaming responses are supported for all providers. See LLM Response Mocking for the full feature guide with raw JSON examples.
Both provider and path are required. All other parameters are optional.
Completions support the seven chat providers below; the rerank-only COHERE and VOYAGE providers cannot produce a completion — see Rerank for mocking those endpoints.
| Parameter | Type | Required | Description |
|---|---|---|---|
provider | string (enum) | Yes | LLM provider: ANTHROPIC, OPENAI, OPENAI_RESPONSES, GEMINI, BEDROCK, AZURE_OPENAI, or OLLAMA |
path | string | Yes | URL path to match (e.g. /v1/messages) |
model | string | No | Model name to include in the response (e.g. claude-sonnet-4-20250514) |
text | string | No | Response text content |
toolCalls | array | No | Tool/function calls to include. Each entry requires name (string) and accepts optional arguments (string or object). |
stopReason | string | No | Stop reason to encode in the provider format (e.g. end_turn, tool_use, stop) |
usage | object | No | Token usage. Accepts inputTokens (integer) and outputTokens (integer). |
streaming | boolean | No | When true, the response is delivered as a Server-Sent Events stream. Defaults to false. |
outputSchema | string or object | No | A JSON Schema the response text is expected to conform to. Validated as the response is encoded (fail-soft): on a mismatch the body is returned unchanged but an x-mockserver-structured-output-invalid header is added and a warning logged. A blank or malformed schema, or absent text, is a no-op. Use this to catch malformed structured-output fixtures; use verify_structured_output to assert over recorded traffic. |
enforceOutputSchema | boolean | No | Opt-in strict structured-output enforcement (default false). When true and an outputSchema is set, a non-conforming configured response fails loudly with a provider-correct error (HTTP 502) instead of the fail-soft diagnostic header — modelling a provider's strict response_format: json_schema mode that guarantees schema-valid output. No effect without an outputSchema. |
chaos | object | No | Optional fault/chaos profile for resilience testing (see the table below). Also accepted per turn in create_llm_conversation. |
chaos fields (all optional):
| Field | Type | Description |
|---|---|---|
errorStatus | integer | HTTP error status to return instead of a normal response (e.g. 429, 529). Fires every time unless errorProbability is set. A provider error is returned as a normal HTTP response even for a streaming completion. |
retryAfter | string | Value for the Retry-After header on an injected error (e.g. "30"). |
errorProbability | number | Probability 0.0–1.0 of injecting the error. 1.0 (or omitted with errorStatus set) always fires; 0.0 never does. Fractional values are non-deterministic unless seed is set. |
truncateMode | string | NONE or MID_STREAM. MID_STREAM truncates a streaming response after a leading fraction of events. |
truncateAtFraction | number | Fraction 0.0–1.0 of streaming events to keep before truncating (default 0.5). Only applies when truncateMode is MID_STREAM. |
malformedSse | boolean | Append a malformed (broken-JSON) SSE chunk so the client must handle a corrupt event. |
seed | integer | Makes a fractional errorProbability reproducible. |
quotaName | string | Enables a stateful request quota (a fixed-window rate limit). Expectations sharing a quotaName share one request counter, so you can model an upstream account limit across several mocks. |
quotaLimit | integer | Maximum requests allowed within the window before further requests are rejected. Requires quotaName and quotaWindowMillis. |
quotaWindowMillis | integer | Window length in milliseconds. The window starts on the first request and resets once it elapses. |
quotaErrorStatus | integer | HTTP status returned when the quota is exceeded (default 429); the retryAfter value, if set, is sent as the Retry-After header. |
Chaos is deterministic for truncation, malformed SSE, an errorProbability of 0.0 or 1.0, and the stateful quota — safe for repeatable tests. Use a fractional probability (optionally with a seed) only when you intend flakiness. The quota is the deterministic, stateful counterpart to the probabilistic error: it counts real requests and rejects the ones over quotaLimit per window (the count resets on server reset).
Example request (Anthropic text completion):
{
"jsonrpc": "2.0",
"id": 30,
"method": "tools/call",
"params": {
"name": "mock_llm_completion",
"arguments": {
"provider": "ANTHROPIC",
"path": "/v1/messages",
"model": "claude-sonnet-4-20250514",
"text": "The capital of France is Paris.",
"stopReason": "end_turn",
"usage": {
"inputTokens": 12,
"outputTokens": 9
}
}
}
}
Example response (success):
{
"jsonrpc": "2.0",
"id": 30,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"created\",\"count\":1,\"id\":\"abc-123\",\"provider\":\"ANTHROPIC\"}"
}
],
"isError": false
}
}
Example response (unsupported provider):
{
"jsonrpc": "2.0",
"id": 30,
"result": {
"content": [
{
"type": "text",
"text": "{\"error\":true,\"message\":\"unsupported LLM provider: UNKNOWN_AI\",\"supported\":[\"ANTHROPIC\",\"AZURE_OPENAI\",\"BEDROCK\",\"GEMINI\",\"OLLAMA\",\"OPENAI\",\"OPENAI_RESPONSES\"]}"
}
],
"isError": false
}
}
create_llm_conversation
Creates a multi-turn scripted LLM conversation. Each turn is registered as a separate mock expectation wired into a scenario state chain. As the client sends successive LLM requests, MockServer advances through the scripted turns in order, matching on conversation predicates (turn index, latest message content, role, or tool result presence) and returning the configured completion for that turn.
Per-session isolation is optional. When isolateBy is set, each unique value of the specified header, query parameter, or cookie gets its own independent state chain, so concurrent test sessions do not interfere with each other.
provider, path, and turns are required. All other parameters are optional.
Conversations support the seven chat providers; the rerank-only COHERE and VOYAGE providers cannot produce a completion — see Rerank.
| Parameter | Type | Required | Description |
|---|---|---|---|
provider | string (enum) | Yes | LLM provider: ANTHROPIC, OPENAI, OPENAI_RESPONSES, GEMINI, BEDROCK, AZURE_OPENAI, or OLLAMA |
path | string | Yes | URL path to match (e.g. /v1/messages) |
model | string | No | Model name to include in each response |
isolateBy | object | No | Per-session isolation configuration. Requires source (header, queryParameter, or cookie) and name (the header/parameter/cookie name to read the session key from). |
turns | array | Yes | Ordered list of conversation turns. Each turn is an object with an optional match predicate block and an optional response block (see below). |
ids | array of strings | No | Expectation IDs to assign to each generated turn expectation, one ID per turn in order. When supplied, each expectation is registered with the given ID. Because MockServer's PUT /mockserver/expectation performs an upsert when an ID already exists, supplying the same IDs as a previously created conversation replaces that conversation in place. This is how the Composer view's "edit existing" flow updates a conversation without creating duplicates. |
Turn match predicates (all optional; all present predicates must be satisfied for the turn to match):
| Field | Type | Description |
|---|---|---|
turnIndex | integer | Match when the conversation has this many completed assistant turns (0-based) |
latestMessageContains | string | Match when the latest message in the conversation contains this substring |
latestMessageMatches | string | Match when the latest message in the conversation matches this Java regular-expression pattern |
latestMessageRole | string | Match when the latest message has this role: USER, ASSISTANT, SYSTEM, or TOOL |
containsToolResultFor | string | Match when the conversation contains a tool result for the named tool |
semanticMatchAgainst | string | Opt-in, exploratory: the intent the latest message should express, judged by a runtime LLM. Off by default and ignored unless mockserver.llmSemanticMatchingEnabled is set and a backend resolves. Non-deterministic — for exploration only, never for CI assertions. |
normalization | object | Optional. Clean up the prompt text before latestMessageContains / latestMessageMatches are checked, so a match is not blocked by cosmetic differences in dynamically-assembled agent prompts. Deterministic — the same prompt always normalises the same way, so it never makes a test flaky. See the table below. |
Turn match.normalization fields (all optional):
| Field | Type | Description |
|---|---|---|
collapseWhitespace | boolean | Collapse runs of spaces, tabs and newlines to a single space and trim. Default true. |
lowercase | boolean | Lowercase the text so capitalisation differences are ignored. Default false. |
sortJsonKeys | boolean | When the prompt is JSON, sort object keys so key ordering does not affect matching. Default true. |
dropBuiltInVolatileFields | boolean | Strip values that change on every run — timestamps, UUIDs, and ids like req_… / msg_… / call_… — before matching. Default false. |
dropVolatileFields | array of string | Names of JSON fields to remove from the prompt before matching (for caller-specific volatile fields). |
Turn response fields (all optional):
| Field | Type | Description |
|---|---|---|
text | string | Response text content |
toolCalls | array | Tool/function calls. Each entry requires name and accepts optional arguments (string or object). |
stopReason | string | Stop reason (e.g. end_turn, tool_use) |
usage | object | Token usage: inputTokens and outputTokens |
streaming | boolean | Stream this turn's response as SSE. Defaults to false. |
Each turn may also carry an optional chaos object (a sibling of match and response) with the same fields as the mock_llm_completion chaos profile, to inject faults into that turn's response.
Example request (2-turn conversation isolated by session header):
{
"jsonrpc": "2.0",
"id": 31,
"method": "tools/call",
"params": {
"name": "create_llm_conversation",
"arguments": {
"provider": "ANTHROPIC",
"path": "/v1/messages",
"model": "claude-sonnet-4-20250514",
"isolateBy": {
"source": "header",
"name": "x-session-id"
},
"turns": [
{
"match": { "turnIndex": 0 },
"response": {
"text": "I can help with that. What city are you asking about?",
"stopReason": "end_turn"
}
},
{
"match": {
"turnIndex": 1,
"latestMessageContains": "paris",
"normalization": {
"lowercase": true,
"dropBuiltInVolatileFields": true
}
},
"response": {
"text": "Paris is the capital of France.",
"stopReason": "end_turn"
}
}
]
}
}
}
In the second turn above, normalization lets the turn match whether the prompt says Paris, PARIS or paris, and ignores any per-request timestamps or ids the agent framework injects — so the match stays stable as prompts are reassembled.
Example response:
{
"jsonrpc": "2.0",
"id": 31,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"created\",\"count\":2,\"scenarioName\":\"__llm_conv_a1b2c3d4__iso=header:x-session-id\",\"states\":[{\"scenarioState\":\"Started\",\"newScenarioState\":\"turn_1\",\"id\":\"exp-001\"},{\"scenarioState\":\"turn_1\",\"newScenarioState\":\"__done\",\"id\":\"exp-002\"}],\"ids\":[\"exp-001\",\"exp-002\"]}"
}
],
"isError": false
}
}
The scenarioName in the response is auto-generated and encodes the isolation key. The states array shows the scenario state progression: Started → turn_1 → __done. Each concurrent session identified by a distinct x-session-id header value advances through its own copy of this state chain.
mock_llm_failover
Creates an LLM failover/retry scenario: the first N requests fail with the HTTP statuses you list, then every subsequent request succeeds with a single provider-correct LLM completion. Use it to test that retry/failover logic — LiteLLM, the Envoy AI Gateway, or an SDK's built-in retries — recovers correctly once the upstream stops erroring. The failures are scripted in order via a scenario state chain, so the scenario is deterministic and repeatable. See LLM Response Mocking for the response wire formats.
provider, path, and failStatuses are required. All other parameters describe the eventual success response and are optional.
| Parameter | Type | Required | Description |
|---|---|---|---|
provider | string (enum) | Yes | LLM provider for the success response: ANTHROPIC, OPENAI, OPENAI_RESPONSES, GEMINI, BEDROCK, AZURE_OPENAI, or OLLAMA (the seven chat providers; the rerank-only COHERE/VOYAGE providers cannot produce a completion — see Rerank) |
path | string | Yes | Request path to match (e.g. /v1/chat/completions) |
failStatuses | array of integer | Yes | Ordered array of HTTP status codes, one per failure attempt (e.g. [503, 503, 429]). The first request returns the first status, the second the next, and so on; after the list is exhausted every further request succeeds. Each status must be 100–599. |
model | string | No | Model name for the success response (e.g. gpt-4o, claude-sonnet-4) |
text | string | No | Success response text content |
toolCalls | array | No | Tool/function calls for the success response. Each entry requires name (string) and accepts optional arguments (string or object). |
stopReason | string | No | Stop reason for the success response (e.g. end_turn, stop) |
usage | object | No | Token usage for the success response. Accepts inputTokens (integer) and outputTokens (integer). |
Example request (two 503s then succeed):
{
"jsonrpc": "2.0",
"id": 32,
"method": "tools/call",
"params": {
"name": "mock_llm_failover",
"arguments": {
"provider": "OPENAI",
"path": "/v1/chat/completions",
"failStatuses": [503, 503],
"model": "gpt-4o",
"text": "Recovered after retry.",
"stopReason": "stop"
}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 32,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"created\",\"count\":3,\"failureAttempts\":2,\"provider\":\"OPENAI\",\"ids\":[\"exp-001\",\"exp-002\",\"exp-003\"]}"
}
],
"isError": false
}
}
The response reports failureAttempts (how many requests fail before recovery) and the ids of the expectations created for the scripted failure-then-success chain.
verify_tool_call
Assert that an agent called a particular tool, by decoding the LLM requests MockServer recorded and inspecting the assistant tool calls in the conversation. Deterministic and read-only — it does not call any LLM. Useful for testing that your agent decided to use the expected tool (and, optionally, with the expected arguments).
| Parameter | Type | Required | Description |
|---|---|---|---|
provider | string | Yes | LLM provider whose recorded requests to inspect (e.g. ANTHROPIC, OPENAI) |
toolName | string | Yes | Name of the tool the agent should have called |
path | string | No | Restrict to requests on this path (e.g. /v1/messages) |
argumentsRegex | string | No | Java regex matched against the tool call's argument JSON |
atLeast | integer | No | Minimum matching calls required (default 1) |
atMost | integer | No | Maximum matching calls allowed |
The result reports count (matching tool calls found) and satisfied (whether the count met the atLeast/atMost constraints); when not satisfied it includes a human-readable message.
{
"jsonrpc": "2.0",
"id": 40,
"method": "tools/call",
"params": {
"name": "verify_tool_call",
"arguments": {
"provider": "ANTHROPIC",
"path": "/v1/messages",
"toolName": "get_weather",
"argumentsRegex": "Paris",
"atLeast": 1
}
}
}
verify_structured_output
Assert that the structured (JSON) output of recorded LLM responses conforms to a JSON Schema. MockServer decodes each recorded response for the given provider, extracts the assistant's output text, and validates it against the schema. Deterministic and read-only — useful for checking that an agent (or a mocked model) returns schema-valid structured output. Responses that produce no text output are reported separately as skippedNoOutput.
| Parameter | Type | Required | Description |
|---|---|---|---|
provider | string | Yes | LLM provider whose recorded responses to validate (e.g. ANTHROPIC, OPENAI) |
schema | string | Yes | JSON Schema the output text of each recorded response must conform to |
path | string | No | Restrict to responses for requests on this path (e.g. /v1/messages) |
The result reports checked, conforming, nonConforming, skippedNoOutput, and allConform, plus a per-response results array (each with conforms and, on failure, the validation error).
{
"jsonrpc": "2.0",
"id": 45,
"method": "tools/call",
"params": {
"name": "verify_structured_output",
"arguments": {
"provider": "ANTHROPIC",
"path": "/v1/messages",
"schema": "{\"type\":\"object\",\"required\":[\"city\",\"temperature\"]}"
}
}
}
explain_agent_run
Summarise an agent run reconstructed from recorded LLM requests — a quick way to see what an agent did without reading raw request bodies. Returns the message count, the number of assistant turns, the ordered sequence of tool-call names (toolCallSequence), the tool-use IDs a result was returned for (toolResultsFor, e.g. "toolu_1"), and the role of the latest message. Deterministic and read-only.
| Parameter | Type | Required | Description |
|---|---|---|---|
provider | string (enum) | Yes | LLM provider whose recorded requests to summarise, or AUTO to detect it from the recorded request paths — useful for proxied traffic where the provider is implicit in the upstream URL |
path | string | No | Restrict to requests on this path |
isolationType | string (enum) | No | Scope the run to a single session by the isolation source the conversation was isolated on: header, query_parameter, or cookie |
isolationKey | string | No | The header/query-parameter/cookie name used to isolate the session (e.g. x-agent-id) |
isolationValue | string | No | The value identifying the session (e.g. agent-001) |
{
"jsonrpc": "2.0",
"id": 41,
"method": "tools/call",
"params": {
"name": "explain_agent_run",
"arguments": { "provider": "ANTHROPIC", "path": "/v1/messages" }
}
}
The result also includes a callGraph object: a nodes array (each with id, kind — a message role or TOOL_CALL — and label) and an edges array (each with from, to, and kind: NEXT for message sequence, INVOKES for a turn's tool calls, RESULT linking a tool call to its returned result). The dashboard Sessions view renders this graph per session.
verify_cost_budget
Asserts that the total estimated USD cost of the LLM responses MockServer has recorded is within a budget — a deterministic, read-only cost gate you can run in CI. It decodes each recorded response for the given provider (via the runtime-LLM client SPI), sums the input/output tokens reported in each response's usage, prices them with MockServer's built-in pricing table, and compares the total against maxCostUsd.
| Parameter | Type | Required | Description |
|---|---|---|---|
provider | string (enum) | Yes | Provider whose recorded responses to total (ANTHROPIC, OPENAI, …) |
maxCostUsd | number | Yes | Cost budget in USD. The assertion passes (withinBudget: true) when the total estimated cost is at or below this value. |
model | string | No | Model id used to price every response (e.g. claude-sonnet-4). If omitted, the model is read from each recorded request body, or from the request path for a native Gemini call (/models/gemini-2.0-flash-001:generateContent). A call that was sent to a Vertex AI host (aiplatform.googleapis.com) is priced at Vertex AI's rates, whether or not you pin the model. Responses whose model has no known price are reported as unpriceable and excluded from the total. |
path | string | No | Only total responses to this request path. |
The result reports checked, skippedNoUsage, unpriceable, totalInputTokens, totalOutputTokens, totalCostUsd, maxCostUsd, withinBudget, budgetCheckAuthoritative, and a per-response results breakdown. The pricing table is public list pricing captured 2025-Q4 and kept in sync with the dashboard — treat totals as an estimate, not an invoice.
Important: withinBudget reflects only the responses that could be priced. When unpriceable > 0 (a recorded model has no known price) or checked == 0 (no responses had usage), the total understates the true cost and a passing withinBudget is not trustworthy. Gate your CI step on budgetCheckAuthoritative (true only when at least one response was checked and every checked response was priced) before trusting withinBudget — pin the model param to guarantee everything is priceable.
{
"jsonrpc": "2.0",
"id": 42,
"method": "tools/call",
"params": {
"name": "verify_cost_budget",
"arguments": { "provider": "ANTHROPIC", "model": "claude-sonnet-4", "maxCostUsd": 0.50 }
}
}
detect_llm_drift
Replay a recorded fixture (cassette) against the live LLM provider and report structural drift in the responses — new fields, removed fields, and changed field types — not semantic/wording differences. This catches the most common VCR problem: a provider changes its response shape and your cassettes silently go stale.
Requires a configured runtime LLM backend (provider environment variables, the mockserver.llmProvider/llmApiKey properties, or a named backend — see Runtime LLM Backend). If none is configured the tool returns {"disabled": true} and does nothing. It fails closed: a network error or non-2xx live response is reported as could-not-check for that exchange, never as drift. Because it calls a real API (keys, tokens, latency, non-determinism), run it in an opt-in or scheduled CI lane — never the per-commit build.
The cassette's provider must match the backend's provider. The tool only ever sends the configured API key to the configured backend. If provider is not the provider of the backend it resolves (the default backend, or the one named by backendName), the call is refused with an error and nothing is sent. To check a cassette recorded against another provider, configure a named backend for that provider and pass its backendName.
| Parameter | Type | Required | Description |
|---|---|---|---|
cassettePath | string | Yes | Path to the recorded fixture JSON whose exchanges are replayed |
provider | string | Yes | LLM provider the cassette was recorded against; must be the resolved backend's provider |
backendName | string | No | Named backend from mockserver.llmBackendsConfig; otherwise the default backend is resolved from env/properties |
The result reports rollup counts (exchanges, drifted, checked, couldNotCheck) and a details array with, per exchange, the addedPaths / removedPaths / typeChangedPaths (or a note when it could not be checked).
{
"jsonrpc": "2.0",
"id": 42,
"method": "tools/call",
"params": {
"name": "detect_llm_drift",
"arguments": { "cassettePath": "fixtures/anthropic-chat.json", "provider": "ANTHROPIC" }
}
}
mock_adversarial_llm_response
Mock a curated adversarial payload as the LLM response, so you can test that your agent resists hostile or malformed model/tool output. A defensive testing aid — the payloads are short, benign test fixtures (not working exploits), and the response is deterministic.
| Parameter | Type | Required | Description |
|---|---|---|---|
provider | string | Yes | LLM provider (the response is rendered in that provider's format) |
path | string | Yes | Request path to match (e.g. /v1/messages) |
payload | string | Yes | Payload id from the catalog (see below) |
model | string | No | Model name to report in the response |
Catalog of payload ids: prompt_injection_ignore_instructions, prompt_injection_tool_redirect, jailbreak_persona, data_exfiltration_request, malformed_json_payload, empty_response, overlong_repetition. An unknown id returns an error listing the available ids.
{
"jsonrpc": "2.0",
"id": 43,
"method": "tools/call",
"params": {
"name": "mock_adversarial_llm_response",
"arguments": { "provider": "ANTHROPIC", "path": "/v1/messages", "payload": "prompt_injection_ignore_instructions" }
}
}
run_mcp_contract_test
Check that a target MCP (Model Context Protocol) server correctly implements the protocol over Streamable HTTP — use it to verify an MCP server you built or changed. The tool runs the required JSON-RPC handshake and core methods against the endpoint (initialize, notifications/initialized, ping, tools/list, and unknown-method rejection) and validates the shape of each response (the JSON-RPC 2.0 envelope and required result fields), never the semantics of any tool. It is fully deterministic and involves no LLM. Each request has a 10-second timeout.
| Parameter | Type | Required | Description |
|---|---|---|---|
targetUrl | string | Yes | Full URL of the target MCP server's Streamable HTTP endpoint (e.g. http://localhost:1080/mockserver/mcp) |
protocolVersion | string | No | MCP protocol version to advertise during initialize (default 2025-06-18; use e.g. 2025-03-26 to test an older revision) |
toolName | string | No | Optional tool to exercise via a tools/call shape check; omit to skip (a tools/call may have side effects on the target) |
Example request:
{
"jsonrpc": "2.0",
"id": 44,
"method": "tools/call",
"params": {
"name": "run_mcp_contract_test",
"arguments": { "targetUrl": "http://localhost:1080/mockserver/mcp" }
}
}
Example response: the result text is a JSON report with an overall status (all_passed or failures_detected), the negotiated protocolVersion and serverInfo, and a per-check results array (each with check, passed, and any validationErrors):
{
"jsonrpc": "2.0",
"id": 44,
"result": {
"content": [
{
"type": "text",
"text": "{\"status\":\"all_passed\",\"protocolVersion\":\"2025-06-18\",\"serverInfo\":{\"name\":\"MockServer\"},\"totalChecks\":5,\"passed\":5,\"failed\":0,\"results\":[{\"check\":\"initialize\",\"passed\":true,\"statusCode\":200,\"detail\":\"session established\"},{\"check\":\"notifications/initialized\",\"passed\":true,\"statusCode\":202},{\"check\":\"ping\",\"passed\":true,\"statusCode\":200},{\"check\":\"tools/list\",\"passed\":true,\"statusCode\":200,\"detail\":\"36 tools advertised\"},{\"check\":\"rejects unknown method\",\"passed\":true,\"statusCode\":200,\"detail\":\"responded with code -32601\"}]}"
}
],
"isError": false
}
}
list_mock_tools
Generates Model Context Protocol tool definitions from the current active response expectations, so an AI agent can discover the mocked endpoints as callable tools without prior knowledge of the API. This tool takes no parameters.
Each response expectation with a concrete method and path matcher becomes one tool entry:
- name — derived from the HTTP method and path in lower snake_case (e.g. get_api_users), deduplicated and truncated to 64 characters.
- description — Mock for METHOD path.
- inputSchema — exposes any query parameters declared on the expectation as string properties, plus an optional body property when the expectation matches on a request body.
- _mockserver — annotation object with method, path, and expectationId so a caller can route an invocation back to the mock.
Expectations whose method or path is a notted matcher, or that have no response action, are skipped.
Example request (no arguments required):
{
"jsonrpc": "2.0",
"id": 50,
"method": "tools/call",
"params": {
"name": "list_mock_tools",
"arguments": {}
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 50,
"result": {
"content": [
{
"type": "text",
"text": "{\"tools\":[{\"name\":\"get_api_users\",\"description\":\"Mock for GET /api/users\",\"inputSchema\":{\"type\":\"object\",\"properties\":{}},\"_mockserver\":{\"method\":\"GET\",\"path\":\"/api/users\",\"expectationId\":\"abc-123\"}},{\"name\":\"post_api_orders\",\"description\":\"Mock for POST /api/orders\",\"inputSchema\":{\"type\":\"object\",\"properties\":{\"body\":{\"description\":\"request body\",\"anyOf\":[{\"type\":\"string\"},{\"type\":\"object\"}]}}},\"_mockserver\":{\"method\":\"POST\",\"path\":\"/api/orders\",\"expectationId\":\"def-456\"}}],\"count\":2}"
}
],
"isError": false
}
}
The count field gives the total number of tool definitions generated. Use this tool to let an agent inspect what a MockServer instance is currently set up to mock — for example, before deciding whether to call create_expectation or to invoke an already-mocked endpoint.
export_optimisation_report
Turns the LLM traffic captured through MockServer's forwarding proxy into a structured optimisation export covering both spend and agent design: either a copy-paste Markdown optimisation brief (paste it into any LLM to get concrete advice) or the structured JSON report bundle. It surfaces deterministic optimisation signals — repeated system prompts, large static context resent every turn, deterministic tool calls that could bypass the model, oversized tool results, output bloat, and duplicate retries — each with token and cost estimates. Export-only, deterministic, and read-only: MockServer never calls an LLM, and secrets are redacted. This is the same report described in full on the AI Agent Optimisation page, which also exposes it as a REST endpoint and a dashboard view.
| Parameter | Type | Required | Description |
|---|---|---|---|
format | string (enum) | No | markdown for the copy-paste optimisation brief (default), json for the structured report bundle, csv for the per-call + totals spreadsheet export, or an eval/fine-tune dataset export of the captured sessions: openai-evals (OpenAI-evals JSONL), fine-tune (chat fine-tune JSONL), or promptfoo (promptfoo test-suite JSON). All formats redact secrets. |
session | string | No | Optional session/grouping key filter (e.g. host:api.openai.com); default is all captured LLM traffic. |
host | string | No | Optional upstream host filter (e.g. api.openai.com). |
provider | string | No | Optional LLM provider filter (e.g. OPENAI, ANTHROPIC). |
Example request:
{
"jsonrpc": "2.0",
"id": 51,
"method": "tools/call",
"params": {
"name": "export_optimisation_report",
"arguments": {
"format": "markdown",
"host": "api.openai.com"
}
}
}
With format: "markdown" the result text carries a brief field (the Markdown document); with format: "json" it carries a structured report object; with format: "csv" it carries a csv field (per-call table plus totals/verdict summary). See LLM Optimisation for the full signal catalogue and worked examples.
diff_agent_runs
A prompt-level diff between two recorded agent runs captured through MockServer — use it to see exactly what changed between a "before" run and an "after" run of the same agent (a prompt edit, a tool change, a model swap). It reconstructs each run's canonical conversation from recorded LLM traffic, normalises the prompts (the same normalisation as a conversation turn's match.normalization, above — whitespace collapsing and JSON key sorting are on by default, lowercasing and volatile-id stripping are off by default), and reports message additions / removals / edits, tool calls added or removed, and the token / cost delta. Deterministic and read-only — MockServer never calls an LLM, and message text is masked for credential shapes before it is compared or returned.
| Parameter | Type | Required | Description |
|---|---|---|---|
before | object | No | Selects the BEFORE run from captured LLM traffic by session, host, and/or provider (the same filter shape as export_optimisation_report). Omit to use all captured traffic. |
after | object | No | Selects the AFTER run — same shape as before. Use a different filter from before (e.g. a different session) so the two sides are actually two different runs. |
normalization | object | No | Optional prompt-normalisation options applied before diffing — the same fields and defaults as the turn-level match.normalization table above: collapseWhitespace (default true), lowercase (default false), sortJsonKeys (default true), dropBuiltInVolatileFields (default false), dropVolatileFields (array of string, none by default). |
Example request:
{
"jsonrpc": "2.0",
"id": 52,
"method": "tools/call",
"params": {
"name": "diff_agent_runs",
"arguments": {
"before": { "session": "run-2026-10-01" },
"after": { "session": "run-2026-10-15" }
}
}
}
The result reports promptChanged, messageCountBefore/messageCountAfter, a messageDiffs array (each with changeType — UNCHANGED/ADDED/REMOVED/CHANGED — role, beforeText, afterText), and toolCallsAdded/toolCallsRemoved arrays whose entries are name(normalisedArguments) fingerprint strings (e.g. get_weather({"city":"paris"})), not bare tool names — a call with the same name but different (normalised) arguments shows up as both added and removed. A tokenDelta object (input/output token and estimated USD cost totals for each side, and their deltas) is included only when both the before and after run have recorded token usage; otherwise the field is omitted.
Low-Level Tools
Low-level tools accept the full MockServer JSON format, giving you complete control over all options. Use these when the high-level tools do not expose a parameter you need.
raw_expectation
Create an expectation using the full MockServer expectation JSON format. This is a passthrough to the PUT /mockserver/expectation REST API.
| Parameter | Type | Required | Description |
|---|---|---|---|
expectation | object | Yes | Full expectation JSON as defined in the REST API specification |
Example request:
{
"jsonrpc": "2.0",
"id": 12,
"method": "tools/call",
"params": {
"name": "raw_expectation",
"arguments": {
"expectation": {
"httpRequest": {
"method": "GET",
"path": "/api/users",
"queryStringParameters": {
"page": ["1"],
"limit": ["10"]
}
},
"httpResponse": {
"statusCode": 200,
"headers": {
"content-type": ["application/json"]
},
"body": "{\"users\": [], \"total\": 0}"
},
"times": {
"remainingTimes": 5,
"unlimited": false
}
}
}
}
}
Schema errors: expectation may also be an array of expectations. Before anything is created, each one is checked against the same expectation JSON schema the REST API uses. If any fails, nothing is created and the result lists every problem in validationErrors: a JSON path, then what is wrong there, prefixed with the expectation's position when an array was sent.
{
"error": true,
"message": "The expectation does not match the MockServer expectation schema: correct each entry of 'validationErrors' (a JSON path, then what is wrong there) and call raw_expectation again",
"validationErrors": [
"expectation 2: $.httpRequest.paht: is not defined in the schema and the schema does not allow additional properties"
]
}
raw_retrieve
Retrieve recorded data using the full MockServer retrieve JSON format. This is a passthrough to the PUT /mockserver/retrieve REST API.
| Parameter | Type | Required | Description |
|---|---|---|---|
requestDefinition | object | No | Request matcher JSON to filter results |
type | string | No | Type of data to retrieve: REQUESTS, REQUEST_RESPONSES, RECORDED_EXPECTATIONS, ACTIVE_EXPECTATIONS, or LOGS |
format | string | No | Response format: JSON, JAVA, or LOG_ENTRIES |
correlationId | string | No | Filter log entries by correlation ID (only applies when type is LOGS). Each incoming request is assigned a unique correlation ID that links all log entries for that request's lifecycle. |
Example request:
{
"jsonrpc": "2.0",
"id": 13,
"method": "tools/call",
"params": {
"name": "raw_retrieve",
"arguments": {
"requestDefinition": {
"path": "/api/.*",
"method": "POST"
},
"type": "REQUEST_RESPONSES",
"format": "JSON"
}
}
}
raw_verify
Verify requests using the full MockServer verification JSON format. This is a passthrough to the PUT /mockserver/verify REST API.
| Parameter | Type | Required | Description |
|---|---|---|---|
verification | object | Yes | Full verification JSON as defined in the REST API specification |
Example request:
{
"jsonrpc": "2.0",
"id": 14,
"method": "tools/call",
"params": {
"name": "raw_verify",
"arguments": {
"verification": {
"httpRequest": {
"method": "POST",
"path": "/api/orders",
"body": {
"type": "JSON_SCHEMA",
"jsonSchema": "{\"type\": \"object\", \"required\": [\"orderId\"]}"
}
},
"times": {
"atLeast": 1,
"atMost": 5
}
}
}
}
}
MockServer MCP Server Capabilities
In addition to the tools above, MockServer's own MCP server (/mockserver/mcp) also implements the prompts and sampling capabilities from the MCP specification. These are available alongside the tools described in this page.
Prompts (prompts/list and prompts/get)
MockServer's MCP server advertises a built-in prompt set. An AI assistant can discover and retrieve these prompts using standard MCP JSON-RPC methods:
| Method | Description |
|---|---|
prompts/list | Returns the configured prompt set — each prompt's name, description, and arguments list (each argument has a name, optional description, and required flag) |
prompts/get | Returns a prompt's message(s) with {{argument}} placeholders substituted from the supplied arguments map. An unknown prompt name returns JSON-RPC error code INVALID_PARAMS (-32602). So does a call that leaves out a required argument, or sends it as null: the error message names each missing argument, for example Missing required argument for prompt 'debug_unmatched_request': path, and data.missingArguments lists them, so you never get back a prompt that still contains an unfilled placeholder. |
Each prompt is a short, fixed set of instructions telling your assistant which MockServer tools to call, in which order, and what each result means. MockServer itself never calls a language model: it only runs the tools, and your own assistant does the reasoning. Every argument is required.
| Prompt | Arguments | Use it when | Tools it chains |
|---|---|---|---|
debug_unmatched_request | method, path | A request got a 404 because no expectation matched it | explain_unmatched_requests |
why_did_verify_fail | method, path | A verification failed and you want to know whether the code under test or the verification is wrong | verify_request (or raw_verify when the verification also matched headers, query parameters or a body), retrieve_recorded_requests, then get_status and retrieve_logs if nothing arrived |
fix_my_expectation | method, path | An expectation does not match the request you meant it for | suggest_expectation_fix (MockServer's own patch, when the request reached MockServer and matched nothing), list_expectations (the expectation's full JSON), then debug_request_mismatch for a hand-made change when no fix is suggested, the patch would not make the expectation match (matchesAfterPatch is false) or it leaves fields unpatched, and raw_expectation (keeping the expectation's id, so it is replaced in place) only after you agree to the change |
why_forward_failed | method, path | A forwarded or proxied request came back as a 502 | explain_forward_failure (the failed forward and the reason its 502 gave), retrieve_logs with its correlationId when MockServer could not name the cause, list_expectations (the forward target's host, port and scheme), then retrieve_request_responses (what MockServer sent instead) when no failed forward is recorded |
create_mock_from_description | description | You want an expectation from a plain-language description of an endpoint | create_expectation or raw_expectation, then list_expectations to confirm |
Facts are kept apart from the assistant's reasoning. The four diagnosis prompts ask the assistant to answer in two sections: Facts from MockServer, holding only values copied from the tool results (status codes, counts, field names, differences and error text), each naming the tool that returned it; and Interpretation, holding the assistant's explanation and suggested change. If a tool returned an error or nothing, the assistant is told to say so rather than guess. Tool results are recomputed when the tools are called, so, for example, a repeated verification also counts requests that arrived after your test's own check ran.
Creating a mock from a description
create_mock_from_description turns a description such as “GET /health returns 200 with the JSON body {"status": "UP"}” into an expectation, with no language model inside MockServer. The prompt tells the assistant to:
- use
create_expectationwhen the description needs only a method, a path, a status code, a response body, response headers, a match count, a time to live or a chaos profile, andraw_expectationwith the full expectation JSON when the request must also match on headers, query parameters, cookies or a body, or the response needs a delay or a template; - on an error, read
messageand, when present,unknownParameters(withsuggestions) orvalidationErrors, correct only the fields they name, and call the tool again, rather than dropping details from the description to make the error go away; - call
list_expectationsto confirm the expectation is active; - report the expectation id MockServer returned, and list separately every detail it assumed because the description did not state it, such as the status code or the content type.
Because a rejected call creates nothing and names the exact field to fix, the assistant can correct itself in one more call instead of creating a mock that silently lacks part of what you described. The error formats are shown under create_expectation and raw_expectation.
Example — list available prompts:
{
"jsonrpc": "2.0",
"id": 100,
"method": "prompts/list",
"params": {}
}
Example — get a prompt with arguments:
{
"jsonrpc": "2.0",
"id": 101,
"method": "prompts/get",
"params": {
"name": "why_forward_failed",
"arguments": {
"method": "GET",
"path": "/api/users"
}
}
}
Example — create a mock from a description:
{
"jsonrpc": "2.0",
"id": 103,
"method": "prompts/get",
"params": {
"name": "create_mock_from_description",
"arguments": {
"description": "POST /orders with a JSON body returns 201 with a Location header of /orders/42"
}
}
}
Sampling (sampling/createMessage)
MockServer's MCP server implements sampling/createMessage, which returns a deterministic mocked completion in the MCP sampling result shape. This lets you test MCP clients that use server-side sampling without connecting to a real LLM.
The response includes role, content (a text content part), model, and stopReason. The model is echoed from the request's modelPreferences.hints when supplied; otherwise a default model name is reported. Supply a mockResponse field in the request params to override the default response text.
Example request:
{
"jsonrpc": "2.0",
"id": 102,
"method": "sampling/createMessage",
"params": {
"messages": [
{ "role": "user", "content": { "type": "text", "text": "What is MockServer?" } }
],
"modelPreferences": {
"hints": [{ "name": "claude-sonnet-4" }]
},
"mockResponse": "MockServer is an open-source HTTP mock and proxy server."
}
}
Example response:
{
"jsonrpc": "2.0",
"id": 102,
"result": {
"role": "assistant",
"content": {
"type": "text",
"text": "MockServer is an open-source HTTP mock and proxy server."
},
"model": "claude-sonnet-4",
"stopReason": "end_turn"
}
}
When mockResponse is omitted, MockServer returns a fixed default completion text. The response is always deterministic and does not call any external LLM.
MCP Resources
In addition to tools, MockServer's MCP server exposes resources that AI assistants can read for context. Resources provide real-time visibility into MockServer's current state.
| Resource URI | Description |
|---|---|
mockserver://expectations | All currently active expectations configured on the server |
mockserver://requests | All recorded requests received by MockServer |
mockserver://logs | Server logs including request matching, expectation creation, and errors |
mockserver://configuration | Current MockServer configuration properties |
mockserver://unmatched | Recent requests that matched no expectation, with ranked closest-expectation diagnostics and remediation hints |
Resources are read-only and are updated in real time. AI assistants can use these to understand the current state of MockServer before taking actions. For example, an assistant might read mockserver://expectations to see what mocks are already configured before creating a new one.
AI Integration — See Also
- MCP Setup — connect Claude Code, Cursor, Windsurf, Cline, or OpenCode to MockServer's built-in MCP endpoint
- MCP Tools Reference — full documentation of all MCP tools, parameters, and resources
- Debugging with AI — workflows for using AI assistants to debug HTTP traffic via MCP
- AI Traffic Inspection — inspect and record LLM/MCP traffic for debugging and deterministic replay
- OpenAPI Contract Verification — verify recorded traffic and run contract/resiliency tests against an OpenAPI spec
- OpenAPI for AI — use MockServer's OpenAPI spec as a fallback for AI tools without MCP support
- AI Protocol Mocking (MCP & A2A) — mock MCP servers and A2A agents your AI application depends on
- LLM Response Mocking — mock LLM API responses from OpenAI, Anthropic, Gemini, Bedrock, Azure OpenAI, and Ollama with provider-correct formatting, streaming, conversations, and chaos
- AI Agent Optimisation — export a structured optimisation brief from captured LLM traffic covering both spend reduction and agent design: detect repeated tokens, deterministic tool calls that could bypass the model, bloated tool surfaces, and retry patterns
- llms.txt — machine-readable index of MockServer documentation for AI assistants and LLMs