Guide / AI engineering Fundamentals
Agent frameworks, protocols, computer use and sandboxing
Agent loops as state machines, durable execution, framework trade-offs (LangGraph-style graphs, workflow engines), MCP vs agent-to-agent protocols, computer-use agents and sandboxing untrusted code.
This page extends Agents, tool use, MCP and memory with the engineering you need to run agents in production.
Fundamentals#
F.1 The agent loop as a state machine#
An agent is a loop: observe state → model decides (tool call or final answer) → execute tool → update state → repeat until done or a limit. Model it as an explicit graph/state machine rather than an opaque while loop:
- State: messages, tool results, plan, scratchpad, counters (steps, tokens, cost), user/tenant context.
- Nodes: LLM calls, tool executions, validators, human approval gates.
- Edges: conditional routing (if the tool failed → retry node; if confidence low → ask human).
- Persistence (checkpointing): save state after every step so a crash, deploy or human wait resumes where it stopped, enabling human-in-the-loop pauses and time-travel debugging.
- Hard limits: max steps, max tokens, max wall-clock, max spend per run; loop detection (same tool call with same args repeated).
Explicit graphs make behaviour testable (unit-test a node), observable (trace per node) and safe (approval nodes before risky actions).
F.2 Workflows vs agents (again, because it is asked)#
| Workflow | Agent | |
|---|---|---|
| Control flow | Fixed in code (prompt chaining, routing, parallelisation, evaluator-optimiser loops) | Model chooses next step |
| Predictability | High | Lower |
| Cost/latency | Lower, bounded | Higher, variable |
| Use | Known steps (extract → validate → write) | Open-ended tasks (research, debugging, ops) |
Start with the simplest workflow that works; add agency only where flexibility pays for itself. Typical hybrid: a deterministic workflow whose one step is a bounded agent.
F.3 Durable execution#
Long-running agents (minutes to days, waiting for humans or webhooks) need durable execution: Temporal, AWS Step Functions, Azure Durable Functions or a database-backed state machine. Benefits: automatic retries, timers, exactly-once-ish orchestration with idempotent activities, visibility, and survival of process crashes. Tool calls become activities with timeouts and retry policies; LLM calls are non-deterministic, so record their outputs in the workflow history rather than re-calling on replay.
F.4 Framework landscape (what to say)#
| Option | Idea | Pick when |
|---|---|---|
| Plain code + provider SDK | Your own loop and tools | Simple agents, maximum control, fewest dependencies |
| Graph/state-machine frameworks (LangGraph-style) | Nodes, edges, state, checkpointers, human interrupts | Complex agents needing persistence and approvals |
| Multi-agent frameworks (CrewAI, AutoGen-style) | Role-based agents conversing | Prototyping; be careful with cost and loops |
| Workflow engines (Temporal, Step Functions) | Durable orchestration | Business processes with reliability needs |
| Provider agent SDKs / managed agent runtimes | Hosted loop, tools, sandboxes | Speed to market; check lock-in and observability |
Interview stance: frameworks help with state, tracing and persistence but hide prompts and control flow; own your prompts, tool schemas and evals, and keep the framework replaceable.
F.5 Protocols: MCP and agent-to-agent#
- MCP (Model Context Protocol): standard way for an AI application to connect to tools, resources and prompts exposed by servers (local via stdio, remote via HTTP). It solves the N×M integration problem. Security: treat MCP servers as untrusted code, scope credentials, require user approval for sensitive tools, watch for tool-description prompt injection and “rug pull” updates.
- A2A (agent-to-agent) style protocols: let independent agents discover each other (agent cards), delegate tasks and exchange results across vendors and organisations, with auth and task lifecycle states. MCP connects an agent to tools; A2A connects agents to agents.
- Function/tool calling schemas: JSON Schema descriptions of arguments; validate arguments server-side; return structured, size-limited results with clear error messages the model can act on.
F.6 Computer-use and browser agents#
Agents that operate a GUI or browser by taking screenshots (or accessibility/DOM trees) and issuing clicks and keystrokes. Strengths: work with systems that have no API. Weaknesses: slow (seconds per step), brittle to UI change, expensive (image tokens), vulnerable to prompt injection from web content, and can take irreversible actions. Mitigations: prefer APIs/tools when they exist, run in an isolated VM/container with no ambient credentials, allowlist domains, require approval for purchases/sends/deletes, log screenshots and actions, cap steps, and verify outcomes with deterministic checks.
F.7 Sandboxing code execution#
Agents that run code (data analysis, scripts) must treat code as hostile:
- Isolation: containers with seccomp/AppArmor, gVisor or Firecracker microVMs for stronger isolation; one sandbox per session or per task; destroy after use.
- Resource limits: CPU, memory, disk, process count, wall-clock timeouts.
- Network: default deny egress; allowlist specific hosts (package mirror); block cloud metadata endpoints (SSRF) and internal networks.
- Filesystem: read-only base image, ephemeral scratch space, no host mounts, no secrets in the sandbox; pass data in and results out through a narrow API.
- Credentials: short-lived, least-privilege tokens scoped to the task; never the user’s full credentials.
- Output handling: treat outputs as untrusted data (they can contain injected instructions).
F.8 Reliability patterns for agents#
Idempotent tools with request IDs; retries with backoff only for safe calls; compensation for multi-step side effects; approval gates for irreversible actions; context management (summarise or prune long histories, keep tool outputs small); caching of deterministic tool results; fallback models; per-run budget; golden-trace regression tests (Evals); and tracing every step with inputs, outputs, latency, tokens and cost.
Most asked questions#
1. When should you use an agent vs a workflow? When the steps are not known in advance; otherwise a workflow is cheaper, faster and more predictable.
2. How do you make agents reliable? Explicit state machine, validated tool schemas, step/cost limits, checkpointing, human approval for risky actions, evals on traces.
3. What is MCP and why does it matter? An open protocol for exposing tools/resources/prompts to AI apps, standardising integrations.
4. How do you sandbox an agent that runs code? MicroVM or gVisor container, no network by default, resource limits, ephemeral filesystem, least-privilege short-lived credentials.
5. How do you stop infinite loops and runaway cost? Max steps/tokens/time, loop detection, per-run budgets, circuit breakers, alerts.
Senior-level questions#
1. “The agent works in demos but fails 30% of production runs.” Build an eval set from real failures, trace failures by node, classify (tool misuse, bad retrieval, context overflow, ambiguous task), add validation and retries, narrow the toolset, improve tool descriptions, add deterministic steps for the common path, and gate with regression evals.
2. “A tool result contains instructions that hijack the agent.” Indirect prompt injection: treat tool output as data, delimit and label it, limit tool privileges by task, require approval for sensitive actions, filter outputs, use separate models/contexts for untrusted content, and monitor for anomalous tool sequences (AI security).
3. “How do you resume an agent that waited three days for approval?” Persist state in a durable store keyed by run ID, store tool results and decisions, version the graph/prompt (old runs continue on the old version or migrate), and re-validate assumptions on resume (the world changed).
4. “Single agent with 40 tools performs badly.” Too many tools degrade selection: route to specialised sub-agents or tool subsets by intent, dynamic tool loading via retrieval over tool descriptions, shorter precise descriptions, and examples.
5. “Multi-agent systems: when are they worth it?” When subtasks are parallel and independent, need different tools/permissions or context isolation; otherwise they multiply cost and failure modes through communication overhead. Prefer one agent with good tools first.
Quiz#
1. Why checkpoint agent state after each step?
To resume after crashes or long waits, support human-in-the-loop pauses and enable replay and debugging.
2. MCP vs A2A?
MCP connects an agent to tools and data sources; A2A-style protocols connect agents to other agents.
3. Two controls for irreversible agent actions?
Human approval gates and least-privilege, scoped credentials (plus dry-run/preview and audit logs).
4. Why default-deny network egress in a code sandbox?
To prevent data exfiltration, SSRF to internal services or metadata endpoints, and downloading malicious payloads.
5. What does durable execution give an agent?
Automatic retries, timers, survival of crashes and deployments, and a full execution history.