SysDesignAtlas

Build an AI Agent Platform

Where the model stops answering and starts acting — tool execution, sandboxing, loop control, and treating model output as untrusted input.

HLDHard11 min readlevel-5aiagentssecurity
Confidence

#The product

Give the assistant a goal. It plans, calls tools — search the web, query a database, run code, send an email — observes results, and iterates until done.

The security posture inverts here. In chat, the worst case is a bad answer. In an agent, the worst case is a bad action: deleted data, money moved, an email sent to the wrong person. Everything below follows from that.

#Phase 1 — The loop

An agent is a model that has been given actions it can take — search a database, send an email, run code — rather than only text it can produce. A tool is one such action, described to the model so it knows the name, what it does, and what arguments it takes. The model doesn't execute anything itself: it asks for a tool to be run, and your platform decides whether to comply.

   ┌──────────────────────────────────────────┐
   │  1. model receives goal + tool schemas   │
   │  2. model emits a tool call              │
   │  3. platform VALIDATES and EXECUTES it   │
   │  4. result appended to context           │
   │  5. repeat until done, or a limit trips  │
   └──────────────────────────────────────────┘

Simple to state and it needs hard bounds on every axis, because an agent that mis-plans will happily loop forever at full token cost:

   max_iterations     ~20      runaway loop guard
   max_tokens         budget   cost ceiling per run
   max_wall_clock     ~5 min   user is waiting
   max_tool_calls     per tool, per run
   max_spend          hard currency cap

Detect non-progress, not just iteration count. An agent calling the same tool with the same arguments three times in a row is stuck. Hash (tool, arguments) and break the loop on repetition — that catches the common failure well before the iteration cap does.

#Phase 2 — Tools as a typed contract

   {
     name: "search_orders",
     description: "Find orders for a customer",   ← the model reads this
     parameters: {
       customer_id: { type: "string", required: true },
       status:      { type: "string", enum: [...] },
       limit:       { type: "integer", max: 100 }
     }
   }

The description is part of your API surface, and it's unusual: it's documentation the model consumes to decide when to call the tool. A vague description produces wrong tool selection, and debugging that feels like debugging prose because it is.

Validate every argument server-side, always. The model produces plausible-looking output, not valid output. It will hallucinate parameter names, invent enum values, and exceed limits. Treat tool arguments exactly as you'd treat a request body from an untrusted client — schema validation, range checks, permission checks.

Design tools to be narrow. execute_sql(query) is dangerous and hard for the model to use correctly. get_orders_for_customer(customer_id, status) is safe, unambiguous, and easier for the model to call right. Narrow tools also fail more informatively — "no customer with ID 123" tells the model exactly what to fix, where a raw SQL syntax error leaves it guessing — so the agent recovers in fewer iterations.

Increasingly, tools reach agents through the Model Context Protocol (MCP) — an open standard, introduced in late 2024, in which a tool server describes its tools with exactly these kinds of schemas and agents call them over JSON-RPC. It makes tools reusable across agents, but it doesn't change the rules above: an MCP server is one more untrusted boundary, in both directions, so arguments are still validated and results are still treated as data. Agent protocols covers MCP and agent-to-agent A2A in depth.

#Phase 3 — Permissions, and the confused deputy

The central security problem, and the one to raise unprompted. A confused deputy is any program that holds more authority than the person asking it for something, and can be talked into using that authority on their behalf. Your agent is the perfect example: it has database credentials, the user doesn't, and the user writes the instructions.

   Agent runs with the USER'S permissions — never its own.

   BROKEN: agent service holds broad DB credentials
           user asks "show me all customer emails"
           → agent complies. It had the access, so it used it.

   CORRECT: every tool call carries the requesting user's
            identity; authorization happens in the tool,
            against that user, on every call.

This is the confused deputy problem: a privileged component tricked into misusing its authority on behalf of someone less privileged. An agent with broad credentials is a confused deputy by construction.

#Phase 4 — Sandboxing code execution

If the agent runs code, you're executing untrusted input from a model that can be manipulated.

   Container per execution, and:
     · no network by default (allow-list if truly needed)
     · read-only root filesystem; small writable scratch
     · CPU / memory / PID / disk limits enforced by the runtime
     · hard wall-clock kill
     · dropped capabilities, non-root user, seccomp profile
     · DESTROYED after the run — never reused

The second-to-last line means: strip the Linux privileges the code doesn't need, run it as an ordinary user rather than root, and use a seccomp profile to block system calls it has no reason to make. Each one removes a route for code to escape the container.

Never reuse a sandbox across users. State left behind is a cross-tenant data leak. If startup latency matters, keep a pool of pre-warmed but unused sandboxes rather than recycling dirty ones.

For stronger isolation than containers give you, use microVMs (Firecracker-style). Containers share the host's operating-system kernel, so a kernel bug can let code break out. A microVM runs its own kernel on a hypervisor, a much smaller and harder wall to get through, yet still starts in close to container times. Worth naming as the option when the workload is genuinely hostile.

#Phase 5 — Durable execution

Agent runs take minutes, accumulate state as they go, and cause real effects in the outside world. That combination makes them a workflow problem — something that must survive a process restart halfway through — rather than a request that either completes or doesn't.

   run_id · user_id · goal · status · iteration
   steps: (run_id, step_n, tool, args, result, status)
            ↑ append-only, durable BEFORE the tool executes

Persist the intent before acting, so a crash mid-run can be resumed rather than restarted. Restarting an agent that already sent three emails sends them again.

Tool calls must be idempotent or protected by idempotency keys, for exactly the reason in Idempotency: retries are inevitable and duplicate side effects are the failure mode that actually hurts.

This is the job scheduler pattern. A worker claims a run with a lease — a lock that expires unless the worker keeps renewing it. A reaper process finds runs whose lease has expired (the worker died) and hands them to a new worker, which resumes from the last saved step. An agent platform is a workflow engine that happens to be driven by a model.

#Phase 6 — Parallelism and cost

Run independent tool calls concurrently. If the model requests three lookups that don't depend on each other, executing them in parallel cuts wall-clock time substantially. Respect declared dependencies; parallelize the rest.

Cost control is critical here because agents multiply token spend in a way chat does not:

   Context grows every iteration — the FULL history of tool
   results is resent on each pass.

   Iteration 1:   2K tokens
   Iteration 10: 40K tokens   ← each iteration costs more
                                than the last

   Mitigations:
     · truncate/summarize old tool results
     · keep only what later steps actually need
     · cap result size per tool (a 1MB API response
       must not enter the context whole)
     · use a smaller model for routine tool selection

A single runaway agent can generate an enormous bill quietly. Per-run spend caps and per-user daily caps aren't a nice-to-have — like an electrical circuit breaker, they automatically cut a run off before the damage grows.

#Phase 7 — Observability

Agent failures are hard to diagnose because the "logic" is in model outputs.

   Per run, capture:
     · full prompt and completion at each iteration
     · every tool call: args, result, latency, error
     · token and cost accounting per step
     · why it terminated (done / limit / error / cancelled)

   → a replayable trace. Without it you cannot debug at all.

Track task success rate, not just uptime. An agent platform that's 100% available and completes 40% of tasks is failing at the thing it exists to do, and no infrastructure metric will tell you that.

#The decision log

DecisionRejectedBecause
User's permissions per tool callAgent's own credentialsConfused deputy — agent becomes a privilege escalation path
Narrow typed toolsGeneric execute_sqlSafer, and the model calls narrow tools more accurately
Server-side arg validationTrust model outputModels hallucinate parameters confidently
Architectural injection defencePrompt-level instructionsNo reliable prompt defence exists
Human confirmation for irreversible actsFull autonomyBlast radius containment is the only real mitigation
Fresh sandbox per runPooled/reused sandboxesReuse leaks state across tenants
Persist intent before executingLog afterCrash mid-run would replay side effects
Loop + spend + repetition limitsIteration cap onlyRepetition detection catches stuck agents far sooner
Parallel independent tool callsStrictly sequentialLarge wall-clock win at no correctness cost

#What you'd cut for v1

Code execution, parallel tools, durable resume, multi-agent orchestration. Ship: a bounded loop, three or four narrow read-only tools, per-user permissions, full tracing, hard iteration and spend caps. Start read-only — add write-capable tools one at a time, each with confirmation, once you trust the traces.

#Explaining the design

"The important shift from chat is that the failure mode changes from a bad answer to a bad action, so I'd design around blast radius from the start.

The loop is bounded on iterations, tokens, wall clock, and spend — plus repetition detection, since an agent calling the same tool with the same arguments is stuck long before it hits the iteration cap.

Tools are narrow and typed, and every argument is validated server-side because model output is plausible, not valid. Critically, tools execute with the requesting user's permissions, never the agent's own — otherwise the agent is a confused deputy and becomes a privilege escalation path.

On prompt injection: there's no robust prompt-level defence, so I'd contain it architecturally — least privilege, human confirmation for irreversible actions, allow-listed egress so it can't exfiltrate, and full audit trails.

Runs are durable workflows: persist the intent before executing so a crash resumes rather than replaying side effects, with idempotency keys on every tool call.

And I'd track task success rate, not just uptime — a platform that's fully available and completes 40% of tasks is failing at its actual job."

#Next

Build an AI Code Assistant — the same primitives under a latency budget an order of magnitude tighter.

#Check yourself

How does the security posture change from chat to agents?Show answer
The worst case goes from a bad answer to a bad action — deleted data, money moved, the wrong email sent — so design around blast radius.
What bounds does an agent loop need?Show answer
Maximum iterations, tokens, wall-clock time, tool calls and spend — plus repetition detection: the same tool with the same arguments three times means it's stuck.
How should tools be designed?Show answer
Narrow and typed (get_orders_for_customer, not execute_sql), with descriptions written for the model, and every argument validated server-side because model output is plausible, not valid.
What is the confused deputy problem for agents?Show answer
An agent holding broader credentials than its user can be talked into using them. Every tool call must carry the requesting user's identity and be authorised against that user.
How do you defend against prompt injection?Show answer
Architecturally, since no prompt-level defence is reliable: least privilege, human confirmation for irreversible actions, tainted data can't trigger privileged tools, allow-listed egress, full audit.
How is agent code execution sandboxed?Show answer
A fresh container or microVM per run: no network by default, read-only root, resource and wall-clock limits, dropped capabilities — destroyed afterwards, never reused across users.
Why are agent runs durable workflows?Show answer
They take minutes and cause real effects, so persist each step's intent before executing and make tool calls idempotent — a crash resumes instead of replaying side effects.
Why does agent cost grow each iteration, and what helps?Show answer
The full history of tool results is resent every pass. Summarise old results, cap result size per tool, use a smaller model for routine steps, and enforce per-run and per-user spend caps.

#What to carry forward

  • Agents fail by acting, so contain blast radius from the start.
  • Bound the loop on every axis and detect repetition.
  • Narrow, validated tools that run with the user's permissions.
  • Prompt injection is contained by architecture, not prompts.
  • Durable, idempotent steps; fresh sandboxes; trace everything and track task success.
00:00
/ 11m