The Core Idea: External tools are how an agent touches the real world: data, files, code and services. Each one needs the same design rule: give it only the power the task needs, and put checks in code, not in the prompt.
- Beginner: Why Agents Need External Tools
A model alone knows only its training data and can only write text. External tools give it fresh data, exact computation and the ability to act. The six most common kinds are:
| Tool kind | What it gives the agent | Main risk |
|---|---|---|
| APIs | Live data and services such as weather or payments | Leaked keys, runaway calls |
| Databases | Business data | Data leaks, destructive queries |
| Web search | Fresh public information | Wrong or hostile content |
| Code execution | Exact math, data work, plots | Running harmful code |
| File operations | Reading and writing documents | Reading or overwriting the wrong files |
| External services | Email, calendar, tickets, chat | Real-world side effects |
Design rule: The more a tool can change in the world, the more checks it needs.
- Beginner: APIs and Databases
APIs are the most general tool: a wrapper function sends an HTTP request and returns only the useful fields. Keep the API key on the server, hide it from the model and shape the output small.
A database tool lets the agent answer questions about business data. The safest design is read-only: accept only a single SELECT statement, run it with a database user that has no write rights, and limit the number of rows returned.
In the code: The query tool accepts a SELECT and rejects DROP TABLE. The best protection is also a read-only database account, because code checks can have gaps.
- Medium: Web Search and Code Execution
Web search lets the agent find fresh information. Treat results as untrusted: pages can be wrong, outdated, or contain hidden instructions. Return short snippets with their sources so the agent can cite them.
Code execution is powerful because the model can write exact calculations instead of guessing them. It is also dangerous, so it must run in a sandbox: a separate process or container with a time limit, no secrets, limited memory and often no network.
| Sandbox control | Why |
|---|---|
| Separate process or container | A crash or attack cannot reach the main app |
| Time and memory limit | Stops infinite loops |
| No access to secrets | Nothing valuable to steal |
| Network off by default | Prevents data leaving |
| Capture output only | The agent gets results, not control |
- Medium: File Operations and External Services
File tools let the agent read and write documents. Confine them to one working folder, resolve paths before checking them (so ../ tricks fail), and prefer new files over overwriting existing ones.
External services such as email, calendars and ticket systems cause real side effects that cannot be undone. Use an approval gate: the agent can prepare an email, but a human must approve sending it.
Golden rule: Reading is cheap and reversible. Writing, sending and paying are not. Put the strongest guards on the actions that cannot be undone.
- Advanced: Designing Safe Tool Sets
| Principle | How to apply it |
|---|---|
| Least privilege | Give each tool the smallest permission that works, such as read-only access |
| Validate in code | Check names, arguments and values before running anything |
| Sandbox risky tools | Run code and untrusted work in isolation |
| Approve irreversible actions | Human approval for sending, paying and deleting |
| Limit volume | Row limits, file size limits and call-rate limits |
| Log everything | Record every tool call for debugging and audits |
- Visual Explanation: Six Tools and the Guard Each One Needs
The figure groups the tool kinds by risk, then shows the four checks implemented in the code below.
Click to see why code checks are not enough aloneCompare ▼
Part 1 shows that the guard grows with the risk. Part 2 maps four checks to the code. Open the bar to see why layered defenses matter.
- Python Implementation: Safe Database, File, Code, Search and Email Tools
This script builds five tools with safety checks: a read-only database query, a folder-confined file tool, a code runner in a separate process with a time limit, a web search stand-in, and an email tool that needs approval.
import os, sqlite3, subprocess, sys, tempfile # 1. Database tool: read-only by design (a single SELECT only)db = sqlite3.connect(":memory:")db.execute("CREATE TABLE orders (id INTEGER, customer TEXT, total REAL)")db.executemany("INSERT INTO orders VALUES (?, ?, ?)", [(1, "Ana", 120.5), (2, "Ben", 80.0), (3, "Ana", 45.25)]) def query_database(sql): cleaned = sql.strip().rstrip(";") if not cleaned.lower().startswith("select") or ";" in cleaned: return {"error": "only a single SELECT is allowed"} return {"rows": db.execute(cleaned).fetchall()} print(query_database("SELECT customer, SUM(total) FROM orders GROUP BY customer"))print(query_database("DROP TABLE orders")) # 2. File tool: confined to one folderWORKDIR = os.path.realpath(tempfile.mkdtemp()) def file_tool(action, name, text=""): path = os.path.realpath(os.path.join(WORKDIR, name)) if not path.startswith(WORKDIR + os.sep): return {"error": "path is outside the allowed folder"} if action == "write": with open(path, "w") as f: f.write(text) return {"ok": True} if action == "read": with open(path) as f: return {"text": f.read()} return {"error": "unknown action"} print(file_tool("write", "notes.txt", "meeting at 5"))print(file_tool("read", "notes.txt"))print(file_tool("read", "../../etc/passwd")) # 3. Code execution tool: separate process with a time limitdef run_code(code): proc = subprocess.run([sys.executable, "-I", "-c", code], capture_output=True, text=True, timeout=3) last_error = proc.stderr.strip().splitlines()[-1] if proc.stderr.strip() else "" return {"stdout": proc.stdout.strip(), "error": last_error} print(run_code("print(sum(range(1, 11)))"))print(run_code("print(1 / 0)")) # 4. Web search and an external service that needs approvaldef web_search(query): pages = {"python": "Python is a popular programming language.", "rag": "RAG combines retrieval with generation."} return {"results": [text for key, text in pages.items() if key in query.lower()] or ["no results"]} def send_email(to, body, approved=False): if not approved: return {"status": "blocked", "reason": "a human must approve outgoing email"} return {"status": "sent", "to": to} print(web_search("what is RAG"))print(send_email("ana@example.com", "Report ready"))print(send_email("ana@example.com", "Report ready", approved=True))Every dangerous request gets a clear error instead of an action: the DROP TABLE, the path escape and the unapproved email. The normal requests work as expected. These errors are returned to the model so it can react.
Knowledge Check
Key Points
The Big Picture
More power in the tool → stronger guards around it
With safe tools your agent can do real work. Next, it needs to remember things.
Up Next: Agents forget everything between runs unless you give them memory. In Agent Memory you will learn short-term, long-term, semantic and persistent memory.