Anyone can get an AI agent to demo well. The hard part is an agent that gives the right result on the hundredth run, on messy real inputs, without doing anything you would not sign off on. Most agent projects stall in that gap between a good demo and a dependable system.
In this guide I cover the full lifecycle in one place: how to build an agent that does a narrow job well, how to measure whether it works using pass^k reliability, how MCP and A2A fit into the architecture, and how to secure the whole system. There is tested Python for an eval harness and a tool gateway. If agents are new to you, start with What Is Agentic AI? and How to Build Your First AI Agent.
What does it mean for an AI agent to "work"?
An agent works when it completes a defined task correctly every time, inside limits you set, and you can prove it with numbers. That definition has three parts, and a missing one is the usual cause of failure.
| Pillar | The question it answers | What "good" looks like |
|---|---|---|
| Build | Does it do the job? | A narrow task, clear tools, a bounded loop, and a human escape hatch |
| Evaluate | Does it do the job reliably? | A test set graded on end state, run many times, tracked as pass^k |
| Secure | Can it be made to do the wrong job? | Least-privilege tools, approvals for risky actions, untrusted-input handling, full logs |
Notice that the model is not on the list. A better model helps, but the work that makes an agent dependable is mostly engineering around the model: the tools it gets, the tests it must pass and the limits it cannot cross.
Why do so many agent projects fail?
Most fail for business and risk reasons, not model quality: unclear value, rising cost and weak controls. Gartner predicted in 2025 that over 40% of agentic AI projects will be cancelled by the end of 2027, citing escalating costs, unclear business value and inadequate risk controls. The same report estimated that only about 130 of the thousands of vendors calling themselves "agentic" offer real agent capability, and called the rest "agent washing". Treat that as a forecast, not a measured rate.
The pattern shows up in survey data too. McKinsey's 2026 State of AI survey found around 40% of large organisations scaling agents but only a small group, about 6%, attributing at least 5% of earnings to AI. Deloitte's 2026 enterprise survey reported that 74% of leaders expect to use agents at least moderately by 2027, yet only 21% have a mature governance model. Adoption is wide; dependable value is narrow.
In my experience the failures cluster into five causes:
| Failure cause | What it looks like | Fix |
|---|---|---|
| Task too broad | "An agent that handles customer operations" | One narrow job with a clear definition of done |
| No evals | Quality judged by a few demo runs | A graded test set and a reliability metric |
| Too much autonomy, too early | The agent can write and send on day one | Read-only first, then approvals, then limits |
| Unmanaged tools | Dozens of overlapping tools, admin-level credentials | Few, clear, least-privilege tools behind one gateway |
| No owner or metric | Nobody tracks cost, errors or whether it helps | One owner, three metrics, a weekly review |
How do you build an agent that works?
Start simple: one narrow task, a few well-described tools, a loop with a hard step limit, and a clear rule for asking a human. Anthropic's guidance in Building effective agents makes the same point: add complexity only when a simpler approach measurably falls short. The system you build around the model is often called the agent harness.
First decide whether you need an agent at all. A workflow follows steps you wrote; an agent decides its own steps. Agents cost more, are slower and are harder to test, so use one only when the path genuinely cannot be fixed in advance.
| Workflow (fixed steps) | Agent (model chooses steps) | |
|---|---|---|
| Best when | The steps are known: extract, classify, route, summarise | The path depends on what the agent finds: investigations, open-ended research |
| Predictability | High | Lower, needs reliability testing |
| Cost and latency | Low and stable | Higher and variable |
| Failure mode | A step breaks | The agent wanders, loops or picks the wrong tool |
If you do need an agent, these design choices matter most:
- Define "done" in one sentence a script could check. "Refund order 1001 and confirm to the customer" is checkable. "Be helpful with orders" is not.
- Cap the loop. Set a maximum number of steps, a time limit and a token or cost budget. When any limit is hit, stop and hand over to a human with a summary.
- Give it an exit. The agent must be able to say "I cannot do this safely" and escalate. An agent with no way to refuse will improvise.
- Keep state outside the model. Store orders, decisions and approvals in your own systems, so you can inspect and grade what happened.
- Put the rules in code. Limits such as "refunds above 50 need a human" belong in the tool layer, not only in the prompt.
How do you design tools an agent can use reliably?
Design tools like a small API for a literal colleague: few, clearly named, strictly typed and forgiving of mistakes. Most "the model got it wrong" bugs turn out to be tool-design bugs.
- Fewer, sharper tools. Overlapping tools such as
search_ordersandfind_ordersmake the model guess. Merge or remove them. - Describe when to use each tool. The description is part of your prompt. Say what the tool does, what it returns and when not to use it.
- Return useful errors. "Unknown order 9999. Valid orders for this customer: 1001, 1002" lets the agent self-correct. A stack trace does not.
- Make write actions safe to repeat. Use idempotency keys so a retry does not refund twice.
- Cap output size. Return 50 rows with a note, not 50,000. Large outputs bury the signal and cost money.
- Separate read tools from write tools. You will want different approval rules for each, as shown in the security section below.
If your agent's main tool is document search, see how to design semantic search for business data for chunking, permissions and retrieval evaluation.
Where do MCP and A2A fit in an agent system?
MCP connects an agent to tools and data; A2A connects an agent to other agents. They solve different problems at different layers, and a serious system may use both.
| MCP (Model Context Protocol) | A2A (Agent2Agent) | |
|---|---|---|
| Connects | An agent to tools, data and prompts | An agent to another, independent agent |
| The other side is | A server that exposes functions | An agent with its own model, tools and memory |
| Discovery | The client asks the server for its tools | The remote agent publishes an Agent Card describing its skills and how to reach it |
| Unit of work | A tool call with a result | A task that can run for a while, ask for input and return results |
| Typical use | "Run this query", "read this file" | "Handle this travel booking", "review this contract" |
The history explains why people now discuss them together. Anthropic introduced MCP in November 2024, and it moved to the Linux Foundation's Agentic AI Foundation (AAIF) in December 2025. Google announced A2A in April 2025 and donated it to the Linux Foundation that June. Version 1.0 arrived in March 2026 with production-ready status, and reporting says it added multi-tenancy, version negotiation, multiple protocol bindings and signed Agent Cards. In August 2026 A2A moved under the same AAIF umbrella as MCP, so both now share neutral governance.
My practical rule: start with MCP, and reach for A2A only when another team or vendor already runs a capable agent you want to delegate to. Calling a remote agent adds latency, cost and a new trust boundary. If you control both sides and the job is one workflow, a single agent with good tools is simpler and easier to test.
For the details of MCP, including the 2026-07-28 specification that made the protocol stateless and tightened authorization, read my MCP explainer. When agents need to buy and pay, a further set of protocols (UCP, ACP and AP2) builds on MCP and A2A; I explain them in Agentic Commerce Explained.
Should you use one agent or many?
Start with one agent. Split only when tool choice becomes unreliable, or when parts of the job need different permissions or owners. Multi-agent systems multiply every problem in this guide: more cost, more logs to read, more places for an error to spread.
| Split when... | Because... | Watch out for |
|---|---|---|
| Tool choice gets unreliable as the tool list grows | Specialists with 4 or 5 tools each choose better | The router agent becomes the new weak point |
| Parts of the job need different permissions | A read-only research agent should not hold write credentials | Context lost at each handoff |
| Another team already runs the capability | Reuse beats rebuilding (this is where A2A fits) | You inherit their reliability and their risks |
Whatever you choose, evaluate the whole system, not only each agent. Two agents that each pass their own tests can still fail together when one misreads the other's output. For patterns, costs and a tested orchestrator, see Multi-Agent Systems: When One AI Agent Isn't Enough.
How do you evaluate an AI agent?
Grade what the agent did to the world, not what it said, and run every task several times, because agents are not deterministic. A fluent "Done, I issued the refund!" is worthless if the refund does not exist in your database.
Three ideas make agent evals different from testing a chatbot:
- Grade the end state. Check the database, the file or the ticket. This is how the τ-bench benchmark scores tool-using agents, by comparing the final state with the goal.
- Look at the trajectory too. The path matters: wrong tool calls, repeated retries and skipped checks are failures even when the final answer is right. Accept different valid paths rather than demanding one exact sequence.
- Measure reliability, not just capability. One lucky run proves the task is possible, not that it is dependable.
That last point is where pass^k helps. pass@k asks whether at least one of k attempts succeeds; pass^k asks whether all k attempts succeed. For an agent that acts on its own, with no human picking the best attempt, the second is the honest measure. The τ-bench authors introduced it for exactly this reason, and reported that even strong function-calling agents completed under half of tasks and were quite inconsistent across repeated trials, with pass^8 below 25% in the retail domain.
The arithmetic is unforgiving. If an agent succeeds on a task with probability p each time, then roughly pk is the chance it succeeds k times in a row:
| Per-run success | pass@1 | pass^3 | pass^5 | pass^8 | How it feels |
|---|---|---|---|---|---|
| 70% | 70% | 34% | 17% | 6% | A demo |
| 90% | 90% | 73% | 59% | 43% | An assistant a human double-checks |
| 95% | 95% | 86% | 77% | 66% | Close to hands-off, for low-risk tasks |
| 99% | 99% | 97% | 95% | 92% | Production-grade for most workflows |
Choose k from your real volume. An agent that handles a thousand cases a day gets a thousand independent chances to fail, so a single-run accuracy of 90% is not the headline; the pass^k at a realistic k is.
Use three kinds of grader, cheapest first:
| Grader | Good for | Caution |
|---|---|---|
| Code check on end state | Anything with a verifiable outcome: records, files, balances | Do not over-specify the exact steps |
| LLM judge with a rubric | Tone, completeness, whether a summary is faithful | Write a structured rubric and spot-check it against human labels |
| Human review | New failure types, high-stakes samples, calibrating the judge | Slow and costly, so sample |
Build the test set from real failures, not imagined ones. I start with 20 to 50 tasks taken from cases a person has had to fix, include a few "must not act" tasks (the agent should refuse or escalate), and add every production incident as a new test. For analyst-style agents such as text-to-SQL and reporting, Agentic AI for Data Analytics covers the checks that catch silent errors.
How do you build an agent eval harness in Python?
A minimal harness needs end-state graders, a fresh environment per trial, the agent under test, and a reliability calculation over repeated runs. The version below uses a stub agent that fails at random, so you can run it without any API key and see the metrics behave.
import random
from math import comb
# 1. Tasks: a goal plus a grader that checks the END STATE, not the agent's words
TASKS = [
{"id": "refund-small", "goal": "Refund order 1001", "grade": lambda s: s["refunds"].get(1001) == 20.0},
{"id": "refund-limit", "goal": "Refund order 1002 (over limit)", "grade": lambda s: 1002 not in s["refunds"] and s["escalated"]},
{"id": "status-only", "goal": "Where is order 1003?", "grade": lambda s: not s["refunds"] and not s["escalated"]},
]
# 2. The agent under test: any function that takes (goal, state) and acts on the state.
# This stub fails at random, like a real LLM agent does.
def flaky_agent(goal, state, p_ok=0.8, rng=random):
if rng.random() > p_ok:
return # did nothing useful this run
if "1001" in goal:
state["refunds"][1001] = 20.0
elif "1002" in goal:
state["escalated"] = True # correct: do not refund, hand to a human
def run_trial(agent, task):
state = {"refunds": {}, "escalated": False} # fresh world for every trial
agent(task["goal"], state)
return task["grade"](state)
# 3. Reliability metrics from n trials with c successes
def pass_at_k(n, c, k): # at least one of k tries succeeds
return 1.0 if n - c < k else 1.0 - comb(n - c, k) / comb(n, k)
def pass_hat_k(n, c, k): # ALL k tries succeed
return comb(c, k) / comb(n, k)
def evaluate(agent, tasks, n=20, k=5):
rows = []
for t in tasks:
c = sum(run_trial(agent, t) for _ in range(n))
rows.append((t["id"], c / n, pass_at_k(n, c, k), pass_hat_k(n, c, k)))
return rows
if __name__ == "__main__":
random.seed(7)
print(f"{'task':<14}{'pass@1':>8}{'pass@5':>8}{'pass^5':>8}")
for tid, p1, pk, phk in evaluate(flaky_agent, TASKS):
print(f"{tid:<14}{p1:>8.2f}{pk:>8.2f}{phk:>8.2f}")
Running it prints:
task pass@1 pass@5 pass^5
refund-small 0.90 1.00 0.55
refund-limit 0.85 1.00 0.40
status-only 1.00 1.00 1.00
Read the gap. The first task succeeds on 90% of single runs and looks fine. Yet it passes five runs in a row only 55% of the time, and the "optimistic" pass@5 of 1.00 hides that completely. The status-only row is a "must not act" test, so a stub that does nothing passes it, which is why a real suite needs both kinds of task.
Here are four of the five tests I ran against this code, so you can reuse them:
def test_metrics_edge_cases():
assert pass_hat_k(20, 20, 5) == 1.0
assert pass_hat_k(20, 0, 5) == 0.0
assert pass_at_k(20, 0, 5) == 0.0
assert pass_hat_k(20, 15, 5) < pass_at_k(20, 15, 5)
def test_perfect_agent_scores_one_everywhere():
perfect = lambda goal, state: flaky_agent(goal, state, p_ok=1.0)
for _, p1, pk, phk in evaluate(perfect, TASKS):
assert p1 == pk == phk == 1.0
def test_grader_checks_state_not_words():
def talker(goal, state): # claims success, changes nothing
print("Done! Refund issued.")
assert run_trial(talker, TASKS[0]) is False
def test_reliability_gap():
random.seed(1)
rows = {r[0]: r for r in evaluate(flaky_agent, TASKS)}
_, p1, pk, phk = rows["refund-small"]
assert pk > p1 > phk # optimistic > single run > strict
To test a real agent, replace flaky_agent with a function that runs your agent loop against a throwaway copy of your data, and keep the graders unchanged. Run the suite on every prompt, tool or model change, and treat a drop in pass^k like a failing unit test.
How do you monitor an agent in production?
Log every run as a trace of model calls, tool calls and results, then track a few metrics and review real runs weekly. Evals tell you the agent worked on your test set; monitoring tells you whether it still works on real traffic.
| Signal | Why it matters | Act when |
|---|---|---|
| Task success rate | Your main outcome metric, sampled and graded | It drifts down after a model, prompt or data change |
| Steps per task | Rising steps signal wandering or retries | The median climbs or the step limit is hit often |
| Tool error rate | Shows broken tools and bad arguments | A single tool's errors spike |
| Escalation and override rate | How often humans step in or reverse the agent | Overrides rise, or fall to zero (nobody is checking) |
| Cost and latency per task | Agents can quietly become expensive | Cost per task breaks your budget |
| Blocked actions | Shows attempts to cross your limits, including attacks | Any unexpected pattern |
Close the loop: every incident becomes a new eval case, so the same failure cannot return unnoticed.
How do you secure an AI agent?
Assume the model can be tricked, and design so a tricked agent cannot do serious damage: least privilege, approvals, hard limits and logs. Prompts that say "never do X" are a hint to the model, not a control.
The core danger is what Simon Willison calls the lethal trifecta: an agent that combines access to private data, exposure to untrusted content and the ability to communicate externally can be steered into leaking that data. Remove any one leg and the attack gets far harder. I cover attacks and defences in depth in Prompt Injection and AI Agent Security; here is the short version for agents you are building today.
- Least privilege. Give each tool the narrowest credential: a read-only database user, a scoped token, one folder rather than the whole drive.
- Tier your tools. Read tools run freely; write tools need approval; some actions get a hard cap no approval can override.
- Treat all retrieved content as untrusted. Web pages, emails, documents and tool output are data, never instructions.
- Break the trifecta. If the agent reads untrusted content and holds private data, remove its ability to send data out, or require approval for it.
- Log everything, including denials. You cannot investigate what you did not record.
The gateway below puts these rules in one place. Every tool call goes through call(), which checks the tool exists, enforces a hard cap, asks for approval on write tools and logs the attempt either way. I tested it with five cases, including an approved refund over the cap, which is still blocked.
import time
TOOLS = {} # name -> (function, tier)
def tool(tier):
def wrap(fn):
TOOLS[fn.__name__] = (fn, tier)
return fn
return wrap
@tool("read")
def get_order(order_id: int):
return {"order_id": order_id, "total": 20.0, "status": "delivered"}
@tool("write")
def refund(order_id: int, amount: float):
return {"refunded": amount, "order_id": order_id}
def call(name, args, approve, log, max_refund=50.0):
"""The only door between the model and your systems."""
entry = {"ts": time.time(), "tool": name, "args": args}
try:
if name not in TOOLS:
raise KeyError(f"unknown tool {name!r}")
fn, tier = TOOLS[name]
entry["tier"] = tier
if name == "refund" and args.get("amount", 0) > max_refund:
raise PermissionError(f"refund above {max_refund} needs a human")
if tier == "write" and not approve(name, args): # human or policy engine
raise PermissionError("approval denied")
result = fn(**args)
entry["ok"] = True
return result
except Exception as e:
entry["ok"] = False
return {"error": str(e)} # the agent reads this and adapts
finally:
log.append(entry) # every call is logged, success or not
Notice that the limit lives in call(), not in the prompt. A model that has been manipulated into asking for a 500 refund still gets "needs a human", because the code says so.
How do you secure MCP and A2A connections?
Treat every MCP server and remote agent as its own trust boundary: verify it, give it minimum access, and treat its output as untrusted. The protocols define identity and authorization mechanisms, but they cannot make a careless deployment safe.
| Risk | Applies to | What it looks like | Defence |
|---|---|---|---|
| Tool poisoning | MCP | A server hides instructions in a tool description | Install only trusted servers; review descriptions; treat them as untrusted |
| Silent changes after approval | MCP | A server alters its tools after you reviewed it | Pin versions; re-review on any change; alert on description diffs |
| Over-broad credentials | MCP, A2A | One admin token shared across servers or agents | Per-server credentials, narrow OAuth scopes, short-lived tokens |
| Spoofed or misleading Agent Card | A2A | A remote agent claims skills or an identity it does not have | Allow-list remote agents; verify signed cards; do not trust self-described capabilities |
| Over-sharing in delegation | A2A | You pass the full conversation or customer record to a remote agent | Send the minimum data the task needs; agree data-handling terms |
| Injection through returned content | MCP, A2A | A tool result or remote agent reply contains instructions | Treat as data; strip or quarantine; never let it widen permissions |
| Runaway delegation | A2A, multi-agent | Agents call each other in loops, burning money | Depth limits, timeouts and a per-task budget |
| Dangerous combinations | MCP | One server reads private data, another can post publicly | Review servers as a set; keep sensitive-read and external-write apart |
Two habits cover most of this. First, give every agent its own identity instead of a shared service account, so logs show who did what. Second, put your gateway in front of MCP and A2A calls too: the same tiers, caps, approvals and logs apply whether the tool is a local function, an MCP server or a remote agent.
How do you roll out an agent safely?
Increase autonomy in stages, and promote the agent only when its measured reliability earns the next stage. Skipping stages is how a small error becomes a customer-facing incident.
| Stage | What the agent does | Promote when |
|---|---|---|
| 1. Shadow | Runs on real inputs but acts on nothing; humans compare its output | Its answers match human decisions at your target rate |
| 2. Suggest | Drafts actions; a person approves every one | Approvals are rarely edited, and pass^k meets target |
| 3. Act on low-risk tasks | Acts alone within hard limits; humans handle the rest | No critical failures over a set number of runs; overrides stay low |
| 4. Broaden | Handles more task types and higher limits | Each new task type has its own evals and owner |
Keep a one-click way to switch the agent off or back to suggest mode. You want that switch before you need it.
What are the most common mistakes with AI agents?
Most agent failures come from process, not models: demo-driven testing, too much early autonomy, prompt-only safety and no owner. Avoid these eight.
- Judging by the demo. Run each important task many times and look at
pass^k. - Grading the answer, not the outcome. Check the database, not the chat message.
- Starting with write access. Begin read-only; earn the rest.
- Trusting the prompt as a safety control. Enforce limits in code.
- Adding protocols for their own sake. MCP and A2A are useful when reuse or delegation is real, not as decoration.
- Going multi-agent too early. Prove one agent first.
- No owner and no review. Someone must read traces and act on them every week.
- Never re-testing after a model swap. A new model version is a new system; rerun the evals.
Checklist: is your agent ready for production?
An agent is production-ready when every item below is true and your evals prove it. Use the list before each rollout stage.
- The task is narrow and "done" can be checked by a script
- A workflow was considered first, and an agent is justified
- The loop has step, time and cost limits, and a human escape route
- Tools are few, clearly described, typed and idempotent where they write
- Read, write and external-send tools are separated and tiered
- Credentials are least-privilege and specific to each tool, server or agent
- Hard limits are enforced in code, not only in the prompt
- An eval set of at least 20 real-failure tasks exists, including "must not act" cases
- Graders check end state;
pass^kmeets target at a realistic k - MCP servers are trusted and pinned; remote agents are allow-listed
- Returned content from tools and agents is treated as untrusted
- Every call, denial and approval is logged and reviewable
- Rollout is staged, with an off switch and a named owner
- Evals rerun after every prompt, tool, server or model change
Sources and further reading
- Anthropic: Building effective agents
- τ-bench: a benchmark for tool-agent-user interaction (introduces pass^k)
- Model Context Protocol specification, version 2026-07-28
- Agentic AI Foundation: Model Context Protocol
- Google Cloud: A2A donated to the Linux Foundation
- Google Open Source Blog: A year of A2A, including v1.0
- Techstrong: A2A moves under the Agentic AI Foundation
- Simon Willison: The lethal trifecta
- SD Times: Gartner on agentic AI project cancellations
- McKinsey: The state of AI
- GRC Report: Deloitte survey on agent adoption and governance
Key takeaways
- An agent "works" when it is correct, repeatable and bounded, and you can prove it with numbers.
- Build narrow: one task, few tools, a capped loop and a way to escalate.
- Evaluate on end state and report
pass^k; a 90% single-run score can mean under 60% over five runs. - MCP connects agents to tools; A2A connects agents to agents. Start with MCP.
- Secure by design: least privilege, tiered tools, hard limits in code, untrusted-by-default content and full logs.
- Roll out in stages and rerun your evals after every change.
Frequently asked questions
What makes an AI agent reliable enough for production?
A narrow task, a loop with step and cost limits, least-privilege tools, a graded test set and measured reliability. Use pass^k, which asks whether the agent succeeds on all k repeated runs, rather than a single lucky run.
What is pass^k and why does it matter for agents?
pass^k is the probability that an agent succeeds on all k attempts at the same task. It matters because agents are non-deterministic and act on their own: a 90% single-run success rate falls to about 59% over five runs in a row.
What is the difference between pass@k and pass^k?
pass@k counts a task as solved if any of k attempts succeeds, which measures peak capability. pass^k counts it only if every attempt succeeds, which measures consistency. Use pass^k for unattended agents.
How do I evaluate an AI agent?
Build 20 to 50 tasks from real failures, grade the end state (database, file or ticket) rather than the agent's words, check the trajectory for bad tool use, run each task several times and track pass^k. Rerun after every change.
What is the difference between MCP and A2A?
MCP connects an agent to tools, data and prompts exposed by servers. A2A connects an agent to another independent agent, discovered through an Agent Card, to which it can delegate tasks. They work at different layers and can be used together.
Do I need A2A to build an agent?
No. Most agents need only tools, which MCP or plain function calling can provide. Consider A2A when another team or vendor already runs a capable agent you want to delegate tasks to.
Should I build a single agent or a multi-agent system?
Start with a single agent. Split only when tool choice becomes unreliable, when parts of the job need different permissions, or when you want to reuse an agent another team already runs. Evaluate the whole system, not only each agent.
How do I secure an AI agent?
Assume the model can be tricked. Use least-privilege credentials, separate read tools from write tools, require approval for risky actions, enforce hard limits in code, treat retrieved content as untrusted data and log every call, including denials.
How do I secure MCP servers and remote agents?
Treat each as a separate trust boundary. Use trusted, version-pinned MCP servers, per-server credentials with narrow scopes, allow-listed remote agents with verified identity, minimal data sharing, and treat anything returned as untrusted input.
How do I roll out an agent safely?
Increase autonomy in stages: shadow mode, then suggest with human approval, then act on low-risk tasks within hard limits, then broaden. Promote only when measured reliability earns it, and keep an off switch and a named owner.
Bring agents that work to your team
Getting an agent to run once is a weekend project. Choosing the right task, building the evals, setting the limits and securing the connections is where most teams get stuck. If you want help designing, testing or securing agents, or training your team to do it, let's talk. I run agent and LLM training for enterprise teams and hands-on agent workshops for founders. To learn it yourself, start with the Agentic AI Skills Roadmap.
Next read: Prompt Injection and AI Agent Security