Skip to Content
These docs describe donkey-kit v0.3.0. Release notes
Local simulatorMCP faults & captures

Live

MCP faults & captures

The local simulator replays model-route refusals. This page covers its MCP counterpart: refusing an MCP tool call in-process with donkey.simulate_mcp(), and replaying the packaged MCP gateway captures against your own client. For the policies these captures come from, see MCP gateway policies.

MCP tool fault injection

New in 0.2.1, donkey.simulate_mcp() makes your agent’s MCP tool calls hit a captured gateway refusal, with no gateway and no Exchange. It is the MCP counterpart of donkey.simulate(PIIDetected), which still targets model calls only.

You declare the servers and tools the test needs. Inside the block, donkey.tools.discover() returns those servers instead of reading Exchange, so your agent’s own discovery code runs unchanged:

servers = {"acme/crm-tools/1.0.0": [{"name": "lookup_customer"}]} with donkey.simulate_mcp("pii-request", servers=servers): tools = await donkey.tools.discover() agent = build_agent(await tools.langgraph()) await agent.ainvoke(...) # the first tool call is refused as a real PIIDetected
  • servers maps each group_id/asset_id/version ref to its MCP tool descriptors. A descriptor without inputSchema gets an empty object schema. Declared servers are marked governed by a simulated check, and discover()’s filters are not applied to them.
  • discover(locked=True) checks the declared servers against donkey.lock as it does at a live gateway, so you can test drift offline. A missing lock raises ConfigError. A pinned server you did not declare raises ToolLockDrift, and a declared server or tool the lock does not pin is dropped. A tool you declare with a different descriptor raises ToolLockDrift when the set binds. Call donkey.tools.lock(path=...) inside the block to pin the declared servers. See Pinning & lockfile.
  • times=1 (the default) counts injected requests. After that, a tools/call is answered by call_tool(name, arguments). If you pass no call_tool, the answer is a single text item.
  • Bind inside the block. After the block exits, those bindings refuse every request instead of reaching a network. Blocks do not nest.
  • The model client is untouched. Combine it with donkey.simulate(...) to inject into both.

The capture names, the bindings that are supported and the behavior below are the same as for the low-level helper.

Low-level helper for a hand-built ToolSet

donkey_kit.simulator.mcp.simulate_mcp() injects a named captured refusal into one ToolSet you already have, with a baseline you provide. Bind and connect inside the context; bindings made before entry are not intercepted.

import httpx from donkey_kit.simulator.mcp import simulate_mcp # tools is an already-resolved, governed ToolSet. offline_backend is your # httpx request handler for MCP initialization, catalog reads and normal calls. with simulate_mcp(tools, "pii-request", baseline=httpx.MockTransport(offline_backend)): bound = await tools.langgraph() await bound[0].ainvoke(arguments)

The required httpx.MockTransport baseline handles all unmatched traffic. It must implement your test backend’s normal responses; this feature does not provide a full MCP server or mock Exchange discovery. There is no network fallback, environment-proxy routing or cross-endpoint redirect. Existing governance, endpoint-provenance and requester checks are not bypassed.

Capture nameMatching methodExisting behavior
pii-requesttools/callHTTP 403 JSON, request-phase PIIDetected
pii-response-ssetools/callHTTP 403 JSON, response-phase PIIDetected, not an SSE error event
abac-denied, global-accesstools/callHTTP 200 access-denial error, ToolNotInProfile
schema-invalid-argstools/callOrdinary ambiguous JSON-RPC error; no schema-specific type
poisoning-block-listtools/listCaptured SSE catalog error; no poisoning-specific type

times=1 counts matching RPC requests across this scope’s clients, not initialization, notifications or unrelated methods. Calls after that count use the offline baseline. The selector is method-wide: it does not match tool names or arguments, and captured diagnostics can name a different tool than your test. Nesting restores the outer factory. Filtered and approval-derived sets share the scope; unrelated ToolSets and model calls are unaffected. Do not overlap independent simulation contexts on the same ToolSet owner.

Every injected response has x-donkey-simulator: true. Status, semantic headers, content type and error payload come from the capture, but the response ID is adapted to the outgoing request so native MCP sessions can correlate it. JSON is reserialized, including the SSE data envelope: this is not byte-verbatim replay. Original packaged files remain unchanged.

Native binding coverage is LangGraph, LlamaIndex, Anthropic, Microsoft Agent Framework, the OpenAI Agents SDK and Strands; other bindings refuse before connecting. Offline Agent Framework injection requires stable agent-framework-core>=1.24.0 and mcp>=2.3.0. OpenAI Agents SDK injection requires stable openai-agents>=0.20.0 and mcp>=2.3.0. Strands injection requires stable strands-agents>=1.64.0 and mcp>=2.3.0. Older or prerelease stacks raise ConfigError before authentication or connection. This restriction applies only to simulation, not normal production bindings. LlamaIndex URLs selecting its legacy SSE transport (/sse, /sse/ or transport=sse) also refuse because that transport ignores the injected client. A captured HTTP failure can end Anthropic’s persistent MCP session and be raised again during context teardown. Wrap the whole binding context in typed_refusals() and reconnect before a later call. Keep sessions inside the simulation context. Clients retained past exit fail closed instead of reconnecting to the gateway. Raw exception responses and native framework diagnostics remain sensitive.

For Agent Framework, wrap native invocation in typed_refusals() and use each server object as an async context manager. Simulation owns a fresh HTTP client for each connection and closes it when that connection ends; the offline baseline remains yours. If you cancel connect(), its framework-owned connection attempt can continue until the offline backend finishes. The framework then cleans up a new connection whose caller was cancelled; await tool.close() to wait for cleanup deterministically before leaving the simulation context. Cancellation does not guarantee immediate cleanup. Whole-server approval and collision-renaming limitations still apply.

from donkey_kit import typed_refusals with simulate_mcp(tools, "pii-request", baseline=httpx.MockTransport(offline_backend)): bound = await tools.agent_framework() with typed_refusals(): async with bound[0] as server: await server.functions[0].invoke(arguments=arguments)

For byte-verbatim HTTP replay without native session correlation, use the packaged captures below. Neither form establishes new live gateway evidence.

For the OpenAI Agents SDK, connect each server inside the simulation scope and wrap native calls in typed_refusals(). The framework owns and closes a fresh HTTP client per connection, including failed initialization and cancelled connection attempts; the offline baseline remains yours. Its default zero retries, filtering and whole-server approval/collision limitations are unchanged.

with simulate_mcp(tools, "pii-request", baseline=httpx.MockTransport(offline_backend)): bound = await tools.openai_agents() with typed_refusals(): async with bound[0] as server: await server.call_tool("calculate", arguments)

For Strands, bind inside the scope and enter each native MCPClient as a synchronous context manager. Its background thread uses a fresh scoped HTTP client on every connection, including an in-scope restart. The transport closes that client; the offline baseline remains yours. A synchronous baseline handler can run on the native thread, so make shared test state thread-safe.

with simulate_mcp(tools, "pii-request", baseline=baseline): bound = await tools.strands() with bound[0] as client: result = client.call_tool_sync("test-call", "calculate", {}) assert result["status"] == "error" assert client.call_tool_sync("next-call", "calculate", {})["status"] == "success"

Strands returns generic status: error tool results for the captured PII, access-denial and schema failures. Structured policy fields and typed exceptions are lost, so typed_refusals() cannot recover them and DDK never infers a policy from the text. The poisoning capture instead raises the native MCPError from list_tools_sync(); it remains ambiguous. Filtering and whole-server approval/collision restrictions are unchanged.

Keep the native context inside the simulation scope. Retained tool calls fail after scope exit and cannot reach the baseline or gateway; cached descriptors can still be inspected. Close the native session even after a failure. On the tested Strands 1.64.0 / MCP 2.3.0 stack, stopping failed, cancelled or expired sessions can emit an upstream RuntimeWarning that MCPClient.stop.<locals>._set_close_event was never awaited, although the HTTP clients close and background threads exit. DDK does not patch or suppress this warning. Bound native-thread tests with a subprocess deadline so an upstream cleanup regression cannot hang your test suite.

Reusable offline baseline

Use mcp_baseline() when you need initialization, tool discovery and ordinary tool results without writing an HTTP handler. It returns a caller-owned httpx.MockTransport for one exact endpoint. Supply MCP tool descriptors and a synchronous call_tool(name, arguments) handler returning an MCP CallToolResult object as a dictionary:

from donkey_kit.simulator.mcp import mcp_baseline, simulate_mcp endpoint = tools.servers[0].endpoint_url baseline = mcp_baseline( endpoint, server_protocol_version="2025-06-18", tools=[{ "name": "calculate", "description": "Return an offline result", "inputSchema": {"type": "object", "properties": {}}, }], call_tool=lambda name, arguments: { "content": [{"type": "text", "text": "success"}], }, ) with simulate_mcp(tools, "pii-request", baseline=baseline): bound = await tools.agent_framework() with typed_refusals(): async with bound[0] as server: await server.functions[0].invoke(arguments={})

server_protocol_version controls the server’s initialize response; it defaults to 2025-06-18. It does not change the client’s requested version. The native MCP SDK accepts or rejects that response, so an unsupported string is useful for negative negotiation tests. This does not change package-version requirements, translate captures, or establish conformance of a complete server to that version.

The helper is a stateless JSON-response baseline, not a full MCP server simulator. It supports initialization, tool listing/calls, initialized notifications and ping. Unknown tools/invalid arguments envelopes return JSON-RPC -32602; unknown methods return -32601. It does not validate arguments against inputSchema, implement policies, SSE streams, resources, prompts or session IDs. Handler exceptions propagate to your test; handlers must not perform network calls. For richer behavior or multiple endpoints, continue supplying your own httpx.MockTransport.

Packaged MCP captures

Separately, the package data contains 15 captured MCP responses: 13 policy envelopes in anypoint/mcp_policies and two access-denial header/body pairs in anypoint/mcp_access. These captures are new in 0.2.1. Use donkey_kit.simulator.fixtures.fixture_bytes() to read them without depending on a repository checkout’s test files.

This is raw offline replay, not a donkey mock route or a donkey-sim/ sentinel, and not bound-tool simulate() injection. There is no session negotiation or request-ID rewriting: captured JSON-RPC IDs and SSE framing stay unchanged. It tests handling of a selected response, not policy enforcement or end-to-end framework behavior.

The example decodes the pii-request.json capture envelope, then encodes its body string as UTF-8; the response body is not JSON-reserialized. Replay only the safe headers from replay_headers(), restore content-type, and add x-donkey-simulator: true to the replay, never to the capture. The URL is a reserved example address, not a real endpoint; the explicit MockTransport handles the call entirely offline, with no server or credentials.

import json import httpx from donkey_kit import PIIDetected, jsonrpc_refusal from donkey_kit.simulator.fixtures import Fixture, fixture_bytes, replay_headers capture = json.loads(fixture_bytes("anypoint/mcp_policies", "pii-request.json")) fixture = Fixture( shape="mcp-capture:pii-request", status=capture["status"], headers=capture["headers"], body=capture["body"].encode("utf-8"), content_type=capture["headers"]["content-type"], ) def respond(request: httpx.Request) -> httpx.Response: return httpx.Response( fixture.status, headers={ **replay_headers(fixture), "content-type": fixture.content_type, "x-donkey-simulator": "true", }, content=fixture.body, ) with httpx.Client(transport=httpx.MockTransport(respond), trust_env=False) as client: response = client.post("https://gateway.example/mcp/") assert response.content == fixture.body assert response.headers["x-donkey-simulator"] == "true" refusal = jsonrpc_refusal(response.json(), response=response) assert isinstance(refusal, PIIDetected) assert refusal.phase == "request" assert refusal.response is response

For access-denial pairs, read the header file with fixture_bytes() and use parse_status() and parse_headers() from the same module; read the body file as bytes. Schema and poisoning errors cannot safely identify a gateway policy from generic codes or diagnostic text, so jsonrpc_refusal() leaves those captures untyped. Despite its name, pii-response-sse.json is HTTP 403 application/json, not an SSE error event. The matcher takes a parsed JSON-RPC envelope, not raw SSE bytes. See MCP gateway policies for the evidence boundaries and framework-specific refusal behavior.

Next steps

Last updated on