Velamuvi AIAcademy

Lesson 2 of 6 · Safety

Least-Privilege Tools

Design least-privilege tools for AI agents: narrow tools, permission checks, user identity from the session, scoped credentials and the confused deputy problem.

  • 6 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Apply the principle of least privilege to agent tools
  • Prefer narrow tools over general ones like run_sql
  • Enforce permissions, limits and allowlists inside the tool, not the prompt
  • Take the user's identity from the session, never from the model
  • Explain the confused deputy problem

Give agents only what they need

The tools you give an agent define the worst thing it can do. A model can be confused, persuaded or tricked; a tool that can't delete the database is a guarantee no prompt can match.

Narrow tools beat general tools

General tools are tempting because one tool covers many needs:

General toolNarrow alternatives
run_sql(query)get_my_orders(), get_order(order_id)
send_email(to, subject, body)email_customer_about_order(order_id, message)
http_request(url, method, body)get_weather(city), track_parcel(tracking_id)
run_shell(command)run_tests(), format_code(path)

With run_sql, any successful manipulation of the model can read or change every record. With get_order(order_id), the worst case is reading one order, and the tool itself can check whether that order belongs to the user.

Checks belong inside the tool

Here's a refund tool built for least privilege. Look at what it checks, and where the user's identity comes from:

Try it yourselfPython
# Least privilege: narrow tools that check permissions themselves, instead of trusting the model.
ORDERS = {"A-100": {"owner": "u-1", "paid": 60.0, "refunded": 0.0},
          "B-200": {"owner": "u-2", "paid": 250.0, "refunded": 0.0},
          "C-300": {"owner": "u-1", "paid": 300.0, "refunded": 0.0}}
AUTO_LIMIT = 100.0              # bigger refunds need a person

class Denied(Exception):
    pass

def refund(user_id, order_id, amount):
    """The ONLY refund tool the agent has. user_id comes from the login session, never from the model."""
    order = ORDERS.get(order_id)
    if order is None or order["owner"] != user_id:       # same error either way: don't reveal other orders
        raise Denied("no such order for this customer")
    if amount <= 0 or amount > order["paid"] - order["refunded"]:
        raise Denied("amount must be positive and no more than what's left to refund")
    if amount > AUTO_LIMIT:
        raise Denied(f"over {AUTO_LIMIT:.0f} EUR: sent to a person for approval")
    order["refunded"] += amount
    return f"refunded {amount:.2f} EUR on {order_id}"

# Requests the model might produce while helping customer u-1 (some after reading a tricky message)
attempts = [("A-100", 60.0), ("A-100", 10.0), ("B-200", 250.0), ("C-300", 150.0), ("A-100", -5.0)]
session_user = "u-1"
for order_id, amount in attempts:
    try:
        print("OK     ", refund(session_user, order_id, amount))
    except Denied as e:
        print("DENIED ", f"{order_id} {amount}: {e}")

# Compare with a "convenient" general tool: one call could read or change ANY customer's data
def run_sql(query):
    return f"(would run on the whole database) {query}"
print("\nWith run_sql the model could send:", run_sql("UPDATE orders SET refunded = paid"))

Every rule is enforced by the tool, whatever the model asks for:

  • Ownership: customer u-1 can't refund customer u-2's order, even if a message convinced the model to try. The error doesn't even confirm that order B-200 exists.
  • Valid amounts: no negative refunds, no refunding more than was paid, no refunding twice.
  • Limits: anything over 100 euros goes to a person instead of running.
  • Identity from the session: user_id comes from the logged-in session, never from the model's arguments. If the model could pass user_id, an attacker could simply ask it to use someone else's.

Compare the run_sql line at the end: one manipulated call, and every order is refunded.

Limits, allowlists and scoped credentials

Beyond narrow tools, a few more layers keep the blast radius small:

  • Allowlists: emails only to approved domains, web requests only to approved hosts, files only in one folder.
  • Limits: maximum amounts, maximum items per call (no “delete 10,000 files”), and rate limits on how often a tool can be called.
  • Scoped credentials: API keys and database accounts with the narrowest permissions available, such as read-only access, one project, or one mailbox.
  • Short-lived credentials: tokens that expire after the task, so a leaked token is soon useless.
  • Separate agents for separate privileges: a reading agent and a writing agent, rather than one with both.

Common mistakes

Practice exercise

Add a recipient allowlist to an email tool, so the agent can only send to approved domains whatever the model asks for.

Your solutionPython
ALLOWED_DOMAINS = {"velamuvi-shop.example", "partner.example"}
recipients = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]

# The send_email tool may only send to addresses whose domain (the part after the last @)
# is exactly one of ALLOWED_DOMAINS. For each recipient print "send" or "block".
Knowledge check

Where should a refund tool get the customer's identity from?

Summary

  • Least privilege: give agents only the tools, actions and credentials their task needs.
  • Prefer narrow tools (get_order) to general ones (run_sql).
  • Enforce ownership, valid values and limits inside the tool, and take identity from the session.
  • Use allowlists, scoped and short-lived credentials, and separate agents for separate privileges.
  • Avoid the confused deputy: check permissions as the end user.

Next: sandboxing.

Finished reading? Tick it off to track your progress.