API, Browser, Database, File and Business Tools

Each kind of system fails and leaks in its own way. Choose the narrowest door that does the job.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

Prefer a purpose-built API over a database query, and a database query or API over driving a screen. Wrap every system in a narrow tool that adds identity, validation, limits and a clean result. Read access should be restricted by the system itself, file access confined to a workspace, and outward actions such as email previewed and approved.

What you will learn: choosing an integration method, secure API calls, database and file tools, browser automation, and tools for email, calendars, customer records and tickets.
Prerequisites: Agent Tools, Function Calling and Tool Registries and Tool Permissions, Approvals and Abuse Risks.

Beginner Choose the door

Which kind of integration?

Task-specific service callnarrow, validated, easiest to test
General API behind a wrapperchoose a few operations
Restricted database or file accessflexible reading with hard limits
Browser or desktop controllast resort for systems without interfaces
Shell or free codeonly inside a sandbox
Moving down adds reach and removes predictability.

Standards such as the Model Context Protocol can package integrations for reuse, but they do not make an integration safe by themselves. The server behind the protocol still needs the controls on this page.

What every wrapper adds

ConcernResponsibility of the wrapper
IdentityAttach credentials for the right user, hidden from the model
InputValidate and translate to the system's format
LimitsRows, size, time, rate, amount
OutputSelect fields, convert units, mark source and time
ErrorsMap to the classes in Reliable Tool Execution and Error Recovery
AuditRecord who did what

APIs

  • Allow listed operations only. Do not give the model a generic "send any request" tool.
  • Fix the base address in configuration; the model supplies parameters, not hosts.
  • Encode parameters with your HTTP library instead of joining strings.
  • Use scoped, short-lived tokens and rotate secrets.
  • Handle pagination deliberately, with a maximum.
  • Pin the API version and test against the provider's sandbox.
  • Verify incoming webhooks by signature and expect duplicates.

An OpenAPI description can generate a first draft of tools. Review it by hand: merge low-level endpoints into useful tasks, remove administrative operations and rewrite descriptions for a reader choosing in a few seconds.

Write the integration down first

Before any code, answer a few questions on one page. It takes an hour and often removes half the scope.

  • Which user tasks need this system, and how often?
  • Which records are read, and which are changed?
  • Whose identity and permissions apply?
  • What is the worst plausible mistake, and can it be undone?
  • What are the provider's limits, terms and data location rules?
  • How will someone switch it off, and what happens to work in progress?

The answers become your tool list, your limits and your first tests. They also give security and data owners something concrete to review.

Intermediate Data and files

When the other side pushes back

Providers limit request rates, fail briefly and sometimes answer slowly. Read the limit information the provider returns and wait as instructed rather than retrying at once. Share one rate budget across all tasks that use the same credential, or a busy agent can block every colleague. Set a time limit shorter than the task's remaining time, and treat a timeout on a write as unknown until you have looked up the result. Cache stable reference data for a short, stated period, and include its age so that the agent does not present old values as current. When a service is down, say so plainly and offer what can still be done.

Database tools

DesignFlexibilityRisk
Fixed parameterized queriesLowLowest; start here
Approved metrics through a semantic layerMediumControlled definitions, see Semantic Layers and Business Metrics for AI
Model-written read queriesHighWrong answers, heavy queries, data exposure
Model-written changesVery highAvoid; offer specific write tools

If the model writes queries, do not rely on checking the text for forbidden words. Let the database enforce the limits: a read-only account, access only to approved views, row-level security, a statement timeout and a row limit. This example uses SQLite's authorizer, which is consulted while a statement is compiled.

"""Let the database itself refuse anything except limited reading."""
import sqlite3

db = sqlite3.connect(":memory:", isolation_level=None)
db.executescript("""
CREATE TABLE orders(id TEXT, status TEXT, total INT);
CREATE TABLE staff(name TEXT, salary INT);
INSERT INTO orders VALUES ('A1','open',40), ('A2','paid',90),
                          ('A3','open',15);
INSERT INTO staff VALUES ('Li', 90000);
""")

ALLOWED = {"orders": {"id", "status", "total"}}

def authorizer(action, arg1, arg2, database, source):
    if action == sqlite3.SQLITE_SELECT:
        return sqlite3.SQLITE_OK
    if action == sqlite3.SQLITE_READ and arg1 in ALLOWED:
        if arg2 == "" or arg2 in ALLOWED[arg1]:    # "" means no column
            return sqlite3.SQLITE_OK
    if action == sqlite3.SQLITE_FUNCTION and arg2 in ("count", "sum"):
        return sqlite3.SQLITE_OK
    return sqlite3.SQLITE_DENY

db.set_authorizer(authorizer)

def query_tool(sql, max_rows=2):
    try:
        cursor = db.execute(sql)          # one statement only
        rows = cursor.fetchmany(max_rows + 1)
    except (sqlite3.Error, sqlite3.Warning) as error:
        return f"refused: {error}"
    more = " (more rows exist)" if len(rows) > max_rows else ""
    return f"{rows[:max_rows]}{more}"

for sql in ["SELECT id, total FROM orders WHERE status='open'",
            "SELECT id FROM orders",
            "SELECT sum(total) FROM orders",
            "SELECT name, salary FROM staff",
            "DELETE FROM orders",
            "SELECT id FROM orders; DROP TABLE orders",
            "SELECT randomblob(100000000)"]:
    print(sql, "\n  ->", query_tool(sql))

Output:

SELECT id, total FROM orders WHERE status='open' 
  -> [('A1', 40), ('A3', 15)]
SELECT id FROM orders 
  -> [('A1',), ('A2',)] (more rows exist)
SELECT sum(total) FROM orders 
  -> [(145,)]
SELECT name, salary FROM staff 
  -> refused: access to staff.name is prohibited
DELETE FROM orders 
  -> refused: not authorized
SELECT id FROM orders; DROP TABLE orders 
  -> refused: You can only execute one statement at a time.
SELECT randomblob(100000000) 
  -> refused: not authorized to use function: randomblob

Reading approved columns worked, long results were marked as partial, and reading salaries, deleting, stacking statements and calling an unlisted function were refused. This is a demonstration, not a complete defense. It sets no time limit, so an expensive join over allowed tables could still run for a long time; add a progress handler or timeout, and on server databases use roles and statement timeouts. A query can also be permitted yet wrong. Safe SQL, Permissions and Evaluation covers checking correctness.

Present query results honestly

A result is more than rows. Return the column names, units, the filters actually applied, the time the data was read and whether rows were cut off. Distinguish "no matching rows" from "query refused" and from "source unavailable", since a model may otherwise report zero sales when it simply lacked permission. Compute totals in the database rather than asking the model to add a long list. Keep personal columns out of the view altogether unless the task needs them, and mask them where partial values are enough.

File and document tools

File names supplied by a model are untrusted. Sequences such as ../, absolute paths and symbolic links can all lead outside the intended folder.

"""Keep a file tool inside one workspace folder."""
import os
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as top:
    root = Path(top, "workspace")
    root.mkdir()
    (root / "notes.txt").write_text("meeting at ten")
    (root / "big.log").write_text("x" * 5000)
    Path(top, "secret.txt").write_text("api key")
    os.symlink(Path(top, "secret.txt"), root / "shortcut.txt")

    def read_file(name, limit=1000):
        base = root.resolve()
        target = (base / name).resolve()      # follows links and '..'
        if not target.is_relative_to(base):
            return "refused: outside the workspace"
        if not target.is_file():
            return "refused: no such file"
        with target.open(encoding="utf-8") as handle:
            text = handle.read(limit + 1)
        if len(text) > limit:
            return f"{len(text[:limit])} characters returned, file is longer"
        return text

    for name in ["notes.txt", "../secret.txt", "shortcut.txt",
                 "/etc/hostname", "sub/../notes.txt", "big.log",
                 "missing.txt"]:
        print(f"{name:<18} {read_file(name)}")

Output:

notes.txt          meeting at ten
../secret.txt      refused: outside the workspace
shortcut.txt       refused: outside the workspace
/etc/hostname      refused: outside the workspace
sub/../notes.txt   meeting at ten
big.log            1000 characters returned, file is longer
missing.txt        refused: no such file

The tool resolves the real location first and then checks that it lies inside the workspace, which catches the link as well as the dots. It also bounds how much is read. A program that can change the folder at the same time could still swap a file for a link between the check and the open, so for untrusted multi-user cases rely on operating-system isolation: a separate container or virtual disk per task.

Document concernMeasure
Large filesPage or section reads; search within the file
Parsing untrusted formatsMaintained parsers, run in isolation, size limits
ArchivesLimit expanded size and check every member path
Hidden instructionsTreat contents as data, not commands
Overwrites and deletionWrite new versions; require confirmation to remove
PermissionsCheck the user's access to each document
Expert Screens and business systems

Browser automation as a tool

When a system has no suitable interface, an agent can operate it through a browser. Libraries such as Playwright drive pages by roles, labels and text, which survives layout changes better than screen coordinates.

  • Use a clean, isolated profile per task, without personal cookies or saved passwords.
  • Restrict sites the browser may visit.
  • Let trusted code sign in; keep secrets out of screenshots and context.
  • Confirm before irreversible clicks.
  • Verify the outcome by reading the resulting page or record.
  • Respect the site's terms and do not try to defeat bot checks.

Page content can contain instructions written to mislead agents, including text people cannot see. Browser and Computer-Use Agents and Visual Grounding and Reliable UI Automation go further.

Email and calendar tools

ActionDesign advice
Search mailScope to the user; return subjects and short extracts first
Draft mailSafe default: create a draft for the person to review
Send mailShow recipients and full content; approval; sending limits
Find meeting timesReturn free slots, not other people's event details
Create eventExplicit time zone; confirm before inviting others
Cancel or changeIdentify the exact event; confirm effect on attendees

Resolve people to addresses with a directory lookup and show the result. A plausible but wrong recipient is one of the easiest serious mistakes to make.

Customer records and tickets

  • Search then act by identifier, never by name alone.
  • Offer specific updates, such as adding a note or changing priority.
  • Check record versions so that a colleague's change is not overwritten.
  • Prevent duplicate tickets by searching for an open one and using an operation key.
  • Label agent-written content so that readers know its origin.
  • Keep workflow rules in the system of record; do not bypass them with direct database writes.

Whose account does the action use?

For mail, calendars and customer systems, prefer access delegated by the signed-in user, limited to the permissions the task needs, so that the system's own rules still apply. A shared service account is simpler to set up and far harder to contain: it often sees more than any one user, and its actions are difficult to attribute. If you must use one, check the requesting user's rights inside your tool before every call and record both identities. Provide a way for users to disconnect the integration, and remove stored tokens when they do. See Agent Identity, Authorization and Secrets.

Systems without good interfaces

For older systems, consider a small service that exposes a few safe operations and hides the awkward protocol. It can be tested once and shared. If only a screen exists, measure failure rates honestly and keep a manual fallback. See ERP, CRM, API and Event Integration.

Add an integration in order

StepDone when
Name the tasksA short list of actions with an owner
Check accessNarrow credentials issued for a test environment
Read firstRead tools pass tests and review
Add writesLimits, keys and approvals in place
Rehearse failureTimeouts, duplicates and bad data handled
ObserveCalls traced and alerts owned
Release graduallyA small group first, with a switch to disable
Illustrative example: replacing screen clicks

An agent updates an old purchasing system through its web pages and fails whenever a pop-up appears. The team learns that the same system accepts a nightly file import. They build a tool that validates a change and adds it to the file, with a status tool for the result. It is slower to take effect but far more dependable.

Keep behavior consistent across tools

An agent that uses six systems meets six ideas about dates, identifiers, paging and errors. Agree house rules and apply them in the wrappers: one date format with offsets, money as whole minor units plus currency, identifiers always returned with their type, the same fields for partial results and the same small set of error classes. The model then learns one pattern, and your tests can check it across every tool at once.

Name an owner for each integration. Providers change fields, deprecate versions and adjust limits, and someone has to notice. A scheduled contract check against a test account will often warn you before users do.

Verify the outcome, not the reply

A success code says the request was accepted, which may differ from the work being done. Where the system processes changes later, return the pending state and give the agent a status tool. After important writes, read the record back and compare the fields that matter. In browser flows, look for the confirmation reference and then confirm it in the record list. Report to the user what was verified, for example "ticket 481 exists and is assigned to the billing queue", instead of "done". When verification is impossible, say that too, so that a person knows to check.

Content from outside is untrusted

Emails, ticket comments, web pages, shared documents and even record fields can be written by people who want to steer your agent. A message might say to forward the inbox or change a bank detail. Mark such content as data in the context, but do not rely on the label. Limit what the agent can do after reading it: no sending to new recipients without approval, no secrets within reach and no tool that moves data to arbitrary places. Prompt Injection Attacks and Defenses explains why this combination of private data, untrusted content and an outward channel is the one to break.

Is the integration earning its keep?

Review each one after a few weeks. How often is it used, which tasks succeed because of it, how often does it fail and how much support does it need? Retire tools that nobody uses, since each one still holds credentials and adds choices for the model.

Common mistakes

  • A generic request, query or shell tool with broad credentials.
  • Filtering query text instead of restricting the database.
  • Joining file paths without resolving them.
  • Reusing a person's everyday browser session.
  • Sending messages without a preview.
  • Writing directly to a system's tables.
  • Assuming one page of results is complete.

Checklist

  • The narrowest practical integration method is used.
  • Credentials are scoped and hidden from the model.
  • Databases enforce read limits, timeouts and row limits.
  • File access is confined and size limited.
  • Browsers run isolated with restricted sites.
  • Outward messages are previewed.
  • Record updates check versions.
  • Each integration has an owner and a disable switch.

Frequently asked questions

Is an MCP server safer than a direct integration?

Not automatically. It standardizes the connection. Safety depends on the server's code, credentials, permissions and your decision to trust it.

May an agent write SQL?

For analysis it can, behind a read-only role, approved views, limits and checks. Prefer fixed queries or approved metrics where answers must be dependable.

When is browser control justified?

When no interface exists, the task is valuable and errors can be detected and contained. Revisit the choice if an interface appears.

How do I test integrations safely?

Use provider sandboxes or local doubles with realistic errors, separate test credentials and data that is not real personal information.

References and further reading

Next steps