# Build a Production-Style AI Agent Harness in Python: SQLite Checkpoints, MCP Tools & Live Trace UI
Most tutorials stop the moment an LLM calls its first function. In a real backend, that is where the actual engineering starts.
If you wire an LLM straight to your database or billing endpoints inside a `while True` loop, three things break fast: a confused model can loop until your token budget is gone, a process restart mid-workflow wipes in-memory state, and a network timeout on a write tool can trigger a duplicate refund when the client retries.
In this guide, we build a complete, production-style AI agent harness in plain Python without heavy agent frameworks. Our working use case is a customer support refund assistant that:
1. Searches local markdown policy files (while blocking `../` path traversal).
2. Queries customer orders from SQLite using parameterized `SELECT` queries only.
3. Submits guarded refund requests over the official Model Context Protocol (`mcp==2.3.0`) with human approval gates and `UNIQUE` idempotency keys (`HTTP 409` on payload mismatch).
4. Saves session history and step checkpoints in SQLite WAL inside explicit transactions so an interrupted run resumes without repeating writes.
5. Streams every LLM and tool span (`latency_ms`, `input_tokens`, `output_tokens`, `estimated_cost_usd`) to a dark FastAPI Server-Sent Events (SSE) trace UI.
If you already built our LLM Cost Budget Gateway in Python, this harness slots straight behind that gateway as the execution layer.
—
Model vs. Agent vs. Harness (And When Frameworks Make Sense)
Developers often treat the model, the agent, and the runtime as one blob. Separating them makes every failure mode obvious:
- Base Model (LLM): Stateless next-token predictor. Given messages and tool schemas, it returns text or a proposed tool call.
- Agent (Decision Loop): The multi-step loop that feeds tool observations back into the model until it reaches an answer.
- Harness (Engineering Runtime): The outer boundary around the loop. It enforces step caps, validates tool arguments, manages transactions and crash-resume checkpoints, applies timeouts, and records traces.
When should you use a framework like LangGraph or CrewAI? If you are prototyping a complex multi-agent graph, need prebuilt connectors, or want visual studio tooling out of the box, frameworks save time. The trade-off is indirection: implicit retry loops and hidden prompt wrappers make production incidents harder to trace. Writing a plain Python harness takes around 200 lines of core logic and keeps every failure boundary in plain sight.
—
Project Architecture & Pinned Dependencies
We use an isolated Python 3.11 environment (the official `mcp` 2.x SDK requires Python 3.10+) with exact pinned versions:
mcp==2.3.0
fastapi==0.165.0
uvicorn==0.55.0
openai==3.60.0
pydantic==2.14.4
httpx==0.29.0
pytest==9.2.0
Note an important protocol change in `mcp==2.3.0`: the server helper previously named `FastMCP` in `mcp` 1.x was renamed to `MCPServer` under `mcp.server.mcpserver`. Always check the installed SDK docs rather than relying on older blog snippets.
The project layout keeps each responsibility in its own small module:
- `data/seed.py` — Seeds fake demo orders (`ORD-1001`, `ORD-1002`, `ORD-1003`) and the `refunds` table with a `UNIQUE` `idempotency_key` constraint.
- `memory.py` — SQLite WAL persistence for `runs`, `messages`, `step_checkpoints`, and `trace_spans`.
- `mcp_server.py` — Official `MCPServer` stdio process exposing `search_policy`, `query_order`, and `create_refund`.
- `tools.py` — `stdio_client` + `ClientSession` wrapper with Pydantic schemas, timeouts, bounded retries, and secret redaction.
- `harness.py` — Bounded 6-step loop with explicit exit reasons.
- `app.py` — FastAPI server with SSE live trace UI (`/events`), `/refunds` endpoint, and a Judge opinion button.
—
Step 1: Why SQLite WAL Alone Does Not Give Crash-Resume
Turning on `PRAGMA journal_mode=WAL;` is great advice for FastAPI apps, because it allows concurrent readers alongside a single writer and protects physical database pages during a power loss. However, WAL alone does not give an AI agent crash-resume.
WAL protects *disk pages*, not *logical progress*. If your process crashes after step 2 finishes, a restarted worker still needs to know which logical step committed and what observation came back. That requires two things together:
1. Explicit transactions (`BEGIN IMMEDIATE … COMMIT` with `ROLLBACK` on error) so message history and checkpoint rows update atomically.
2. A `step_checkpoints` table keyed by `(run_id, step_num)` so resuming starts at `last_step + 1`.
Here is the core checkpoint write in `memory.py`:
def save_step_checkpoint(
self,
run_id: str,
session_id: str,
step_num: int,
new_messages: list[dict],
tool_name: str | None = None,
tool_args: dict | None = None,
observation: dict | None = None,
) -> None:
conn = self._connect()
now = time.time()
try:
conn.execute("BEGIN IMMEDIATE;")
for msg in new_messages:
conn.execute(
"INSERT INTO messages (session_id, role, content_json, created_at) VALUES (?, ?, ?, ?)",
(session_id, msg.get("role", "assistant"), json.dumps(msg), now),
)
conn.execute(
"""
INSERT OR REPLACE INTO step_checkpoints
(run_id, step_num, tool_name, tool_args_json, observation_json, status, created_at)
VALUES (?, ?, ?, ?, ?, 'committed', ?)
""",
(
run_id,
step_num,
tool_name,
json.dumps(tool_args) if tool_args is not None else None,
json.dumps(observation) if observation is not None else None,
now,
),
)
conn.execute("COMMIT;")
except Exception:
conn.execute("ROLLBACK;")
raise
finally:
conn.close()
Table of Contents
- 1 The Danger Window: Crashing After Write, Before Checkpoint
- 2 Blocking Path Traversal and Arbitrary SQL
- 3 Idempotency Keys and HTTP 409 Conflict Detection
- 4 Timeouts Do Not Prove Failure
- 5 Recorded Demo Run Metrics
- 6 What Is Missing for Real Production
- 7 Why not just use SQLite WAL without a checkpoints table?
- 8 Why did the MCP tool calls take around 520 ms locally?
- 9 Can I run this harness with a local LLM instead of OpenAI?
The Danger Window: Crashing After Write, Before Checkpoint
Consider three places a worker can die during a refund step:
1. Before the write: Nothing changed. Retrying the step is safe.
2. After the checkpoint: Everything committed. Resuming skips straight to the next step.
3. After the refund write succeeds, before the checkpoint commits: On resume, `step_checkpoints` has no row for step 1, so the harness re-runs step 1.
If your refund service is not idempotent, case 3 creates a double refund. That is why checkpoints and idempotency keys must work together.
—
Step 2: Guarded MCP Tools, Path Safety & HTTP 409 Idempotency
Rather than calling raw Python functions inside the harness process, we isolate tools behind an official `MCPServer` subprocess (`mcp_server.py`) communicating over `stdio`. Each tool enforces strict boundaries—a pattern we also recommend in our guide on Tool Calling in AI Agents.
Blocking Path Traversal and Arbitrary SQL
`search_policy` resolves the requested path and verifies containment inside `POLICIES_DIR` with `Path.is_relative_to`, blocking `../../.env` escapes. `query_order` accepts only an `order_id` string and passes it to a parameterized `SELECT` statement:
@mcp.tool()
def search_policy(filename: str, query: str) -> str:
"""Search a markdown policy file inside data/policies/. Blocks path traversal."""
candidate = (POLICIES_DIR / filename).resolve()
if not candidate.is_relative_to(POLICIES_DIR) or not candidate.is_file():
return json.dumps({"error": "Blocked: invalid or outside-sandbox policy path", "filename": filename})
text = candidate.read_text(encoding="utf-8")
q = query.strip().lower()
matches = [line for line in text.splitlines() if q in line.lower()]
return json.dumps({"file": candidate.name, "matches": matches or text.splitlines()[:6]})
@mcp.tool()
def query_order(order_id: str) -> str:
"""Read-only parameterized order lookup by order_id. Arbitrary SQL is not accepted."""
conn = sqlite3.connect(str(DB_PATH), timeout=10.0)
conn.row_factory = sqlite3.Row
try:
row = conn.execute(
"SELECT order_id, customer_name, item_name, amount_usd, status, delivered_days_ago FROM orders WHERE order_id = ?",
(order_id.strip(),),
).fetchone()
if row is None:
return json.dumps({"found": False, "order_id": order_id})
return json.dumps({"found": True, "order": dict(row)})
finally:
conn.close()
Idempotency Keys and HTTP 409 Conflict Detection
Our `refunds` table puts a `UNIQUE` constraint on `idempotency_key` and stores a SHA-256 `payload_hash` of `(order_id, amount_usd, reason)`:
- New key: Inserts the refund row and returns `HTTP 200` (`replayed: false`).
- Same key + same payload hash: Returns the original refund record (`HTTP 200`, `replayed: true`).
- Same key + different payload hash: Rejects the mutation with `HTTP 409 Conflict`.
payload = {"order_id": order_id, "amount_usd": round(float(amount_usd), 2), "reason": reason.strip()}
payload_hash = hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
existing = conn.execute(
"SELECT * FROM refunds WHERE idempotency_key = ?",
(idempotency_key,),
).fetchone()
if existing is not None:
conn.execute("COMMIT;")
if existing["payload_hash"] != payload_hash:
return 409, {
"error": "Idempotency conflict: same key used with different payload",
"idempotency_key": idempotency_key,
}
return 200, {
"refund_id": existing["refund_id"],
"order_id": existing["order_id"],
"amount_usd": existing["amount_usd"],
"status": existing["status"],
"idempotency_key": existing["idempotency_key"],
"replayed": True,
}
Timeouts Do Not Prove Failure
In `tools.py`, `call_mcp_tool` wraps each `stdio_client` + `ClientSession` call in `asyncio.wait_for(…, timeout=timeout_sec)`. A timeout only proves you stopped waiting—the refund server may have committed the write right before the connection stalled. Because of that, automatic retries are strictly bounded (`max_retries=1`) and allowed only on read-only tools or idempotent writes.
—
Step 3: The Bounded 6-Step Execution Loop (`harness.py`)
Our core agent loop in `harness.py` stays small and readable, enforcing a hard `MAX_STEPS = 6` cap and six explicit exits:
1. `final_answer` — Model returned text without a tool call.
2. `invalid_tool_call` — Unknown tool name or Pydantic argument validation failure.
3. `approval_required` — Write tool (`create_refund`) paused because `approved` is `False`.
4. `timeout` — MCP tool call exceeded `tool_timeout_sec` after bounded retries.
5. `model_error` — LLM SDK raised an exception.
6. `step_limit` — Loop reached step 6 without a final answer.
for step in range(start_step, MAX_STEPS + 1):
history = memory.load_messages(session_id)
t0 = time.perf_counter()
try:
turn = call_model(history, model_name)
except Exception as exc:
emit(memory.add_span(run_id, step, "llm", model_name, "error", (time.perf_counter() - t0) * 1000, detail={"error": redact_secrets(str(exc))}))
memory.finish_run(run_id, "failed", "model_error", None)
return {"run_id": run_id, "exit_reason": "model_error", "error": redact_secrets(str(exc))}
cost = estimate_cost_usd(model_name, turn.input_tokens, turn.output_tokens)
emit(memory.add_span(run_id, step, "llm", model_name, "ok", (time.perf_counter() - t0) * 1000, turn.input_tokens, turn.output_tokens, cost))
if not turn.tool_name:
memory.save_step_checkpoint(run_id, session_id, step, [{"role": "assistant", "content": turn.text or ""}])
memory.finish_run(run_id, "completed", "final_answer", turn.text or "")
return {"run_id": run_id, "exit_reason": "final_answer", "final_answer": turn.text or "", "resumed": state["resumed"]}
raw_args = dict(turn.tool_args or {})
if turn.tool_name == "create_refund" and approved:
raw_args["approved"] = True
ok, parsed_or_err = validate_tool_call(turn.tool_name, raw_args)
if not ok:
emit(memory.add_span(run_id, step, "tool", turn.tool_name, "invalid_tool_call", 0.0, detail={"error": parsed_or_err}))
memory.finish_run(run_id, "failed", "invalid_tool_call", None)
return {"run_id": run_id, "exit_reason": "invalid_tool_call", "error": parsed_or_err}
—
Step 4: FastAPI Live Trace UI, Secret Redaction & Judge Opinion
`app.py` serves a dark-mode trace dashboard (`#0D1117` background, `#161B22` panels) backed by `GET /events` using Server-Sent Events. Every span is passed through `redact_secrets()` before broadcasting so credential fields (`api_key`, `access_token`, `secret`, `password`) and `sk-…` strings become `[REDACTED]`, while integer `input_tokens` and `output_tokens` remain intact.
Token cost estimates read from `pricing.json` (labelled with `date_checked: 2026-11-29`). When a model is missing from the config or a tool span has no token count, the UI displays `"unknown"` instead of guessing.
Recorded Demo Run Metrics
Running the support prompt `"Check policy and refund ORD-1001 ($129.00, damaged keycaps)"` with the deterministic demo model against real `mcp_server.py` stdio subprocesses and SQLite produced these recorded spans:
| Step | Type | Name | Latency (ms) | In / Out Tokens | Est. Cost (USD) |
| :-: | :— | :— | :-: | :-: | :-: |
| 1 | `tool` | `search_policy` | 535.88 ms | – | `unknown` |
| 2 | `tool` | `query_order` | 519.97 ms | – | `unknown` |
| 3 | `tool` | `create_refund` | 511.23 ms | – | `unknown` |
| 4 | `llm` | `gpt-4o-mini` | – | 270 / 20 | `$0.000053` |
Notice why each MCP tool span takes ~510–536 ms: `tools.py` spawns a fresh `mcp_server.py` stdio subprocess per call. That isolation is great for a local demo, and easy to speed up later by keeping a persistent MCP `ClientSession` pool open.
The Judge button (`POST /judge`) sends redacted spans to an LLM for a `PASS` / `FAIL` verdict with a one-sentence reason, and explicitly labels the output `"Model opinion (not a deterministic test)"` so it is never confused with a pytest assertion.
—
Step 5: Verified Pytest Output & Production-Style Limitations
All 8 deterministic tests pass in 7.11 seconds using a fake model (zero API cost) wired to the real MCP stdio server and SQLite WAL database:
tests/test_harness.py::test_normal_answer PASSED [ 12%]
tests/test_harness.py::test_invalid_tool_call PASSED [ 25%]
tests/test_harness.py::test_step_limit PASSED [ 37%]
tests/test_harness.py::test_tool_timeout PASSED [ 50%]
tests/test_harness.py::test_crash_and_resume_no_duplicate PASSED [ 62%]
tests/test_harness.py::test_duplicate_write_idempotent_replay PASSED [ 75%]
tests/test_harness.py::test_409_conflict_different_payload PASSED [ 87%]
tests/test_harness.py::test_path_traversal_blocked PASSED [100%]
============================== 8 passed in 7.11s ===============================
What Is Missing for Real Production
We call this harness production-style rather than production-ready because five real-world layers are intentionally omitted from a local tutorial:
1. Authentication and RBAC: `/run` and `/refunds` have no user auth or per-tenant authorization.
2. Persistent MCP Connection Pooling: Eliminates the ~500 ms per-call stdio subprocess startup cost.
3. Background Worker Queue: Long-running agent loops should run on a queue rather than inside an HTTP request handler.
4. Multi-Node Database Replication: Single-file SQLite WAL scales well on one host, not across multiple stateless containers.
5. Centralized Monitoring & Security Audit: Exporting spans to OpenTelemetry collectors with alerting and formal threat review.
—
Frequently Asked Questions
Why not just use SQLite WAL without a checkpoints table?
WAL protects physical database pages and prevents reader/writer lock errors, but it does not track which logical step in your Python loop completed. Combining `BEGIN IMMEDIATE` transactions with `step_checkpoints` gives true step-level crash-resume.
Why did the MCP tool calls take around 520 ms locally?
Because `call_mcp_tool` spawns a fresh `mcp_server.py` subprocess over `stdio` on every call. Keeping one persistent `ClientSession` alive in a pool drops that overhead dramatically.
Can I run this harness with a local LLM instead of OpenAI?
Yes. `harness.py` uses the official `openai` SDK and reads `OPENAI_BASE_URL` and `MODEL_NAME` from environment variables, so you can point it at `http://localhost:11434/v1` with Ollama without changing the loop.




Leave a Reply