Agents with External Tools

Connect agents to the outside world: APIs, databases, web search, code execution, file operations and external services, with safe designs that limit what each tool can do.

30 minIntermediateCode Examples

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.

  1. 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 kindWhat it gives the agentMain risk
APIsLive data and services such as weather or paymentsLeaked keys, runaway calls
DatabasesBusiness dataData leaks, destructive queries
Web searchFresh public informationWrong or hostile content
Code executionExact math, data work, plotsRunning harmful code
File operationsReading and writing documentsReading or overwriting the wrong files
External servicesEmail, calendar, tickets, chatReal-world side effects

Design rule: The more a tool can change in the world, the more checks it needs.

  1. 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.

  1. 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 controlWhy
Separate process or containerA crash or attack cannot reach the main app
Time and memory limitStops infinite loops
No access to secretsNothing valuable to steal
Network off by defaultPrevents data leaving
Capture output onlyThe agent gets results, not control

  1. 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.

  1. Advanced: Designing Safe Tool Sets

PrincipleHow to apply it
Least privilegeGive each tool the smallest permission that works, such as read-only access
Validate in codeCheck names, arguments and values before running anything
Sandbox risky toolsRun code and untrusted work in isolation
Approve irreversible actionsHuman approval for sending, paying and deleting
Limit volumeRow limits, file size limits and call-rate limits
Log everythingRecord every tool call for debugging and audits
Credentials
Never put API keys or passwords in prompts or tool descriptions. Keep them in environment variables on the server, and give the agent a separate low-privilege key.

  1. 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.

Part 1 · Six Tool Kinds and Their GuardMatch the guard to the risk
Read toolsAPIs, database, search
Return only needed fields
↓
Read-only access, row limits
↓
Low risk with limits
Compute toolsCode execution
Separate process, time limit
↓
No secrets, network off
↓
Sandboxed
Action toolsFiles, email, services
Confined to one folder
↓
Human approval for sending
↓
Highest guard
Part 2 · Four Checks in the CodeSeen in the script
Only SELECT
Database
DROP TABLE is rejected.
Folder fence
Files
A path outside the folder is rejected.
Time limit
Code
Runs in a separate process.
Approval
Email
Blocked until a human approves.
Click to see why code checks are not enough aloneCompare ▼
A check can have gaps, so defense comes in layers: a read-only database account, a sandbox for code, a folder with limited rights, and human approval for irreversible actions.

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.

  1. 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.

external_tools.pyPython 3.10+ · standard library only
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))
EXPECTED OUTPUT (your numbers may differ slightly)
{'rows': [('Ana', 165.75), ('Ben', 80.0)]}
{'error': 'only a single SELECT is allowed'}
{'ok': True}
{'text': 'meeting at 5'}
{'error': 'path is outside the allowed folder'}
{'stdout': '55', 'error': ''}
{'stdout': '', 'error': 'ZeroDivisionError: division by zero'}
{'results': ['RAG combines retrieval with generation.']}
{'status': 'blocked', 'reason': 'a human must approve outgoing email'}
{'status': 'sent', 'to': 'ana@example.com'}

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

Question 1: Why should file tools be confined to one folder?
Question 2: What is the safest way to handle an agent sending email?

Key Points

✓External tools give agents fresh data, exact computation and the power to act.
✓Database tools should be read-only, limited and run by a low-privilege account.
✓Treat web search results as untrusted and return short snippets with sources.
✓Run code execution in a sandbox with a time limit, no secrets and often no network.
✓Confine file tools to one folder and require approval for irreversible actions.
✓Apply least privilege, validate in code, limit volume and log every call.

The Big Picture

External Tools in One Line

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.