Harness Engineering — How the Agent Runs
Engineering the scaffold that turns a language model into an agent. MCP servers, tool definitions, memory architecture, and orchestration patterns.
Concepts
MCP & Tools
Memory Systems
Orchestration
Discipline 02 of 3: Harness Engineering is the layer between the LLM and the world. Context Engineering determines what the agent knows; Harness Engineering determines what it can do and how it reasons about doing it. Agent Testing then proves the combination works.
What a Harness Is
The core idea
An LLM alone is a text function. A harness wraps it with tool access, memory, state, and an execution loop — turning a text function into an agent that can observe, reason, and act over multiple steps.
What it is NOT
The harness is not the prompt. It is not the data. It is not the model. It is the runtime: the code and infrastructure that orchestrates calls, manages tool results, routes between agents, and persists state.
Why it fails independently
A perfect context layer with a broken harness still fails. A well-tested harness with no context governance still hallucinates. The disciplines are coupled but separable — each has its own engineering surface and its own class of bugs.
The production gap
Most demos skip harness engineering entirely — one prompt, one tool call, one reply. Production agents have retry logic, fallback routing, budget enforcement, latency budgets, and audit trails. This gap is where most agentic projects fail.
The Agent Stack — Four Layers
4
Orchestration Layer
Multi-step reasoning loop. Plans, calls tools, observes results, decides next action. Implements ReAct, Plan-and-Execute, or multi-agent routing.
3
Tool / MCP Layer
Function schemas exposed to the model. MCP servers, API wrappers, database connectors. Defines what actions are available and how results are returned.
2
Memory Layer
In-context window, episodic (conversation history), semantic (vector retrieval), procedural (fine-tuned behaviours). Governs what the agent remembers across calls and sessions.
1
Context Layer (Discipline 01)
Semantic models, ontologies, governed metrics. Provided by Context Engineering — the harness consumes this layer but does not own it.
Anatomy of an Agent Turn
# Simplified ReAct loop — one agent turn
def agent_turn(user_input, context, memory, tools):
## 1. Compose context window
messages = memory.load_episodic() # past turns
messages += context.retrieve(user_input) # semantic retrieval
messages.append({"role": "user", "content": user_input})
## 2. LLM call with tool definitions
response = llm.call(messages, tools=tools.schemas())
## 3. Tool execution loop
while response.has_tool_calls():
for call in response.tool_calls:
result = tools.execute(call.name, call.args) # harness executes
messages.append(tool_result(call.id, result))
response = llm.call(messages, tools=tools.schemas())
## 4. Memory update
memory.save_episodic(user_input, response.text)
return response.text
Key Engineering Concerns
| Concern | What it means in practice | Common failure |
| Tool budget | Max tool calls per turn; per-session cost ceiling | Infinite loop; runaway spend |
| Latency budget | Timeout per tool; overall turn deadline | Hanging agent; user-facing timeout |
| Retry & fallback | Transient tool failure → retry with backoff; then fallback tool or graceful degradation | Single point of failure; silent data loss |
| State isolation | Separate context per user session; no cross-contamination | User A sees User B's data |
| Audit trail | Log every tool call, arguments, result, latency, model version | Undiagnosable failures in production |
| Tool schema drift | Tool API changes without schema update → model confusion | Hallucinated arguments; silent wrong calls |
| Context window overflow | Multi-turn accumulation exceeds model max tokens | Truncation mid-reasoning; lost tool results |
Model Context Protocol (MCP) — Anthropic's open standard for connecting LLMs to tools and data sources. MCP defines a client/server architecture where MCP clients (Claude Desktop, IDEs, agents) connect to MCP servers that expose Tools, Resources, and Prompts.
MCP Architecture
MCP Host
The application running the LLM — Claude Desktop, Cursor, your agent framework. Manages one or more MCP client connections. Owns the conversation loop.
MCP Client
Lives inside the host. Maintains a 1:1 connection with an MCP server. Routes tool calls and resource reads to the right server. Handles connection lifecycle.
MCP Server
A lightweight process exposing capabilities via the MCP protocol. Can expose Tools (actions), Resources (data), and Prompts (reusable templates). Stateless or stateful.
Transport
stdio (local process, used by Claude Desktop), HTTP+SSE (remote servers, web agents), WebSocket (bidirectional streaming). MCP 2025-03-26 added Streamable HTTP transport.
MCP Server Capabilities
| Capability | What it exposes | Model interaction | Example |
| Tools |
Executable actions with typed input/output schemas |
Model calls tool by name; server executes; result returned to model |
run_query(), create_file(), send_email() |
| Resources |
Data sources accessible via URI (text or binary) |
Model or host reads resource via URI; content injected into context |
file:///repo/README.md, postgres://db/schema |
| Prompts |
Reusable parameterized message templates |
Host fetches prompt template, injects parameters, adds to messages |
code-review template, SQL generation template |
| Sampling 2025+ |
Server-initiated LLM calls via the host |
Server requests model completion; host routes through its LLM |
Agentic servers that themselves need to reason |
Tool Definition — Best Practices
# Well-structured MCP tool definition (Python SDK 1.x)
from mcp.server import FastMCP
mcp = FastMCP("financial-tools")
@mcp.tool()
async def get_account_balance(
account_id: str,
as_of_date: str | None = None,
currency: str = "USD"
) -> dict:
"""
Return the balance for a single account.
Args:
account_id: Unique account identifier (format: ACC-XXXXXX)
as_of_date: ISO 8601 date for historical balance (default: today)
currency: ISO 4217 currency code for conversion (default: USD)
Returns:
balance: Current balance as float
currency: Currency of the returned balance
last_updated: ISO 8601 timestamp of the last transaction
"""
# Implementation ...
Tool description quality = model accuracy. The description is the model's only guide to when and how to call the tool. Vague descriptions cause wrong-tool selection. Missing argument constraints cause hallucinated values. Always document: when to use, what each argument means, valid ranges, and what the return value contains.
Tool Design Patterns
| Pattern | When to use | Anti-pattern |
| Narrow tools |
One tool = one semantic action. get_balance() ≠ get_account_summary() |
Swiss-army-knife tools with 15 optional params — model rarely calls them correctly |
| Explicit error codes |
Return structured errors the model can reason over: {"error": "account_not_found"} |
Raising exceptions that propagate as raw stack traces — model cannot act on them |
| Idempotent reads vs. writes |
Mark read-only tools clearly; require explicit confirmation args on destructive writes |
Silent side-effects on tools the model thinks are reads |
| Bounded output |
Cap returned rows/bytes; include a next_cursor for pagination |
Returning 50,000 rows into the context window |
| Human-in-the-loop gate |
Inject a confirm_action() tool before irreversible operations |
Direct execution of delete/send/pay without approval step |
| Tool versioning |
Name versions explicitly (v1_get_balance vs get_balance) during migrations |
Silent schema changes that break cached reasoning in long-running agents |
Anthropic vs OpenAI Tool Use — Comparison
| Aspect | Anthropic (Claude) | OpenAI (GPT-4o / o3) |
| Schema format | JSON Schema (name, description, input_schema) | JSON Schema (name, description, parameters) |
| Parallel tool calls | Yes — multiple tool_use blocks in one response | Yes — parallel_tool_calls flag (default on) |
| Tool choice | auto | any | {type:"tool", name:...} | auto | none | required | {type:"function",...} |
| Computer use | Beta API (bash, text_editor, computer tools) | Via CUA model (computer-use-preview) |
| MCP support | Native: Claude Desktop, Claude API MCP connector | MCP via OpenAI Agents SDK (not native API) |
| Token counting | count_tokens() with tools[] parameter | Not directly exposed; estimate from schema size |
MCP Registry & Ecosystem (2025)
Anthropic MCP Servers
Official servers: filesystem, fetch, git, GitHub, Google Drive, PostgreSQL, Slack, Brave Search, SQLite, Puppeteer. All open-source on github.com/modelcontextprotocol/servers.
MCP Registry
registry.mcp.so — community registry of 3,000+ servers (Jun 2025). Includes commercial servers from Cloudflare, Atlassian, AWS, Stripe, Notion.
Auth: OAuth 2.1 (2025-03-26)
MCP spec added OAuth 2.1 for remote server authentication. Servers can now require user consent before granting tool access — critical for SaaS tool integrations.
MCP Inspector
Official debugging tool (npx @modelcontextprotocol/inspector). Inspect, test, and monitor MCP server connections locally before deploying to agents.
Memory is what an agent can access beyond the current prompt. The five memory types operate at different timescales and have different engineering costs. Most production failures come from conflating them or choosing the wrong type for a use case.
The Five Memory Types
Everything in the current context window: system prompt, conversation history, tool results, retrieved documents. Instantaneous — no retrieval cost. Lost at session end. Bounded by model max tokens (200K for Claude 3.7).
Unlimited reads
Token budget
No persistence
Conversation history and past interactions, stored externally and selectively loaded into context. Enables continuity across sessions. Key engineering decision: what to summarise vs. what to store verbatim.
Postgres / SQLite
Summarisation
Recency bias
Facts, documents, and knowledge embedded as vectors. Retrieved by similarity to the current query. Powers RAG pipelines. Accuracy depends heavily on chunking strategy, embedding model, and hybrid search configuration.
Pinecone
Weaviate
pgvector
Chroma
How-to knowledge baked into the model via fine-tuning or exposed as tool recipes. Expensive to update — changing procedural memory means retraining or deploying a new tool version. Use sparingly; prefer semantic memory for content that changes.
Fine-tuning
System prompt rules
Tool definitions
Structured data the agent reads and writes via tools. Not embedded or summarised — raw, queryable, authoritative. The agent manages explicit external state: task lists, user preferences, running totals, intermediate artefacts.
Key-value stores
Graph DBs
File system
Choosing Memory Types by Use Case
| Use case | Primary memory type | Secondary | Avoid |
| Customer support agent (single session) | In-context | Episodic (prior tickets) | Fine-tuning for per-ticket facts |
| Research assistant (multi-day project) | Episodic + Semantic | External (notes store) | Trying to fit everything in-context |
| Financial analytics agent | External (live DB) | Semantic (policy docs) | Embedding live metrics — they go stale |
| Coding assistant | In-context (repo files) | Semantic (docs) | Episodic for code — summarisation corrupts intent |
| Multi-agent pipeline | External (shared state) | Episodic per sub-agent | Shared in-context — no isolation |
| Domain-specialised assistant | Procedural (fine-tuned) | Semantic (KB) | Fine-tuning for volatile facts |
Memory Systems & Libraries (2025)
Mem0 GA
Managed long-term memory layer. Automatic extraction of facts from conversations; vector+graph hybrid storage; SDK for Python/Node. Integrates with LangChain and direct API calls.
Zep GA
Graph-based memory for agents. Stores facts as a knowledge graph, not just vectors. Supports temporal reasoning ("what did the user say last week"). Postgres + pgvector backend.
LangGraph Persistence GA
Graph state checkpoints persisted to Postgres or Redis. Enables pause-and-resume, human-in-the-loop interrupts, time-travel debugging. Part of LangGraph Platform.
Claude Projects Memory 2025
Claude.ai managed memory — extracts and stores facts automatically across Project conversations. Exposed via the API as a system-prompt injection. Claude Code uses a file-based variant (MEMORY.md).
Semantic Memory — RAG Engineering Notes
RAG accuracy depends more on the chunking and retrieval strategy than on the embedding model. Naive sentence-window chunking routinely outperforms expensive models with poor chunking. Hybrid search (dense + BM25 + reranker) consistently outperforms pure-vector search by 10–25% on enterprise corpora.
| Decision | Options | Default recommendation |
| Chunk strategy | Fixed-size · Sentence-window · Semantic · Hierarchical | Semantic (spaCy / NLTK) for dense docs; hierarchical for structured content |
| Chunk size | 128–2048 tokens | 512 tokens with 10% overlap — balance precision vs. recall |
| Embedding model | text-embedding-3-small · Snowflake Arctic-embed-M · nomic-embed-text | Arctic-embed-M for domain-specific; text-embedding-3-large for general |
| Search mode | Dense vector · BM25 sparse · Hybrid · Hybrid + reranker | Hybrid + reranker (Cohere Rerank or cross-encoder) for production |
| Retrieval count | top-k (3–20) | top-5 for tight context; top-10 with reranker |
| Freshness | Full re-index · Delta index · Streaming incremental | Delta index nightly + streaming for high-velocity sources |
Orchestration is the control flow that determines how the agent sequences thoughts, tool calls, and responses. The choice of pattern has the largest single impact on latency, cost, and correctness in multi-step tasks.
Core Reasoning Patterns
ReAct
Reason → Act → Observe
Interleaves Thought / Action / Observation steps in a single prompt. The model reasons about what to do, calls a tool, observes the result, and continues. Minimal external state; works in a single thread.
Use for: single-agent, sequential tool calls, tasks that fit in one context window.
Plan-and-Execute
Plan first · Execute separately
A planner LLM generates a task list upfront. An executor LLM runs each task. Separating planning from execution reduces hallucinated mid-plan pivots and allows parallel execution of independent steps.
Use for: complex multi-step tasks with parallelisable subtasks; when plan quality is more important than latency.
Reflexion
Act → Reflect → Retry
After each attempt, a reflection model critiques the output and generates corrective instructions. The main agent retries with the critique. Significantly improves accuracy on coding and reasoning tasks at the cost of 2–3× token usage.
Use for: code generation, math, tasks with clear correctness signals where retry is cheap.
CRAG (Corrective RAG)
Retrieve → Evaluate → Correct
Adds a retrieval evaluator that scores retrieved documents as Correct / Incorrect / Ambiguous. On incorrect, re-queries with a rewritten question or falls back to web search. Prevents the model from reasoning over irrelevant context.
Use for: knowledge-intensive agents where RAG quality is variable and hallucination risk is high.
Multi-agent (Supervisor)
Router → Specialist agents
A supervisor agent routes tasks to specialist sub-agents (researcher, coder, analyst). Each sub-agent has its own tool set and context. Results aggregate back to the supervisor for synthesis.
Use for: diverse task types that exceed a single agent's tool/context capacity; parallel work streams.
Swarm (Handoff)
Agent → transfers_to → Agent
Agents transfer control to each other directly — no central supervisor. Each agent decides when it has completed its part and which agent to hand off to. Flexible but harder to audit and debug.
Use for: conversational routing (triage → specialist → escalation); OpenAI Agents SDK swarm pattern.
Orchestration Frameworks — Comparison (2025)
| Framework | Model | Strengths | Limitations | Status |
| LangGraph |
Stateful graph (nodes + edges) |
Human-in-the-loop, time-travel debugging, persistence, streaming, wide tool ecosystem |
Steep learning curve; verbose for simple flows |
GA |
| CrewAI |
Role-based multi-agent crews |
Readable role/goal definition; enterprise features (memory, delegation); quick multi-agent setup |
Less control over low-level flow; can be "magic" |
GA |
| AutoGen v0.4 |
Actor model (async agents) |
Async-first; compositional; strong multi-agent conversation management |
Breaking changes from v0.2; smaller community |
GA |
| OpenAI Agents SDK |
Agents + handoffs + guardrails |
Native to OpenAI ecosystem; built-in tracing; swarm handoff pattern |
Tightly coupled to OpenAI models; limited cross-provider |
GA |
| Databricks Agent Framework |
MLflow-traced LangGraph agents |
Native Unity Catalog tools, MLflow eval integration, Genie MCP, production deployment via AI Gateway |
Databricks-only; overkill for non-Databricks stacks |
GA |
| Anthropic Claude Agent SDK |
Tool loop + MCP client |
Native Claude integration; MCP client built-in; simple API surface |
Claude-only; less orchestration abstraction than LangGraph |
GA |
| Semantic Kernel |
Plugin-based (Microsoft) |
Strong Azure/Office integration; C# first class; enterprise auth |
Python support secondary; heavy for lightweight use cases |
GA |
| LlamaIndex Workflows |
Event-driven steps |
Tight RAG integration; async step execution; LlamaParse for doc ingestion |
Less suited for multi-agent; smaller orchestration ecosystem |
GA |
| LangChain AgentExecutor |
ReAct loop wrapper |
Large ecosystem; extensive docs; many integrations |
Being superseded by LangGraph for production; verbose config |
Legacy |
Framework Selection Guide
| Starting point | Recommended framework | Reason |
| Databricks stack | Databricks Agent Framework (LangGraph + MLflow) | Native Unity Catalog tools, Genie MCP, one-click deployment to AI Gateway |
| Need human-in-the-loop interrupts | LangGraph | Checkpoint persistence + interrupt() node support |
| Multi-agent, quick prototype | CrewAI | Readable role/goal YAML; built-in delegation; fast to get running |
| OpenAI-only stack | OpenAI Agents SDK | Native handoffs, guardrails, and tracing; no translation layer |
| Azure / Microsoft stack | Semantic Kernel | Native Azure OpenAI, Entra auth, Teams/Office plugins |
| Minimal dependency budget | Direct API (Anthropic or OpenAI) + custom ReAct loop | Framework overhead often > 50% of token cost for simple agents |
| Need async + multi-model | AutoGen v0.4 | Actor model handles async well; supports multiple LLM backends |
Observability — OTel for Agent Harnesses
OpenTelemetry Semantic Conventions for Generative AI (OTel GenAI, v1.29+) standardise span names and attributes for LLM calls, embedding calls, and agent runs. Use these rather than custom attributes to keep observability compatible with any vendor (Langfuse, Datadog, Honeycomb, Arize Phoenix).
| OTel Span | Key attributes | What to measure |
| gen_ai.client.operation | gen_ai.system, gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens | Per-call latency, token spend, model version |
| gen_ai.tool.call | gen_ai.tool.name, gen_ai.tool.call.id | Tool selection, execution time, error rate |
| gen_ai.agent.run | gen_ai.agent.name, gen_ai.agent.run.id | End-to-end agent latency, turn count, success rate |
| gen_ai.retrieval.query | gen_ai.retrieval.source, gen_ai.retrieval.score_top1 | RAG relevance, retrieval latency |